{"code":"# ruff: noqa\n# Configuration file for the Sphinx documentation builder.\n#\n# For the full list of built-in configuration values, see the documentation:\n# https:\/\/www.sphinx-doc.org\/en\/master\/usage\/configuration.html\n\n# -- Project information -----------------------------------------------------\n# https:\/\/www.sphinx-doc.org\/en\/master\/usage\/configuration.html#project-information\n\nproject = \"Algorand Python\"\ncopyright = \"2024, Algorand Foundation\" # noqa: A001\nauthor = \"Algorand Foundation\"\n\n# -- General configuration ---------------------------------------------------\n# https:\/\/www.sphinx-doc.org\/en\/master\/usage\/configuration.html#general-configuration\n\nextensions = [\n \"sphinx.ext.githubpages\",\n \"sphinx.ext.intersphinx\",\n \"sphinx_copybutton\",\n \"myst_parser\",\n \"autodoc2\",\n]\n\ntemplates_path = [\"_templates\"]\nexclude_patterns = [\"_build\", \"Thumbs.db\", \".DS_Store\", \"architecture-decisions\/*.md\"]\n\nintersphinx_mapping = {\n \"python\": (\"https:\/\/docs.python.org\/3\", None),\n}\n\n# warning exclusions\nsuppress_warnings = [\n \"myst.xref_missing\",\n \"autodoc2.dup_item\",\n]\nnitpick_ignore = [\n (\"py:class\", \"algopy.arc4.AllowedOnCompletes\"),\n]\nnitpick_ignore_regex = [\n (\"py:class\", r\"algopy.*\\._.*\"),\n]\n\n# -- Options for HTML output -------------------------------------------------\n# https:\/\/www.sphinx-doc.org\/en\/master\/usage\/configuration.html#options-for-html-output\n\nhtml_theme = \"furo\"\nhtml_static_path = [\"_static\"]\nhtml_css_files = [\n \"custom.css\",\n]\n\npython_maximum_signature_line_length = 80\n\n# -- Options for myst ---\nmyst_enable_extensions = [\n \"colon_fence\",\n \"fieldlist\",\n]\n\n# -- Options for autodoc2 ---\nautodoc2_packages = [\n {\n \"path\": \".\/algopy-stubs\",\n \"module\": \"algopy\",\n \"auto_mode\": False,\n },\n]\nautodoc2_docstring_parser_regexes = [\n # this will render all docstrings as Markdown\n (r\".*\", \"myst\"),\n]\nautodoc2_hidden_objects = [\n \"undoc\",\n]\nautodoc2_hidden_regexes = [\n r\".*\\.__subclasshook__\", # inherited from Protocol\n]\nautodoc2_class_inheritance = False\nautodoc2_module_all_regexes = [r\"algopy.*\"]\nautodoc2_render_plugin = \"myst\"\nautodoc2_sort_names = True\nautodoc2_index_template = None\nautodoc2_docstrings = \"all\"\n","repo_name":"algorandfoundation\/puya","path":"docs\/conf.py","language":"Python","license":"NOASSERTION","size":2216} {"code":"","repo_name":"algorandfoundation\/puya","path":"examples\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"# WARNING: This code is provided for example only. Do NOT deploy to mainnet.\n\nfrom algopy import (\n Account,\n ARC4Contract,\n Asset,\n Global,\n Txn,\n UInt64,\n arc4,\n gtxn,\n itxn,\n op,\n subroutine,\n)\n\n# Total supply of the pool tokens\nTOTAL_SUPPLY = 10_000_000_000\n# scale helps with precision when doing computation for\n# the number of tokens to transfer\nSCALE = 1000\n# Fee for swaps, 5 represents 0.5% ((fee \/ scale)*100)\nFEE = 5\nFACTOR = SCALE - FEE\n\n\nclass ConstantProductAMM(ARC4Contract):\n def __init__(self) -> None:\n # init runs whenever the txn's app ID is zero, and runs first\n # so if we have multiple create methods, this can contain common code.\n\n # The asset id of asset A\n self.asset_a = Asset()\n # The asset id of asset B\n self.asset_b = Asset()\n # The current governor of this contract, allowed to do admin type actions\n self.governor = Txn.sender\n # The asset id of the Pool Token, used to track share of pool the holder may recover\n self.pool_token = Asset()\n # The ratio between assets (A*Scale\/B)\n self.ratio = UInt64(0)\n\n @arc4.abimethod()\n def set_governor(self, new_governor: Account) -> None:\n \"\"\"sets the governor of the contract, may only be called by the current governor\"\"\"\n self._check_is_governor()\n self.governor = new_governor\n\n @arc4.abimethod()\n def bootstrap(self, seed: gtxn.PaymentTransaction, a_asset: Asset, b_asset: Asset) -> UInt64:\n \"\"\"bootstraps the contract by opting into the assets and creating the pool token.\n\n Note this method will fail if it is attempted more than once on the same contract\n since the assets and pool token application state values are marked as static and\n cannot be overridden.\n\n Args:\n seed: Initial Payment transaction to the app account so it can opt in to assets\n and create pool token.\n a_asset: One of the two assets this pool should allow swapping between.\n b_asset: The other of the two assets this pool should allow swapping between.\n\n Returns:\n The asset id of the pool token created.\n \"\"\"\n assert not self.pool_token, \"application has already been bootstrapped\"\n self._check_is_governor()\n assert Global.group_size == 2, \"group size not 2\"\n assert seed.receiver == Global.current_application_address, \"receiver not app address\"\n\n assert seed.amount >= 300_000, \"amount minimum not met\" # 0.3 Algos\n assert a_asset.id < b_asset.id, \"asset a must be less than asset b\"\n self.asset_a = a_asset\n self.asset_b = b_asset\n self.pool_token = self._create_pool_token()\n\n self._do_opt_in(self.asset_a)\n self._do_opt_in(self.asset_b)\n return self.pool_token.id\n\n @arc4.abimethod(\n default_args={\n \"pool_asset\": \"pool_token\",\n \"a_asset\": \"asset_a\",\n \"b_asset\": \"asset_b\",\n },\n )\n def mint(\n self,\n a_xfer: gtxn.AssetTransferTransaction,\n b_xfer: gtxn.AssetTransferTransaction,\n pool_asset: Asset,\n a_asset: Asset,\n b_asset: Asset,\n ) -> None:\n \"\"\"mint pool tokens given some amount of asset A and asset B.\n\n Given some amount of Asset A and Asset B in the transfers, mint some number of pool\n tokens commensurate with the pools current balance and circulating supply of\n pool tokens.\n\n Args:\n a_xfer: Asset Transfer Transaction of asset A as a deposit to the pool in\n exchange for pool tokens.\n b_xfer: Asset Transfer Transaction of asset B as a deposit to the pool in\n exchange for pool tokens.\n pool_asset: The asset ID of the pool token so that we may distribute it.\n a_asset: The asset ID of the Asset A so that we may inspect our balance.\n b_asset: The asset ID of the Asset B so that we may inspect our balance.\n \"\"\"\n self._check_bootstrapped()\n\n # well-formed mint\n assert pool_asset == self.pool_token, \"asset pool incorrect\"\n assert a_asset == self.asset_a, \"asset a incorrect\"\n assert b_asset == self.asset_b, \"asset b incorrect\"\n assert a_xfer.sender == Txn.sender, \"sender invalid\"\n assert b_xfer.sender == Txn.sender, \"sender invalid\"\n\n # valid asset a xfer\n assert (\n a_xfer.asset_receiver == Global.current_application_address\n ), \"receiver not app address\"\n assert a_xfer.xfer_asset == self.asset_a, \"asset a incorrect\"\n assert a_xfer.asset_amount > 0, \"amount minimum not met\"\n\n # valid asset b xfer\n assert (\n b_xfer.asset_receiver == Global.current_application_address\n ), \"receiver not app address\"\n assert b_xfer.xfer_asset == self.asset_b, \"asset b incorrect\"\n assert b_xfer.asset_amount > 0, \"amount minimum not met\"\n\n to_mint = tokens_to_mint(\n pool_balance=self._current_pool_balance(),\n a_balance=self._current_a_balance(),\n b_balance=self._current_b_balance(),\n a_amount=a_xfer.asset_amount,\n b_amount=b_xfer.asset_amount,\n )\n assert to_mint > 0, \"send amount too low\"\n\n # mint tokens\n do_asset_transfer(receiver=Txn.sender, asset=self.pool_token, amount=to_mint)\n self._update_ratio()\n\n @arc4.abimethod(\n default_args={\n \"pool_asset\": \"pool_token\",\n \"a_asset\": \"asset_a\",\n \"b_asset\": \"asset_b\",\n },\n )\n def burn(\n self,\n pool_xfer: gtxn.AssetTransferTransaction,\n pool_asset: Asset,\n a_asset: Asset,\n b_asset: Asset,\n ) -> None:\n \"\"\"burn pool tokens to get back some amount of asset A and asset B\n\n Args:\n pool_xfer: Asset Transfer Transaction of the pool token for the amount the\n sender wishes to redeem\n pool_asset: Asset ID of the pool token so we may inspect balance.\n a_asset: Asset ID of Asset A so we may inspect balance and distribute it\n b_asset: Asset ID of Asset B so we may inspect balance and distribute it\n \"\"\"\n self._check_bootstrapped()\n\n assert pool_asset == self.pool_token, \"asset pool incorrect\"\n assert a_asset == self.asset_a, \"asset a incorrect\"\n assert b_asset == self.asset_b, \"asset b incorrect\"\n\n assert (\n pool_xfer.asset_receiver == Global.current_application_address\n ), \"receiver not app address\"\n assert pool_xfer.asset_amount > 0, \"amount minimum not met\"\n assert pool_xfer.xfer_asset == self.pool_token, \"asset pool incorrect\"\n assert pool_xfer.sender == Txn.sender, \"sender invalid\"\n\n # Get the total number of tokens issued\n # !important: this happens prior to receiving the current axfer of pool tokens\n pool_balance = self._current_pool_balance()\n a_amt = tokens_to_burn(\n pool_balance=pool_balance,\n supply=self._current_a_balance(),\n amount=pool_xfer.asset_amount,\n )\n b_amt = tokens_to_burn(\n pool_balance=pool_balance,\n supply=self._current_b_balance(),\n amount=pool_xfer.asset_amount,\n )\n\n # Send back commensurate amt of a\n do_asset_transfer(receiver=Txn.sender, asset=self.asset_a, amount=a_amt)\n\n # Send back commensurate amt of b\n do_asset_transfer(receiver=Txn.sender, asset=self.asset_b, amount=b_amt)\n self._update_ratio()\n\n @arc4.abimethod(\n default_args={\n \"a_asset\": \"asset_a\",\n \"b_asset\": \"asset_b\",\n },\n )\n def swap(\n self,\n swap_xfer: gtxn.AssetTransferTransaction,\n a_asset: Asset,\n b_asset: Asset,\n ) -> None:\n \"\"\"Swap some amount of either asset A or asset B for the other\n\n Args:\n swap_xfer: Asset Transfer Transaction of either Asset A or Asset B\n a_asset: Asset ID of asset A so we may inspect balance and possibly transfer it\n b_asset: Asset ID of asset B so we may inspect balance and possibly transfer it\n \"\"\"\n self._check_bootstrapped()\n\n assert a_asset == self.asset_a, \"asset a incorrect\"\n assert b_asset == self.asset_b, \"asset b incorrect\"\n\n assert swap_xfer.asset_amount > 0, \"amount minimum not met\"\n assert swap_xfer.sender == Txn.sender, \"sender invalid\"\n\n match swap_xfer.xfer_asset:\n case self.asset_a:\n in_supply = self._current_b_balance()\n out_supply = self._current_a_balance()\n out_asset = self.asset_a\n case self.asset_b:\n in_supply = self._current_a_balance()\n out_supply = self._current_b_balance()\n out_asset = self.asset_b\n case _:\n assert False, \"asset id incorrect\"\n\n to_swap = tokens_to_swap(\n in_amount=swap_xfer.asset_amount, in_supply=in_supply, out_supply=out_supply\n )\n assert to_swap > 0, \"send amount too low\"\n\n do_asset_transfer(receiver=Txn.sender, asset=out_asset, amount=to_swap)\n self._update_ratio()\n\n @subroutine\n def _check_bootstrapped(self) -> None:\n assert self.pool_token, \"bootstrap method needs to be called first\"\n\n @subroutine\n def _update_ratio(self) -> None:\n a_balance = self._current_a_balance()\n b_balance = self._current_b_balance()\n\n self.ratio = a_balance * SCALE \/\/ b_balance\n\n @subroutine\n def _check_is_governor(self) -> None:\n assert (\n Txn.sender == self.governor\n ), \"Only the account set in global_state.governor may call this method\"\n\n @subroutine\n def _create_pool_token(self) -> Asset:\n return (\n itxn.AssetConfig(\n asset_name=b\"DPT-\" + self.asset_a.unit_name + b\"-\" + self.asset_b.unit_name,\n unit_name=b\"dbt\",\n total=TOTAL_SUPPLY,\n decimals=3,\n manager=Global.current_application_address,\n reserve=Global.current_application_address,\n )\n .submit()\n .created_asset\n )\n\n @subroutine\n def _do_opt_in(self, asset: Asset) -> None:\n do_asset_transfer(\n receiver=Global.current_application_address,\n asset=asset,\n amount=UInt64(0),\n )\n\n @subroutine\n def _current_pool_balance(self) -> UInt64:\n return self.pool_token.balance(Global.current_application_address)\n\n @subroutine\n def _current_a_balance(self) -> UInt64:\n return self.asset_a.balance(Global.current_application_address)\n\n @subroutine\n def _current_b_balance(self) -> UInt64:\n return self.asset_b.balance(Global.current_application_address)\n\n\n##############\n# Mathy methods\n##############\n\n# Notes:\n# 1) During arithmetic operations, depending on the inputs, these methods may overflow\n# the max uint64 value. This will cause the program to immediately terminate.\n#\n# Care should be taken to fully understand the limitations of these functions and if\n# required should be swapped out for the appropriate byte math operations.\n#\n# 2) When doing division, any remainder is truncated from the result.\n#\n# Care should be taken to ensure that _when_ the truncation happens,\n# it does so in favor of the contract. This is a subtle security issue that,\n# if mishandled, could cause the balance of the contract to be drained.\n\n\n@subroutine\ndef tokens_to_mint(\n *,\n pool_balance: UInt64,\n a_balance: UInt64,\n b_balance: UInt64,\n a_amount: UInt64,\n b_amount: UInt64,\n) -> UInt64:\n is_initial_mint = a_balance == a_amount and b_balance == b_amount\n if is_initial_mint:\n return op.sqrt(a_amount * b_amount) - SCALE\n issued = TOTAL_SUPPLY - pool_balance\n a_ratio = SCALE * a_amount \/\/ (a_balance - a_amount)\n b_ratio = SCALE * b_amount \/\/ (b_balance - b_amount)\n if a_ratio < b_ratio:\n return a_ratio * issued \/\/ SCALE\n else:\n return b_ratio * issued \/\/ SCALE\n\n\n@subroutine\ndef tokens_to_burn(*, pool_balance: UInt64, supply: UInt64, amount: UInt64) -> UInt64:\n issued = TOTAL_SUPPLY - pool_balance - amount\n return supply * amount \/\/ issued\n\n\n@subroutine\ndef tokens_to_swap(*, in_amount: UInt64, in_supply: UInt64, out_supply: UInt64) -> UInt64:\n in_total = SCALE * (in_supply - in_amount) + (in_amount * FACTOR)\n out_total = in_amount * FACTOR * out_supply\n return out_total \/\/ in_total\n\n\n@subroutine\ndef do_asset_transfer(*, receiver: Account, asset: Asset, amount: UInt64) -> None:\n itxn.AssetTransfer(\n xfer_asset=asset,\n asset_amount=amount,\n asset_receiver=receiver,\n ).submit()\n","repo_name":"algorandfoundation\/puya","path":"examples\/amm\/contract.py","language":"Python","license":"NOASSERTION","size":12955} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass ConstantProductAMM(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def set_governor(\n self,\n new_governor: algopy.Account,\n ) -> None:\n \"\"\"\n sets the governor of the contract, may only be called by the current governor\n \"\"\"\n\n @algopy.arc4.abimethod\n def bootstrap(\n self,\n seed: algopy.gtxn.PaymentTransaction,\n a_asset: algopy.Asset,\n b_asset: algopy.Asset,\n ) -> algopy.arc4.UIntN[typing.Literal[64]]:\n \"\"\"\n bootstraps the contract by opting into the assets and creating the pool token.\n Note this method will fail if it is attempted more than once on the same contract since the assets and pool token application state values are marked as static and cannot be overridden.\n \"\"\"\n\n @algopy.arc4.abimethod\n def mint(\n self,\n a_xfer: algopy.gtxn.AssetTransferTransaction,\n b_xfer: algopy.gtxn.AssetTransferTransaction,\n pool_asset: algopy.Asset,\n a_asset: algopy.Asset,\n b_asset: algopy.Asset,\n ) -> None:\n \"\"\"\n mint pool tokens given some amount of asset A and asset B.\n Given some amount of Asset A and Asset B in the transfers, mint some number of pool tokens commensurate with the pools current balance and circulating supply of pool tokens.\n \"\"\"\n\n @algopy.arc4.abimethod\n def burn(\n self,\n pool_xfer: algopy.gtxn.AssetTransferTransaction,\n pool_asset: algopy.Asset,\n a_asset: algopy.Asset,\n b_asset: algopy.Asset,\n ) -> None:\n \"\"\"\n burn pool tokens to get back some amount of asset A and asset B\n \"\"\"\n\n @algopy.arc4.abimethod\n def swap(\n self,\n swap_xfer: algopy.gtxn.AssetTransferTransaction,\n a_asset: algopy.Asset,\n b_asset: algopy.Asset,\n ) -> None:\n \"\"\"\n Swap some amount of either asset A or asset B for the other\n \"\"\"\n","repo_name":"algorandfoundation\/puya","path":"examples\/amm\/out\/client_ConstantProductAMM.py","language":"Python","license":"NOASSERTION","size":2067} {"code":"import typing\n\nfrom algopy import ARC4Contract, arc4\n\n\nclass Swapped(arc4.Struct):\n a: arc4.UInt64\n b: arc4.UInt64\n\n\nclass EventEmitter(ARC4Contract):\n @arc4.abimethod\n def emit_swapped(self, a: arc4.UInt64, b: arc4.UInt64) -> None:\n arc4.emit(Swapped(b, a))\n arc4.emit(\"Swapped(uint64,uint64)\", b, a)\n arc4.emit(\"Swapped\", b, a)\n\n @arc4.abimethod()\n def emit_ufixed(\n self,\n a: arc4.BigUFixedNxM[typing.Literal[256], typing.Literal[16]],\n b: arc4.UFixedNxM[typing.Literal[64], typing.Literal[2]],\n ) -> None:\n arc4.emit(\"AnEvent(ufixed256x16,ufixed64x2)\", a, b)\n","repo_name":"algorandfoundation\/puya","path":"examples\/arc_28\/contract.py","language":"Python","license":"NOASSERTION","size":633} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass EventEmitter(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def emit_swapped(\n self,\n a: algopy.arc4.UIntN[typing.Literal[64]],\n b: algopy.arc4.UIntN[typing.Literal[64]],\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def emit_ufixed(\n self,\n a: algopy.arc4.BigUFixedNxM[typing.Literal[256], typing.Literal[16]],\n b: algopy.arc4.UFixedNxM[typing.Literal[64], typing.Literal[2]],\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"examples\/arc_28\/out\/client_EventEmitter.py","language":"Python","license":"NOASSERTION","size":578} {"code":"from algopy import (\n Account,\n ARC4Contract,\n Asset,\n Global,\n LocalState,\n Txn,\n UInt64,\n arc4,\n gtxn,\n itxn,\n subroutine,\n)\n\n\nclass Auction(ARC4Contract):\n def __init__(self) -> None:\n self.auction_end = UInt64(0)\n self.previous_bid = UInt64(0)\n self.asa_amount = UInt64(0)\n self.asa = Asset()\n self.previous_bidder = Account()\n self.claimable_amount = LocalState(UInt64, key=\"claim\", description=\"The claimable amount\")\n\n @arc4.abimethod\n def opt_into_asset(self, asset: Asset) -> None:\n # Only allow app creator to opt the app account into a ASA\n assert Txn.sender == Global.creator_address, \"Only creator can opt in to ASA\"\n # Verify a ASA hasn't already been opted into\n assert self.asa.id == 0, \"ASA already opted in\"\n # Save ASA ID in global state\n self.asa = asset\n\n # Submit opt-in transaction: 0 asset transfer to self\n itxn.AssetTransfer(\n asset_receiver=Global.current_application_address,\n xfer_asset=asset,\n ).submit()\n\n @arc4.abimethod\n def start_auction(\n self,\n starting_price: UInt64,\n length: UInt64,\n axfer: gtxn.AssetTransferTransaction,\n ) -> None:\n assert Txn.sender == Global.creator_address, \"auction must be started by creator\"\n\n # Ensure the auction hasn't already been started\n assert self.auction_end == 0, \"auction already started\"\n\n # Verify axfer\n assert (\n axfer.asset_receiver == Global.current_application_address\n ), \"axfer must transfer to this app\"\n\n # Set global state\n self.asa_amount = axfer.asset_amount\n self.auction_end = Global.latest_timestamp + length\n self.previous_bid = starting_price\n\n @arc4.abimethod\n def opt_in(self) -> None:\n pass\n\n @arc4.abimethod\n def bid(self, pay: gtxn.PaymentTransaction) -> None:\n # Ensure auction hasn't ended\n assert Global.latest_timestamp < self.auction_end, \"auction has ended\"\n\n # Verify payment transaction\n assert pay.sender == Txn.sender, \"payment sender must match transaction sender\"\n assert pay.amount > self.previous_bid, \"Bid must be higher than previous bid\"\n\n # set global state\n self.previous_bid = pay.amount\n self.previous_bidder = pay.sender\n\n # Update claimable amount\n self.claimable_amount[Txn.sender] = pay.amount\n\n @arc4.abimethod\n def claim_bids(self) -> None:\n amount = original_amount = self.claimable_amount[Txn.sender]\n\n # subtract previous bid if sender is previous bidder\n if Txn.sender == self.previous_bidder:\n amount -= self.previous_bid\n\n itxn.Payment(\n amount=amount,\n receiver=Txn.sender,\n ).submit()\n\n self.claimable_amount[Txn.sender] = original_amount - amount\n\n @arc4.abimethod\n def claim_asset(self, asset: Asset) -> None:\n assert Global.latest_timestamp > self.auction_end, \"auction has not ended\"\n # Send ASA to previous bidder\n itxn.AssetTransfer(\n xfer_asset=asset,\n asset_close_to=self.previous_bidder,\n asset_receiver=self.previous_bidder,\n asset_amount=self.asa_amount,\n ).submit()\n\n @subroutine\n def delete_application(self) -> None:\n itxn.Payment(\n receiver=Global.creator_address,\n close_remainder_to=Global.creator_address,\n ).submit()\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"examples\/auction\/contract.py","language":"Python","license":"NOASSERTION","size":3611} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass Auction(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def opt_into_asset(\n self,\n asset: algopy.Asset,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def start_auction(\n self,\n starting_price: algopy.arc4.UIntN[typing.Literal[64]],\n length: algopy.arc4.UIntN[typing.Literal[64]],\n axfer: algopy.gtxn.AssetTransferTransaction,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def opt_in(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def bid(\n self,\n pay: algopy.gtxn.PaymentTransaction,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def claim_bids(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def claim_asset(\n self,\n asset: algopy.Asset,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"examples\/auction\/out\/client_Auction.py","language":"Python","license":"NOASSERTION","size":914} {"code":"import typing\n\nfrom algopy import Box, BoxMap, BoxRef, Bytes, Global, String, Txn, UInt64, arc4, subroutine\n\nStaticInts: typing.TypeAlias = arc4.StaticArray[arc4.UInt8, typing.Literal[4]]\n\n\nclass BoxContract(arc4.ARC4Contract):\n def __init__(self) -> None:\n self.box_a = Box(UInt64)\n self.box_b = Box[arc4.DynamicBytes](arc4.DynamicBytes, key=\"b\")\n self.box_c = Box(arc4.String, key=b\"BOX_C\")\n self.box_d = Box(Bytes)\n self.box_map = BoxMap(UInt64, String, key_prefix=\"\")\n self.box_ref = BoxRef()\n\n @arc4.abimethod\n def set_boxes(self, a: UInt64, b: arc4.DynamicBytes, c: arc4.String) -> None:\n self.box_a.value = a\n self.box_b.value = b.copy()\n self.box_c.value = c\n self.box_d.value = b.native\n\n b_value = self.box_b.value.copy()\n assert self.box_b.value.length == b_value.length, \"direct reference should match copy\"\n\n self.box_a.value += 3\n\n # test .length\n assert self.box_a.length == 8\n assert self.box_b.length == b.bytes.length\n assert self.box_c.length == c.bytes.length\n assert self.box_d.length == b.native.length\n\n # test .value.bytes\n assert self.box_c.value.bytes[0] == c.bytes[0]\n assert self.box_c.value.bytes[-1] == c.bytes[-1]\n assert self.box_c.value.bytes[:-1] == c.bytes[:-1]\n assert self.box_c.value.bytes[:2] == c.bytes[:2]\n\n # test .value with Bytes type\n assert self.box_d.value[0] == b.native[0]\n assert self.box_d.value[-1] == b.native[-1]\n assert self.box_d.value[:-1] == b.native[:-1]\n assert self.box_d.value[:5] == b.native[:5]\n assert self.box_d.value[: UInt64(2)] == b.native[: UInt64(2)]\n\n @arc4.abimethod\n def check_keys(self) -> None:\n assert self.box_a.key == b\"box_a\", \"box a key ok\"\n assert self.box_b.key == b\"b\", \"box b key ok\"\n assert self.box_c.key == b\"BOX_C\", \"box c key ok\"\n\n @arc4.abimethod\n def delete_boxes(self) -> None:\n del self.box_a.value\n del self.box_b.value\n del self.box_c.value\n assert self.box_a.get(default=UInt64(42)) == 42\n assert self.box_b.get(default=arc4.DynamicBytes(b\"42\")).native == b\"42\"\n assert self.box_c.get(default=arc4.String(\"42\")) == \"42\"\n a, a_exists = self.box_a.maybe()\n assert not a_exists\n assert a == 0\n\n @arc4.abimethod\n def read_boxes(self) -> tuple[UInt64, Bytes, arc4.String]:\n return get_box_value_plus_1(self.box_a) - 1, self.box_b.value.native, self.box_c.value\n\n @arc4.abimethod\n def boxes_exist(self) -> tuple[bool, bool, bool]:\n return bool(self.box_a), bool(self.box_b), bool(self.box_c)\n\n @arc4.abimethod\n def slice_box(self) -> None:\n box_0 = Box(Bytes, key=String(\"0\"))\n box_0.value = Bytes(b\"Testing testing 123\")\n assert box_0.value[0:7] == b\"Testing\"\n\n self.box_c.value = arc4.String(\"Hello\")\n assert self.box_c.value.bytes[2:10] == b\"Hello\"\n\n @arc4.abimethod\n def arc4_box(self) -> None:\n box_d = Box(StaticInts, key=Bytes(b\"d\"))\n box_d.value = StaticInts(arc4.UInt8(0), arc4.UInt8(1), arc4.UInt8(2), arc4.UInt8(3))\n\n assert box_d.value[0] == 0\n assert box_d.value[1] == 1\n assert box_d.value[2] == 2\n assert box_d.value[3] == 3\n\n @arc4.abimethod\n def test_box_ref(self) -> None:\n # init ref, with valid key types\n box_ref = BoxRef(key=\"blob\")\n assert not box_ref, \"no data\"\n box_ref = BoxRef(key=b\"blob\")\n assert not box_ref, \"no data\"\n box_ref = BoxRef(key=Bytes(b\"blob\"))\n assert not box_ref, \"no data\"\n box_ref = BoxRef(key=String(\"blob\"))\n assert not box_ref, \"no data\"\n\n # create\n assert box_ref.create(size=32)\n assert box_ref, \"has data\"\n\n # manipulate data\n sender_bytes = Txn.sender.bytes\n app_address = Global.current_application_address.bytes\n value_3 = Bytes(b\"hello\")\n box_ref.replace(0, sender_bytes)\n box_ref.resize(8000)\n box_ref.splice(0, 0, app_address)\n box_ref.replace(64, value_3)\n prefix = box_ref.extract(0, 32 * 2 + value_3.length)\n assert prefix == app_address + sender_bytes + value_3\n\n # delete\n assert box_ref.delete()\n assert box_ref.key == b\"blob\"\n\n # query\n value, exists = box_ref.maybe()\n assert not exists\n assert value == b\"\"\n assert box_ref.get(default=sender_bytes) == sender_bytes\n\n # update\n box_ref.put(sender_bytes + app_address)\n assert box_ref, \"Blob exists\"\n assert box_ref.length == 64\n assert get_box_ref_length(box_ref) == 64\n\n # instance box ref\n self.box_ref.create(size=UInt64(32))\n assert self.box_ref, \"has data\"\n self.box_ref.delete()\n\n @arc4.abimethod\n def box_map_test(self) -> None:\n key_0 = UInt64(0)\n key_1 = UInt64(1)\n value = String(\"Hmmmmm\")\n self.box_map[key_0] = value\n assert self.box_map[key_0].bytes.length == value.bytes.length\n assert self.box_map.length(key_0) == value.bytes.length\n\n assert self.box_map.get(key_1, default=String(\"default\")) == String(\"default\")\n value, exists = self.box_map.maybe(key_1)\n assert not exists\n assert key_0 in self.box_map\n assert self.box_map.key_prefix == b\"\"\n\n # test box map not assigned to the class and passed to subroutine\n tmp_box_map = BoxMap(UInt64, String, key_prefix=Bytes())\n tmp_box_map[key_1] = String(\"hello\")\n assert get_box_map_value_from_key_plus_1(tmp_box_map, UInt64(0)) == \"hello\"\n del tmp_box_map[key_1]\n\n @arc4.abimethod\n def box_map_set(self, key: UInt64, value: String) -> None:\n self.box_map[key] = value\n\n @arc4.abimethod\n def box_map_get(self, key: UInt64) -> String:\n return self.box_map[key]\n\n @arc4.abimethod\n def box_map_del(self, key: UInt64) -> None:\n del self.box_map[key]\n\n @arc4.abimethod\n def box_map_exists(self, key: UInt64) -> bool:\n return key in self.box_map\n\n\n@subroutine\ndef get_box_value_plus_1(box: Box[UInt64]) -> UInt64:\n return box.value + 1\n\n\n@subroutine\ndef get_box_ref_length(ref: BoxRef) -> UInt64:\n return ref.length\n\n\n@subroutine\ndef get_box_map_value_from_key_plus_1(box_map: BoxMap[UInt64, String], key: UInt64) -> String:\n return box_map[key + 1]\n","repo_name":"algorandfoundation\/puya","path":"examples\/box_storage\/contract.py","language":"Python","license":"NOASSERTION","size":6493} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass BoxContract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def set_boxes(\n self,\n a: algopy.arc4.UIntN[typing.Literal[64]],\n b: algopy.arc4.DynamicBytes,\n c: algopy.arc4.String,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def check_keys(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def delete_boxes(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def read_boxes(\n self,\n ) -> algopy.arc4.Tuple[algopy.arc4.UIntN[typing.Literal[64]], algopy.arc4.DynamicBytes, algopy.arc4.String]: ...\n\n @algopy.arc4.abimethod\n def boxes_exist(\n self,\n ) -> algopy.arc4.Tuple[algopy.arc4.Bool, algopy.arc4.Bool, algopy.arc4.Bool]: ...\n\n @algopy.arc4.abimethod\n def slice_box(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def arc4_box(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_box_ref(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def box_map_test(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def box_map_set(\n self,\n key: algopy.arc4.UIntN[typing.Literal[64]],\n value: algopy.arc4.String,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def box_map_get(\n self,\n key: algopy.arc4.UIntN[typing.Literal[64]],\n ) -> algopy.arc4.String: ...\n\n @algopy.arc4.abimethod\n def box_map_del(\n self,\n key: algopy.arc4.UIntN[typing.Literal[64]],\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def box_map_exists(\n self,\n key: algopy.arc4.UIntN[typing.Literal[64]],\n ) -> algopy.arc4.Bool: ...\n","repo_name":"algorandfoundation\/puya","path":"examples\/box_storage\/out\/client_BoxContract.py","language":"Python","license":"NOASSERTION","size":1776} {"code":"from algopy import Bytes, Contract, Txn, UInt64, log, op, subroutine\n\nADD = 1\nSUB = 2\nMUL = 3\nDIV = 4\n\n\n@subroutine\ndef itoa(i: UInt64) -> Bytes:\n digits = Bytes(b\"0123456789\")\n radix = digits.length\n if i < radix:\n return digits[i]\n return itoa(i \/\/ radix) + digits[i % radix]\n\n\nclass MyContract(Contract):\n def approval_program(self) -> UInt64:\n num_args = Txn.num_app_args\n if num_args == 0:\n a = UInt64(0)\n b = UInt64(0)\n action = UInt64(0)\n log(a)\n log(b)\n else:\n assert num_args == 3, \"Expected 3 args\"\n action_b = Txn.application_args(0)\n action = op.btoi(action_b)\n a_bytes = Txn.application_args(1)\n b_bytes = Txn.application_args(2)\n log(a_bytes)\n log(b_bytes)\n a = op.btoi(a_bytes)\n b = op.btoi(b_bytes)\n\n result = self.do_calc(action, a, b)\n result_b = itoa(a) + self.op(action) + itoa(b) + b\" = \" + itoa(result)\n log(result_b)\n return UInt64(1)\n\n @subroutine\n def op(self, action: UInt64) -> Bytes:\n if action == ADD:\n return Bytes(b\" + \")\n elif action == SUB:\n return Bytes(b\" - \")\n elif action == MUL:\n return Bytes(b\" * \")\n elif action == DIV:\n return Bytes(b\" \/\/ \")\n else:\n return Bytes(b\" - \")\n\n @subroutine\n def do_calc(self, maybe_action: UInt64, a: UInt64, b: UInt64) -> UInt64:\n if maybe_action == ADD:\n return self.add(a, b)\n elif maybe_action == SUB:\n return self.sub(a, b)\n elif maybe_action == MUL:\n return self.mul(a, b)\n elif maybe_action == DIV:\n return self.div(a, b)\n else:\n assert False, \"unknown operation\"\n\n @subroutine\n def add(self, a: UInt64, b: UInt64) -> UInt64:\n return a + b\n\n @subroutine\n def sub(self, a: UInt64, b: UInt64) -> UInt64:\n return a - b\n\n @subroutine\n def mul(self, a: UInt64, b: UInt64) -> UInt64:\n return a * b\n\n @subroutine\n def div(self, a: UInt64, b: UInt64) -> UInt64:\n return a \/\/ b\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"examples\/calculator\/contract.py","language":"Python","license":"NOASSERTION","size":2278} {"code":"from algopy import (\n Account,\n Application,\n Asset,\n Bytes,\n Contract,\n GlobalState,\n String,\n UInt64,\n subroutine,\n)\n\n\nclass AppStateContract(Contract):\n def __init__(self) -> None:\n self.global_int_full = GlobalState(UInt64(55))\n self.global_int_simplified = UInt64(33)\n self.global_int_no_default = GlobalState(UInt64)\n\n self.global_bytes_full = GlobalState(Bytes(b\"Hello\"))\n self.global_bytes_simplified = Bytes(b\"Hello\")\n self.global_bytes_no_default = GlobalState(Bytes)\n\n self.global_bool_full = GlobalState(False)\n self.global_bool_simplified = True\n self.global_bool_no_default = GlobalState(bool)\n\n self.global_asset = GlobalState(Asset)\n self.global_application = GlobalState(Application)\n self.global_account = GlobalState(Account)\n\n def approval_program(self) -> bool:\n assert self.global_int_simplified == 33\n assert self.global_int_full\n assert self.global_int_full.value == 55\n assert not self.global_int_no_default\n self.global_int_no_default.value = UInt64(44)\n i_value, i_exists = self.global_int_no_default.maybe()\n assert i_exists\n assert i_value == 44\n assert read_global_uint64(Bytes(b\"global_int_no_default\")) == 44\n\n assert self.global_bytes_simplified == b\"Hello\"\n assert self.global_bytes_full\n assert self.global_bytes_full.value == b\"Hello\"\n assert self.global_bytes_full.get(Bytes(b\"default\")) == b\"Hello\"\n assert not self.global_bytes_no_default\n self.global_bytes_no_default.value = Bytes(b\"World\")\n b_value, b_exists = self.global_bytes_no_default.maybe()\n assert b_exists\n assert b_value == b\"World\"\n assert read_global_bytes(String(\"global_bytes_no_default\")) == b\"World\"\n del self.global_bytes_no_default.value\n b_value, b_exists = self.global_bytes_no_default.maybe()\n assert not b_exists\n\n assert self.global_bytes_no_default.get(Bytes(b\"default\")) == b\"default\"\n\n # Assert 'is set'\n assert self.global_bool_full\n assert not self.global_bool_no_default\n\n self.global_bool_no_default.value = True\n\n # Assert 'value'\n assert not self.global_bool_full.value\n assert self.global_bool_simplified\n assert self.global_bool_no_default.value\n\n # test the proxy can be passed as an argument\n assert get_global_state_plus_1(self.global_int_no_default) == 45\n\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n\n@subroutine\ndef get_global_state_plus_1(state: GlobalState[UInt64]) -> UInt64:\n return state.value + 1\n\n\n@subroutine\ndef read_global_uint64(key: Bytes) -> UInt64:\n return GlobalState(UInt64, key=key).value\n\n\n@subroutine\ndef read_global_bytes(key: String) -> Bytes:\n return GlobalState(Bytes, key=key).value\n","repo_name":"algorandfoundation\/puya","path":"examples\/global_state\/contract.py","language":"Python","license":"NOASSERTION","size":2937} {"code":"from algopy import Contract, Txn, log\n\n\nclass HelloWorldContract(Contract):\n def approval_program(self) -> bool:\n name = Txn.application_args(0)\n log(b\"Hello, \" + name)\n return True\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"examples\/hello_world\/contract.py","language":"Python","license":"NOASSERTION","size":270} {"code":"from algopy import ARC4Contract, String, arc4\n\n# Note: this contract is also used in the Puya AlgoKit template. So any breaking changes\n# that require fixing this contract should also be made there\n# https:\/\/github.com\/algorandfoundation\/algokit-puya-template\/blob\/main\/template_content\/pyproject.toml.jinja\n# https:\/\/github.com\/algorandfoundation\/algokit-puya-template\/blob\/main\/template_content\/.algokit\/generators\/create_contract\/smart_contracts\/%7B%25%20raw%20%25%7D%7B%7B%20contract_name%20%7D%7D%7B%25%20endraw%20%25%7D\/contract.py.j2\n\n\nclass HelloWorldContract(ARC4Contract):\n @arc4.abimethod\n def hello(self, name: String) -> String:\n return \"Hello, \" + name\n","repo_name":"algorandfoundation\/puya","path":"examples\/hello_world_arc4\/contract.py","language":"Python","license":"NOASSERTION","size":680} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass HelloWorldContract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def hello(\n self,\n name: algopy.arc4.String,\n ) -> algopy.arc4.String: ...\n","repo_name":"algorandfoundation\/puya","path":"examples\/hello_world_arc4\/out\/client_HelloWorldContract.py","language":"Python","license":"NOASSERTION","size":292} {"code":"from algopy import (\n Account,\n Bytes,\n Contract,\n LocalState,\n OnCompleteAction,\n String,\n Txn,\n UInt64,\n log,\n subroutine,\n)\n\n\nclass LocalStateContract(Contract):\n def __init__(self) -> None:\n self.local = LocalState(Bytes)\n self.local_bool = LocalState(bool)\n\n def approval_program(self) -> bool:\n if Txn.application_id == 0:\n return True\n if Txn.on_completion not in (OnCompleteAction.NoOp, OnCompleteAction.OptIn):\n return False\n if Txn.num_app_args == 0:\n return False\n\n method = Txn.application_args(0)\n if Txn.num_app_args == 1:\n if method == b\"get_guaranteed_data\":\n log(self.get_guaranteed_data(Txn.sender))\n elif method == b\"get_data_or_assert\":\n log(self.get_data_or_assert(Txn.sender))\n elif method == b\"delete_data\":\n self.delete_data(Txn.sender)\n log(\"Deleted\")\n else:\n return False\n return True\n elif Txn.num_app_args == 2:\n if method == b\"set_data\":\n self.set_data(Txn.sender, Txn.application_args(1))\n elif method == b\"get_data_with_default\":\n log(self.get_data_with_default(Txn.sender, Txn.application_args(1)))\n else:\n return False\n return True\n else:\n return False\n\n def clear_state_program(self) -> bool:\n return True\n\n @subroutine\n def get_guaranteed_data(self, for_account: Account) -> Bytes:\n result = self.local[for_account]\n # this just tests local state proxy can be passed around\n assert result.length == get_local_state_length(self.local, for_account)\n # tests for dynamic key\n assert local_bytes_exists(for_account, Bytes(b\"local\"))\n assert read_local_bytes(for_account, String(\"local\")) == result\n return result\n\n @subroutine\n def get_data_with_default(self, for_account: Account, default: Bytes) -> Bytes:\n # offset contract use arguments without kwarg\n return self.local.get(account=for_account, default=default)\n\n @subroutine\n def get_data_or_assert(self, for_account: Account) -> Bytes:\n result, exists = self.local.maybe(for_account)\n assert exists, \"no data for account\"\n return result\n\n @subroutine\n def set_data(self, for_account: Account, value: Bytes) -> None:\n self.local[for_account] = value\n\n @subroutine\n def delete_data(self, for_account: Account) -> None:\n del self.local[for_account]\n\n\n@subroutine\ndef get_local_state_length(state: LocalState[Bytes], account: Account) -> UInt64:\n return state[account].length\n\n\n@subroutine\ndef local_bytes_exists(account: Account, key: Bytes) -> bool:\n return account in LocalState(Bytes, key=key)\n\n\n@subroutine\ndef read_local_bytes(account: Account, key: String) -> Bytes:\n return LocalState(Bytes, key=key)[account]\n","repo_name":"algorandfoundation\/puya","path":"examples\/local_state\/local_state_contract.py","language":"Python","license":"NOASSERTION","size":3010} {"code":"from algopy import (\n Bytes,\n Contract,\n LocalState,\n OnCompleteAction,\n Txn,\n UInt64,\n log,\n op,\n subroutine,\n)\n\n\nclass LocalStateContract(Contract, name=\"LocalStateWithOffsets\"):\n def __init__(self) -> None:\n self.local = LocalState(Bytes)\n\n def approval_program(self) -> bool:\n if Txn.application_id == 0:\n return True\n if Txn.on_completion not in (OnCompleteAction.NoOp, OnCompleteAction.OptIn):\n return False\n if Txn.num_app_args < 1:\n return False\n\n offset = op.btoi(Txn.application_args(0))\n method = Txn.application_args(1)\n if Txn.num_app_args == 2:\n if method == b\"get_guaranteed_data\":\n log(self.get_guaranteed_data(offset))\n elif method == b\"get_data_or_assert\":\n log(self.get_data_or_assert(offset))\n elif method == b\"delete_data\":\n self.delete_data(offset)\n log(\"Deleted\")\n else:\n return False\n return True\n elif Txn.num_app_args == 3:\n if method == b\"set_data\":\n self.set_data(offset, Txn.application_args(2))\n elif method == b\"get_data_with_default\":\n log(self.get_data_with_default(offset, Txn.application_args(2)))\n else:\n return False\n return True\n else:\n return False\n\n def clear_state_program(self) -> bool:\n return True\n\n @subroutine\n def get_guaranteed_data(self, for_account: UInt64) -> Bytes:\n return self.local[for_account]\n\n @subroutine\n def get_data_with_default(self, for_account: UInt64, default: Bytes) -> Bytes:\n return self.local.get(for_account, default)\n\n @subroutine\n def get_data_or_assert(self, for_account: UInt64) -> Bytes:\n result, exists = self.local.maybe(for_account)\n assert exists, \"no data for account\"\n return result\n\n @subroutine\n def set_data(self, for_account: UInt64, value: Bytes) -> None:\n self.local[for_account] = value\n\n @subroutine\n def delete_data(self, for_account: UInt64) -> None:\n del self.local[for_account]\n","repo_name":"algorandfoundation\/puya","path":"examples\/local_state\/local_state_with_offsets.py","language":"Python","license":"NOASSERTION","size":2220} {"code":"import typing\n\nfrom algopy import BigUInt, Bytes, arc4, op, subroutine, urange\n\nBytes32: typing.TypeAlias = arc4.StaticArray[arc4.Byte, typing.Literal[32]]\nProof: typing.TypeAlias = arc4.DynamicArray[Bytes32]\n\n\nclass MerkleTree(arc4.ARC4Contract):\n @arc4.abimethod(create=\"require\")\n def create(self, root: Bytes32) -> None:\n self.root = root.bytes\n\n @arc4.abimethod\n def verify(self, proof: Proof, leaf: Bytes32) -> bool:\n return self.root == compute_root_hash(proof, leaf.bytes)\n\n\n@subroutine\ndef compute_root_hash(proof: Proof, leaf: Bytes) -> Bytes:\n computed = leaf\n for idx in urange(proof.length):\n computed = hash_pair(computed, proof[idx].bytes)\n return computed\n\n\n@subroutine\ndef hash_pair(a: Bytes, b: Bytes) -> Bytes:\n return op.sha256(a + b if BigUInt.from_bytes(a) < BigUInt.from_bytes(b) else b + a)\n","repo_name":"algorandfoundation\/puya","path":"examples\/merkle\/contract.py","language":"Python","license":"NOASSERTION","size":860} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass MerkleTree(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod(create='require')\n def create(\n self,\n root: algopy.arc4.StaticArray[algopy.arc4.Byte, typing.Literal[32]],\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def verify(\n self,\n proof: algopy.arc4.DynamicArray[algopy.arc4.StaticArray[algopy.arc4.Byte, typing.Literal[32]]],\n leaf: algopy.arc4.StaticArray[algopy.arc4.Byte, typing.Literal[32]],\n ) -> algopy.arc4.Bool: ...\n","repo_name":"algorandfoundation\/puya","path":"examples\/merkle\/out\/client_MerkleTree.py","language":"Python","license":"NOASSERTION","size":602} {"code":"from algopy import ARC4Contract, Asset, arc4, op, subroutine\n\n\nclass UserStruct(arc4.Struct):\n name: arc4.String\n id: arc4.UInt64\n asset: arc4.UInt64\n\n\nclass ExampleContract(ARC4Contract):\n @subroutine\n def read_from_box(self, user_id: arc4.UInt64) -> UserStruct:\n box_data, exists = op.Box.get(user_id.bytes)\n assert exists, \"User with that id does not exist\"\n return UserStruct.from_bytes(box_data)\n\n @subroutine\n def write_to_box(self, user: UserStruct) -> None:\n box_key = user.id.bytes\n # Delete existing data, so we don't have to worry about resizing the box\n op.Box.delete(box_key)\n\n op.Box.put(box_key, user.bytes)\n\n @subroutine\n def box_exists(self, user_id: arc4.UInt64) -> bool:\n _data, exists = op.Box.get(user_id.bytes)\n return exists\n\n @arc4.abimethod()\n def add_user(self, user: UserStruct) -> None:\n assert not self.box_exists(user.id), \"User with id must not exist\"\n self.write_to_box(user)\n\n @arc4.abimethod()\n def attach_asset_to_user(self, user_id: arc4.UInt64, asset: Asset) -> None:\n user = self.read_from_box(user_id)\n user.asset = arc4.UInt64(asset.id)\n self.write_to_box(user)\n\n @arc4.abimethod()\n def get_user(self, user_id: arc4.UInt64) -> UserStruct:\n return self.read_from_box(user_id)\n","repo_name":"algorandfoundation\/puya","path":"examples\/struct_in_box\/contract.py","language":"Python","license":"NOASSERTION","size":1365} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\nclass UserStruct(algopy.arc4.Struct):\n name: algopy.arc4.String\n id: algopy.arc4.UIntN[typing.Literal[64]]\n asset: algopy.arc4.UIntN[typing.Literal[64]]\n\nclass ExampleContract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def add_user(\n self,\n user: UserStruct,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def attach_asset_to_user(\n self,\n user_id: algopy.arc4.UIntN[typing.Literal[64]],\n asset: algopy.Asset,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def get_user(\n self,\n user_id: algopy.arc4.UIntN[typing.Literal[64]],\n ) -> UserStruct: ...\n","repo_name":"algorandfoundation\/puya","path":"examples\/struct_in_box\/out\/client_ExampleContract.py","language":"Python","license":"NOASSERTION","size":749} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass TicTacToeContract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod(create='allow')\n def new_game(\n self,\n move: algopy.arc4.Tuple[algopy.arc4.UIntN[typing.Literal[64]], algopy.arc4.UIntN[typing.Literal[64]]],\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def join_game(\n self,\n move: algopy.arc4.Tuple[algopy.arc4.UIntN[typing.Literal[64]], algopy.arc4.UIntN[typing.Literal[64]]],\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def whose_turn(\n self,\n ) -> algopy.arc4.UIntN[typing.Literal[8]]: ...\n\n @algopy.arc4.abimethod\n def play(\n self,\n move: algopy.arc4.Tuple[algopy.arc4.UIntN[typing.Literal[64]], algopy.arc4.UIntN[typing.Literal[64]]],\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"examples\/tictactoe\/out\/client_TicTacToeContract.py","language":"Python","license":"NOASSERTION","size":863} {"code":"# ruff: noqa: PT018\nimport typing\n\nfrom algopy import Account, GlobalState, Txn, UInt64, arc4, op, subroutine\n\nRow: typing.TypeAlias = arc4.StaticArray[arc4.UInt8, typing.Literal[3]]\nGame: typing.TypeAlias = arc4.StaticArray[Row, typing.Literal[3]]\nMove: typing.TypeAlias = tuple[UInt64, UInt64]\nEMPTY = 0\nHOST = 1\nCHALLENGER = 2\nDRAW = 3\n\n\nclass TicTacToeContract(arc4.ARC4Contract):\n def __init__(self) -> None:\n self.challenger = GlobalState(Account)\n self.winner = GlobalState(arc4.UInt8)\n\n @arc4.abimethod(create=\"allow\")\n def new_game(self, move: Move) -> None:\n if Txn.application_id:\n # if a challenger has joined, don't allow starting a new game\n # until this one is complete\n if self.challenger:\n assert self.winner, \"Game isn't over\"\n # reset challenger and winner\n del self.challenger.value\n del self.winner.value\n self.host = Txn.sender\n self.game = Game.from_bytes(op.bzero(9))\n column, row = move\n assert column < 3 and row < 3, \"Move must be in range\"\n self.game[row][column] = arc4.UInt8(HOST)\n self.turns = UInt64(0)\n\n @arc4.abimethod\n def join_game(self, move: Move) -> None:\n assert not self.challenger, \"Host already has a challenger\"\n self.challenger.value = Txn.sender\n self.make_move(arc4.UInt8(CHALLENGER), move)\n\n @arc4.abimethod\n def whose_turn(self) -> arc4.UInt8:\n return arc4.UInt8(HOST) if self.turns % 2 else arc4.UInt8(CHALLENGER)\n\n @arc4.abimethod\n def play(self, move: Move) -> None:\n assert not self.winner, \"Game is already finished\"\n if self.turns % 2:\n assert Txn.sender == self.host, \"It is the host's turn\"\n player = arc4.UInt8(HOST)\n else:\n assert Txn.sender == self.challenger.get(\n default=Account()\n ), \"It is the challenger's turn\"\n player = arc4.UInt8(CHALLENGER)\n self.make_move(player, move)\n\n @subroutine\n def make_move(self, player: arc4.UInt8, move: Move) -> None:\n column, row = move\n assert column < 3 and row < 3, \"Move must be in range\"\n assert self.game[row][column] == EMPTY, \"Square is already taken\"\n self.game[row][column] = player\n self.turns += 1\n if self.did_win(player, column=column, row=row):\n self.winner.value = player\n elif self.turns == 9:\n self.winner.value = arc4.UInt8(DRAW)\n\n @subroutine\n def did_win(self, player: arc4.UInt8, column: UInt64, row: UInt64) -> bool:\n g = self.game.copy()\n\n if g[row][0] == g[row][1] == g[row][2]:\n return True\n\n if g[0][column] == g[1][column] == g[2][column]:\n return True\n\n # if player owns center, check diagonals\n if player == g[1][1]:\n if g[0][0] == player == g[2][2]:\n return True\n if g[0][2] == player == g[2][0]:\n return True\n return False\n","repo_name":"algorandfoundation\/puya","path":"examples\/tictactoe\/tictactoe.py","language":"Python","license":"NOASSERTION","size":3051} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\nclass VotingPreconditions(algopy.arc4.Struct):\n is_voting_open: algopy.arc4.UIntN[typing.Literal[64]]\n is_allowed_to_vote: algopy.arc4.UIntN[typing.Literal[64]]\n has_already_voted: algopy.arc4.UIntN[typing.Literal[64]]\n current_time: algopy.arc4.UIntN[typing.Literal[64]]\n\nclass VotingRoundApp(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod(create='require')\n def create(\n self,\n vote_id: algopy.arc4.String,\n snapshot_public_key: algopy.arc4.DynamicBytes,\n metadata_ipfs_cid: algopy.arc4.String,\n start_time: algopy.arc4.UIntN[typing.Literal[64]],\n end_time: algopy.arc4.UIntN[typing.Literal[64]],\n option_counts: algopy.arc4.DynamicArray[algopy.arc4.UIntN[typing.Literal[8]]],\n quorum: algopy.arc4.UIntN[typing.Literal[64]],\n nft_image_url: algopy.arc4.String,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def bootstrap(\n self,\n fund_min_bal_req: algopy.gtxn.PaymentTransaction,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def close(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod(readonly=True)\n def get_preconditions(\n self,\n signature: algopy.arc4.DynamicBytes,\n ) -> VotingPreconditions: ...\n\n @algopy.arc4.abimethod\n def vote(\n self,\n fund_min_bal_req: algopy.gtxn.PaymentTransaction,\n signature: algopy.arc4.DynamicBytes,\n answer_ids: algopy.arc4.DynamicArray[algopy.arc4.UIntN[typing.Literal[8]]],\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"examples\/voting\/out\/client_VotingRoundApp.py","language":"Python","license":"NOASSERTION","size":1622} {"code":"# Converted from https:\/\/github.com\/algorandfoundation\/nft_voting_tool\/blob\/c0f8be47ab80c8694d2cf40ca0df54cec07ff14a\/src\/algorand\/smart_contracts\/voting.py\nimport typing\n\nfrom algopy import (\n Account,\n ARC4Contract,\n BoxMap,\n BoxRef,\n Bytes,\n Global,\n GlobalState,\n OpUpFeeSource,\n String,\n Txn,\n UInt64,\n arc4,\n ensure_budget,\n gtxn,\n itxn,\n log,\n op,\n subroutine,\n uenumerate,\n urange,\n)\n\nVoteIndexArray: typing.TypeAlias = arc4.DynamicArray[arc4.UInt8]\n\nVOTE_INDEX_BYTES = 1\nVOTE_COUNT_BYTES = 8\n\n#: The min balance increase per box created\nBOX_FLAT_MIN_BALANCE = 2500\n\n#: The min balance increase per byte of boxes (key included)\nBOX_BYTE_MIN_BALANCE = 400\n\n#: The min balance increase for each asset opted into\nASSET_MIN_BALANCE = 100000\n\n\nclass VotingPreconditions(arc4.Struct):\n is_voting_open: arc4.UInt64\n is_allowed_to_vote: arc4.UInt64\n has_already_voted: arc4.UInt64\n current_time: arc4.UInt64\n\n\nclass VotingRoundApp(ARC4Contract):\n def __init__(self) -> None:\n self.is_bootstrapped = False\n # The minimum number of voters who have voted\n self.voter_count = UInt64(0)\n self.close_time = GlobalState(UInt64)\n self.tally_box = BoxRef(key=\"V\")\n self.votes_by_account = BoxMap(Account, VoteIndexArray, key_prefix=\"\")\n\n @arc4.abimethod(create=\"require\")\n def create(\n self,\n vote_id: String,\n snapshot_public_key: Bytes,\n metadata_ipfs_cid: String,\n start_time: UInt64,\n end_time: UInt64,\n option_counts: VoteIndexArray,\n quorum: UInt64,\n nft_image_url: String,\n ) -> None:\n assert start_time < end_time, \"End time should be after start time\"\n assert end_time >= Global.latest_timestamp, \"End time should be in the future\"\n\n self.vote_id = vote_id\n self.snapshot_public_key = snapshot_public_key\n self.metadata_ipfs_cid = metadata_ipfs_cid\n self.start_time = start_time\n self.end_time = end_time\n self.quorum = quorum\n self.nft_image_url = nft_image_url\n self.store_option_counts(option_counts.copy())\n\n @arc4.abimethod\n def bootstrap(self, fund_min_bal_req: gtxn.PaymentTransaction) -> None:\n assert not self.is_bootstrapped, \"Must not be already bootstrapped\"\n self.is_bootstrapped = True\n\n assert (\n fund_min_bal_req.receiver == Global.current_application_address\n ), \"Payment must be to app address\"\n\n tally_box_size = self.total_options * VOTE_COUNT_BYTES\n min_balance_req = (\n # minimum balance req for: ALGOs + Vote result NFT asset\n ASSET_MIN_BALANCE * 2\n # create NFT fee\n + 1000\n # tally box\n + BOX_FLAT_MIN_BALANCE\n # tally box key \"V\"\n + BOX_BYTE_MIN_BALANCE\n # tally box value\n + (tally_box_size * BOX_BYTE_MIN_BALANCE)\n )\n log(min_balance_req)\n assert (\n fund_min_bal_req.amount == min_balance_req\n ), \"Payment must be for the exact min balance requirement\"\n assert self.tally_box.create(size=tally_box_size)\n\n @arc4.abimethod\n def close(self) -> None:\n ensure_budget(20000, fee_source=OpUpFeeSource.GroupCredit)\n assert not self.close_time, \"Already closed\"\n self.close_time.value = Global.latest_timestamp\n\n note = (\n '{\"standard\":\"arc69\",'\n '\"description\":\"This is a voting result NFT for voting round with ID '\n + self.vote_id\n + '.\",\"properties\":{\"metadata\":\"ipfs:\/\/'\n + self.metadata_ipfs_cid\n + '\",\"id\":\"'\n + self.vote_id\n + '\",\"quorum\":'\n + itoa(self.quorum)\n + ',\"voterCount\":'\n + itoa(self.voter_count)\n + ',\"tallies\":['\n )\n\n current_index = UInt64(0)\n for question_index, question_options in uenumerate(self.option_counts):\n if question_index > 0:\n note += \",\"\n if question_options > 0:\n note += \"[\"\n for option_index in urange(question_options.native):\n if option_index > 0:\n note += \",\"\n votes_for_option = self.get_vote_from_box(current_index)\n note += itoa(votes_for_option)\n current_index += 1\n note += \"]\"\n note += \"]}}\"\n self.nft_asset_id = (\n itxn.AssetConfig(\n total=1,\n decimals=0,\n default_frozen=False,\n asset_name=\"[VOTE RESULT] \" + self.vote_id,\n unit_name=\"VOTERSLT\",\n url=self.nft_image_url,\n note=note,\n fee=Global.min_txn_fee,\n )\n .submit()\n .created_asset.id\n )\n\n @arc4.abimethod(readonly=True)\n def get_preconditions(self, signature: Bytes) -> VotingPreconditions:\n return VotingPreconditions(\n is_voting_open=arc4.UInt64(self.voting_open()),\n is_allowed_to_vote=arc4.UInt64(self.allowed_to_vote(signature)),\n has_already_voted=arc4.UInt64(self.already_voted()),\n current_time=arc4.UInt64(Global.latest_timestamp),\n )\n\n @arc4.abimethod\n def vote(\n self,\n fund_min_bal_req: gtxn.PaymentTransaction,\n signature: Bytes,\n answer_ids: VoteIndexArray,\n ) -> None:\n ensure_budget(7700, fee_source=OpUpFeeSource.GroupCredit)\n # Check voting preconditions\n assert self.allowed_to_vote(signature), \"Not allowed to vote\"\n assert self.voting_open(), \"Voting not open\"\n assert not self.already_voted(), \"Already voted\"\n questions_count = self.option_counts.length\n assert answer_ids.length == questions_count, \"Number of answers incorrect\"\n # Check voter box is funded\n min_bal_req = BOX_FLAT_MIN_BALANCE + (\n (32 + 2 + VOTE_INDEX_BYTES * answer_ids.length) * BOX_BYTE_MIN_BALANCE\n )\n assert (\n fund_min_bal_req.receiver == Global.current_application_address\n ), \"Payment must be to app address\"\n\n log(min_bal_req)\n assert fund_min_bal_req.amount == min_bal_req, \"Payment must be the exact min balance\"\n # Record the vote for each question\n cumulative_offset = UInt64(0)\n for question_index in urange(questions_count):\n # Load the user's vote for this question\n answer_option_index = answer_ids[question_index].native\n options_count = self.option_counts[question_index].native\n assert answer_option_index < options_count, \"Answer option index invalid\"\n self.increment_vote_in_box(cumulative_offset + answer_option_index)\n cumulative_offset += options_count\n self.votes_by_account[Txn.sender] = answer_ids.copy()\n self.voter_count += 1\n\n @subroutine\n def voting_open(self) -> bool:\n return (\n self.is_bootstrapped\n and not self.close_time\n and self.start_time <= Global.latest_timestamp <= self.end_time\n )\n\n @subroutine\n def already_voted(self) -> bool:\n return Txn.sender in self.votes_by_account\n\n @subroutine\n def store_option_counts(self, option_counts: VoteIndexArray) -> None:\n assert option_counts.length, \"option_counts should be non-empty\"\n assert option_counts.length <= 112, \"Can't have more than 112 questions\"\n\n total_options = UInt64(0)\n for item in option_counts:\n total_options += item.native\n assert total_options <= 128, \"Can't have more than 128 vote options\"\n\n self.option_counts = option_counts.copy()\n self.total_options = total_options\n\n @subroutine\n def allowed_to_vote(self, signature: Bytes) -> bool:\n ensure_budget(2000)\n return op.ed25519verify_bare(\n Txn.sender.bytes,\n signature,\n self.snapshot_public_key,\n )\n\n @subroutine\n def get_vote_from_box(self, index: UInt64) -> UInt64:\n return op.btoi(self.tally_box.extract(index, VOTE_COUNT_BYTES))\n\n @subroutine\n def increment_vote_in_box(self, index: UInt64) -> None:\n current_vote = self.get_vote_from_box(index)\n self.tally_box.replace(index, op.itob(current_vote + 1))\n\n\n@subroutine\ndef itoa(i: UInt64) -> String:\n digits = Bytes(b\"0123456789\")\n radix = digits.length\n if i < radix:\n return String.from_bytes(digits[i])\n return itoa(i \/\/ radix) + String.from_bytes(digits[i % radix])\n","repo_name":"algorandfoundation\/puya","path":"examples\/voting\/voting.py","language":"Python","license":"NOASSERTION","size":8705} {"code":"","repo_name":"algorandfoundation\/puya","path":"scripts\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"import csv\nimport subprocess\nfrom pathlib import Path\n\nfrom scripts.compile_all_examples import ProgramSizes\n\n_SCRIPTS_DIR = Path(__file__).parent\n_ROOT_DIR = _SCRIPTS_DIR.parent\n\n\ndef main() -> None:\n sizes_path = _ROOT_DIR \/ \"examples\" \/ \"sizes.txt\"\n curr_text = sizes_path.read_text(\"utf8\")\n prev_text = subprocess.run(\n [\"git\", \"show\", \"HEAD:examples\/sizes.txt\"],\n capture_output=True,\n text=True,\n check=True,\n cwd=_ROOT_DIR,\n ).stdout\n if prev_text == curr_text:\n return\n curr_sizes = ProgramSizes.load(curr_text).sizes\n prev_sizes = ProgramSizes.load(prev_text).sizes\n delta = ProgramSizes()\n assert curr_sizes.keys() == prev_sizes.keys(), \"can't analyse with different programs\"\n for program_name in curr_sizes:\n prev_prog_size = prev_sizes[program_name]\n curr_prog_size = curr_sizes[program_name]\n if prev_prog_size != curr_prog_size:\n for level in range(3):\n delta.sizes[program_name][level] = curr_prog_size[level] - prev_prog_size[level]\n _sizes_to_csv(delta)\n\n\ndef _sizes_to_csv(ps: ProgramSizes) -> None:\n tmp_dir = _ROOT_DIR \/ \"_tmp\"\n tmp_dir.mkdir(exist_ok=True)\n with (tmp_dir \/ \"sizes_diff.csv\").open(\"w\", encoding=\"utf8\") as output:\n writer = csv.writer(output)\n writer.writerow([\"Name\", \"O0\", \"O1\", \"O2\", \"O0#Ops\", \"O1#Ops\", \"O2#Ops\"])\n # copy sizes and sort by name\n for name, prog_sizes in sorted(ps.sizes.items()):\n o0, o1, o2 = (prog_sizes[i] for i in range(3))\n writer.writerow(\n map(str, (name, o0.bytecode, o1.bytecode, o2.bytecode, o0.ops, o1.ops, o2.ops))\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"algorandfoundation\/puya","path":"scripts\/analyse_sizes_diff.py","language":"Python","license":"NOASSERTION","size":1735} {"code":"import typing\nfrom collections import Counter\nfrom collections.abc import Iterator\nfrom pathlib import Path\n\nVCS_ROOT = Path(__file__).parent.parent\n\nOUTPUT_BASE_DIRS = [\"examples\", \"test_cases\"]\n\nCODE_INDENT = \" \"\n\nINTERESTING_OPS = frozenset(\n [\n # pure stack manipulation\n \"intc\",\n *[f\"intc_{i}\" for i in range(4)],\n \"bytec\",\n *[f\"bytec_{i}\" for i in range(4)],\n \"pushbytes\",\n \"pushbytess\",\n \"pushint\",\n \"pushints\",\n \"frame_dig\",\n \"frame_bury\",\n \"bury\",\n \"cover\",\n \"dig\",\n \"dup\",\n \"dup2\",\n \"dupn\",\n \"pop\",\n \"popn\",\n \"swap\",\n \"uncover\",\n # constants\n \"addr\",\n \"byte\",\n \"int\",\n \"method\",\n \"txn\",\n \"txna\",\n \"gtxn\",\n \"gtxna\",\n \"itxn\",\n \"itxna\",\n \"global\",\n \"pushint\",\n \"pushbytes\",\n \"gload\",\n \"gaid\",\n # other loads\n \"load\",\n ]\n)\n\n\ndef main() -> None:\n teal_blocks = read_all_blocks()\n single_op_blocks = (block[0] for block in teal_blocks if len(block) == 1)\n print(\"Single op block counts:\")\n for count, op in sorted(\n ((count, op) for op, count in Counter(single_op_blocks).items()), reverse=True\n ):\n print(f\" {count}x {op}\")\n\n window_size = 2\n while True:\n num_printed = 0\n print(f\"\\nInteresting op sequence of length {window_size} counts:\")\n seqs = [\n tuple(seq)\n for block in teal_blocks\n for seq in sliding_window(block, window_size)\n if INTERESTING_OPS.issuperset(seq)\n ]\n for count, ops in sorted(\n ((count, ops) for ops, count in Counter(seqs).items()), reverse=True\n )[:20]:\n if count == 1:\n break\n print(f\" {count}x {'; '.join(ops)}\")\n num_printed += 1\n if num_printed == 0:\n break\n window_size += 1\n\n\ndef read_all_blocks(*, include_clear_state: bool = True) -> list[list[str]]:\n teal_files = list[Path]()\n for output_base_dir in OUTPUT_BASE_DIRS:\n output_dir = VCS_ROOT \/ output_base_dir\n assert output_dir.is_dir()\n teal_files.extend(output_dir.rglob(\"*\/out\/*.approval.teal\"))\n if include_clear_state:\n teal_files.extend(output_dir.rglob(\"*\/out\/*.clear.teal\"))\n\n teal_blocks = list[list[str]]()\n for teal_file in teal_files:\n current_block = list[str]()\n teal = teal_file.read_text(\"utf8\")\n file_lines = teal.splitlines()\n assert file_lines[0].startswith(\"#pragma\")\n for line in file_lines[1:]:\n if not line.startswith(CODE_INDENT):\n # new block \/ function\n if current_block:\n teal_blocks.append(current_block)\n current_block = []\n else:\n op, *_ = line.split()\n if op:\n current_block.append(op)\n if current_block:\n teal_blocks.append(current_block)\n return teal_blocks\n\n\nT = typing.TypeVar(\"T\")\n\n\ndef sliding_window(seq: list[T], window_size: int) -> Iterator[list[T]]:\n for i in range(len(seq) - window_size + 1):\n yield seq[i : i + window_size]\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"algorandfoundation\/puya","path":"scripts\/analyse_teal_op_frequencies.py","language":"Python","license":"NOASSERTION","size":3342} {"code":"import argparse\nimport base64\nfrom pathlib import Path\n\nfrom algosdk.v2client.algod import AlgodClient\n\n\ndef main(path: list[Path]) -> None:\n algod_client = AlgodClient(algod_token=\"a\" * 64, algod_address=\"http:\/\/localhost:4001\")\n for p in path:\n response = algod_client.compile(p.read_text(\"utf8\"))\n compiled: str = response[\"result\"]\n compiled_bytes = base64.b64decode(compiled)\n p.with_suffix(\".teal.bin\").write_bytes(compiled_bytes)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(prog=\"assemble\")\n parser.add_argument(\"files\", type=Path, nargs=\"+\", metavar=\"FILE\")\n args = parser.parse_args()\n main(args.files)\n","repo_name":"algorandfoundation\/puya","path":"scripts\/assemble.py","language":"Python","license":"NOASSERTION","size":677} {"code":"#!\/usr\/bin\/env python3\nimport argparse\nimport json\nimport operator\nimport os\nimport re\nimport shutil\nimport subprocess\nimport sys\nfrom collections import defaultdict\nfrom collections.abc import Iterable\nfrom concurrent.futures import ProcessPoolExecutor\nfrom pathlib import Path\n\nimport algokit_utils.deploy\nimport attrs\nimport prettytable\n\nSCRIPT_DIR = Path(__file__).parent\nGIT_ROOT = SCRIPT_DIR.parent\nCONTRACT_ROOT_DIRS = [\n GIT_ROOT \/ \"examples\",\n GIT_ROOT \/ \"test_cases\",\n]\nSIZE_TALLY_PATH = GIT_ROOT \/ \"examples\" \/ \"sizes.txt\"\nENV_WITH_NO_COLOR = dict(os.environ) | {\n \"NO_COLOR\": \"1\", # disable colour output\n \"PYTHONUTF8\": \"1\", # force utf8 on windows\n}\n# iterate optimization levels first and with O1 first and then cases, this is a workaround\n# to prevent race conditions that occur when the mypy parsing stage of O0, O2 tries to\n# read the client_.py output from the 01 level before it is finished writing to\n# disk\nDEFAULT_OPTIMIZATION = (1, 0, 2)\n\n\ndef get_root_and_relative_path(path: Path) -> tuple[Path, Path]:\n for root in CONTRACT_ROOT_DIRS:\n if path.is_relative_to(root):\n return root, path.relative_to(root)\n raise RuntimeError(f\"{path} is not relative to a known example\")\n\n\ndef get_unique_name(path: Path) -> str:\n _, rel_path = get_root_and_relative_path(path)\n # strip suffixes\n while rel_path.suffixes:\n rel_path = rel_path.with_suffix(\"\")\n\n use_parts = []\n for part in rel_path.parts:\n if \"MyContract\" in part:\n use_parts.append(\"\".join(part.split(\"MyContract\")))\n elif \"Contract\" in part:\n use_parts.append(\"\".join(part.split(\"Contract\")))\n elif part.endswith((f\"out{SUFFIX_O0}\", f\"out{SUFFIX_O1}\", f\"out{SUFFIX_O2}\")):\n pass\n else:\n use_parts.append(part)\n return \"\/\".join(filter(None, use_parts))\n\n\n@attrs.frozen\nclass Size:\n bytecode: int | None = None\n ops: int | None = None\n\n def __add__(self, other: object) -> \"Size\":\n if not isinstance(other, Size):\n return NotImplemented\n return Size(\n bytecode=(self.bytecode or 0) + (other.bytecode or 0),\n ops=(self.ops or 0) + (other.ops or 0),\n )\n\n def __sub__(self, other: object) -> \"Size\":\n if not isinstance(other, Size):\n return NotImplemented\n return Size(\n bytecode=(self.bytecode or 0) - (other.bytecode or 0),\n ops=(self.ops or 0) - (other.ops or 0),\n )\n\n\ndef _program_to_sizes() -> defaultdict[str, defaultdict[int, Size]]:\n def _opt_to_sizes() -> defaultdict[int, Size]:\n return defaultdict[int, Size](Size)\n\n return defaultdict[str, defaultdict[int, Size]](_opt_to_sizes)\n\n\n@attrs.define(str=False)\nclass ProgramSizes:\n sizes: defaultdict[str, defaultdict[int, Size]] = attrs.field(factory=_program_to_sizes)\n\n def add_at_level(self, level: int, teal_file: Path, bin_file: Path) -> None:\n name = get_unique_name(bin_file)\n # this combines both approval and clear program sizes\n self.sizes[name][level] += Size(\n bytecode=bin_file.stat().st_size,\n ops=_get_num_teal_ops(teal_file),\n )\n\n @classmethod\n def load(cls, text: str) -> \"ProgramSizes\":\n lines = list(filter(None, text.splitlines()))\n program_sizes = ProgramSizes()\n sizes = program_sizes.sizes\n for line in lines[1:-1]:\n name, o0, o1, o2, _, o0_ops, o1_ops, o2_ops = line.rsplit(maxsplit=7)\n name = name.strip()\n for opt, (bin_str, ops_str) in enumerate(((o0, o0_ops), (o1, o1_ops), (o2, o2_ops))):\n if bin_str == \"None\":\n continue\n if bin_str == \"-\":\n previous = sizes[name][opt - 1]\n bytecode = previous.bytecode\n ops = previous.ops\n else:\n bytecode = int(bin_str)\n ops = int(ops_str)\n sizes[name][opt] = Size(bytecode=bytecode, ops=ops)\n return program_sizes\n\n def __str__(self) -> str:\n writer = prettytable.PrettyTable(\n field_names=[\"Name\", \"O0\", \"O1\", \"O2\", \"|\", \"O0#Ops\", \"O1#Ops\", \"O2#Ops\"],\n header=True,\n border=False,\n min_width=6,\n left_padding_width=0,\n right_padding_width=0,\n align=\"r\",\n )\n writer.align[\"Name\"] = \"l\"\n writer.align[\"|\"] = \"c\"\n # copy sizes and sort by name\n sizes = defaultdict(\n self.sizes.default_factory, {p: self.sizes[p].copy() for p in sorted(self.sizes)}\n )\n totals = {i: Size() for i in range(3)}\n for prog_sizes in sizes.values():\n for i in range(3):\n totals[i] += prog_sizes[i]\n # Add totals at end\n sizes[\"Total\"].update(totals)\n for name, prog_sizes in sizes.items():\n o0, o1, o2 = (prog_sizes[i] for i in range(3))\n row = list(\n map(\n str, (name, o0.bytecode, o1.bytecode, o2.bytecode, \"|\", o0.ops, o1.ops, o2.ops)\n )\n )\n if o0 == o1:\n for i in (2, 6):\n row[i] = \"-\"\n if o1 == o2:\n for i in (3, 7):\n row[i] = \"-\"\n writer.add_row(row)\n return writer.get_string()\n\n\ndef _get_num_teal_ops(path: Path) -> int:\n ops = 0\n teal = path.read_text(\"utf8\")\n for line in algokit_utils.deploy.strip_comments(teal).splitlines():\n line = line.strip()\n if not line or line.endswith(\":\") or line.startswith(\"#\"):\n # ignore comment only lines, labels and pragmas\n pass\n else:\n ops += 1\n\n return ops\n\n\n@attrs.define\nclass CompilationResult:\n rel_path: str\n ok: bool\n bin_files: list[Path]\n stdout: str\n\n\ndef _stabilise_logs(stdout: str) -> list[str]:\n return [\n line.replace(\"\\\\\", \"\/\").replace(str(GIT_ROOT).replace(\"\\\\\", \"\/\"), \"\")\n for line in stdout.splitlines()\n if not line.startswith(\n (\n \"debug: Skipping algopy stub \",\n \"debug: Skipping typeshed stub \",\n \"warning: Skipping stub: \",\n \"debug: Skipping stdlib stub \",\n \"debug: Building AWST for \",\n \"debug: Discovered user module \",\n # ignore platform specific paths\n \"debug: Using python executable: \",\n \"debug: Using python site-packages: \",\n \"debug: Found algopy: \",\n )\n )\n ]\n\n\ndef checked_compile(p: Path, flags: list[str], *, out_suffix: str) -> CompilationResult:\n assert p.is_dir()\n out_dir = (p \/ f\"out{out_suffix}\").resolve()\n template_vars_path = p \/ \"template.vars\"\n\n root, rel_path_ = get_root_and_relative_path(p)\n rel_path = str(rel_path_)\n\n if out_dir.exists():\n for prev_out_file in out_dir.iterdir():\n if prev_out_file.is_dir():\n shutil.rmtree(prev_out_file)\n elif prev_out_file.suffix != \".log\":\n prev_out_file.unlink()\n cmd = [\n \"poetry\",\n \"run\",\n \"puyapy\",\n *flags,\n f\"--out-dir={out_dir}\",\n \"--output-destructured-ir\",\n \"--output-bytecode\",\n \"--log-level=debug\",\n *_load_template_vars(template_vars_path),\n rel_path,\n ]\n result = subprocess.run(\n cmd,\n cwd=root,\n check=False,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n text=True,\n env=ENV_WITH_NO_COLOR,\n encoding=\"utf-8\",\n )\n bin_files_written = re.findall(r\"info: Writing (.+\\.bin)\", result.stdout)\n\n # normalize ARC-56 output\n arc56_files_written = re.findall(r\"info: Writing (.+\\.arc56\\.json)\", result.stdout)\n for arc56_file in arc56_files_written:\n _normalize_arc56(root \/ arc56_file)\n\n log_path = p \/ f\"puya{out_suffix}.log\"\n log_txt = \"\\n\".join(_stabilise_logs(result.stdout))\n log_path.write_text(log_txt, encoding=\"utf8\")\n\n ok = result.returncode == 0\n return CompilationResult(\n rel_path=rel_path,\n ok=ok,\n bin_files=[root \/ p for p in bin_files_written],\n stdout=result.stdout if not ok else \"\", # don't thunk stdout if no errors\n )\n\n\ndef _normalize_arc56(path: Path) -> None:\n arc56 = json.loads(path.read_text())\n compiler_version = arc56.get(\"compilerInfo\", {}).get(\"compilerVersion\", {})\n compiler_version[\"major\"] = 99\n compiler_version[\"minor\"] = 99\n compiler_version[\"patch\"] = 99\n path.write_text(json.dumps(arc56, indent=4), encoding=\"utf8\")\n\n\ndef _load_template_vars(path: Path) -> Iterable[str]:\n if path.exists():\n for line in path.read_text(\"utf8\").splitlines():\n if line.startswith(\"prefix=\"):\n prefix = line.removeprefix(\"prefix=\")\n yield f\"--template-vars-prefix={prefix}\"\n else:\n yield f\"-T={line}\"\n\n\nSUFFIX_O0 = \"_unoptimized\"\nSUFFIX_O1 = \"\"\nSUFFIX_O2 = \"_O2\"\n\n\ndef _compile_for_level(arg: tuple[Path, int]) -> tuple[CompilationResult, int]:\n p, optimization_level = arg\n if optimization_level == 0:\n flags = [\n \"-O0\",\n \"--no-output-arc32\",\n ]\n out_suffix = SUFFIX_O0\n elif optimization_level == 2:\n flags = [\n \"-O2\",\n \"--no-output-arc32\",\n \"-g0\",\n ]\n out_suffix = SUFFIX_O2\n else:\n assert optimization_level == 1\n flags = [\n \"-O1\",\n \"--output-awst\",\n \"--output-ssa-ir\",\n \"--output-optimization-ir\",\n \"--output-memory-ir\",\n \"--output-client\",\n \"--output-source-map\",\n \"--output-arc56\",\n ]\n out_suffix = SUFFIX_O1\n result = checked_compile(p, flags=flags, out_suffix=out_suffix)\n return result, optimization_level\n\n\n@attrs.define(kw_only=True)\nclass CompileAllOptions:\n limit_to: list[Path] = attrs.field(factory=list)\n optimization_level: list[int] = attrs.field(factory=list)\n\n\ndef main(options: CompileAllOptions) -> None:\n limit_to = options.limit_to\n if limit_to:\n to_compile = [Path(x).resolve() for x in limit_to]\n else:\n to_compile = [\n item\n for root in CONTRACT_ROOT_DIRS\n for item in root.iterdir()\n if item.is_dir() and any(item.glob(\"*.py\"))\n ]\n\n failures = list[tuple[str, str]]()\n program_sizes = ProgramSizes()\n # use selected opt levels, but retain original order\n opt_levels = [\n o\n for o in DEFAULT_OPTIMIZATION\n if o in (options.optimization_level or DEFAULT_OPTIMIZATION)\n ]\n with ProcessPoolExecutor() as executor:\n args = [(case, level) for level in opt_levels for case in to_compile]\n for compilation_result, level in executor.map(_compile_for_level, args):\n rel_path = compilation_result.rel_path\n case_name = f\"{rel_path} -O{level}\"\n for bin_file in compilation_result.bin_files:\n program_sizes.add_at_level(level, bin_file.with_suffix(\".teal\"), bin_file)\n if compilation_result.ok:\n print(f\"\u2705 {case_name}\")\n else:\n print(f\"\ud83d\udca5 {case_name}\", file=sys.stderr)\n failures.append((case_name, compilation_result.stdout))\n\n if failures:\n print(\"Compilation failures:\")\n for name, stdout in sorted(failures, key=operator.itemgetter(0)):\n print(f\" ~~~ {name} ~~~ \")\n print(\n \"\\n\".join(\n ln\n for ln in stdout.splitlines()\n if (ln.startswith(\"debug: Traceback \") or not ln.startswith(\"debug: \"))\n )\n )\n print(\"Updating sizes.txt\")\n if limit_to or options.optimization_level:\n print(\"Loading existing sizes.txt\")\n # load existing sizes for non-default options\n merged = ProgramSizes.load(SIZE_TALLY_PATH.read_text(\"utf8\"))\n for program, sizes in program_sizes.sizes.items():\n for o, size in sizes.items():\n merged.sizes[program][o] = size\n program_sizes = merged\n SIZE_TALLY_PATH.write_text(str(program_sizes))\n sys.exit(len(failures))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"limit_to\", type=Path, nargs=\"*\", metavar=\"LIMIT_TO\")\n parser.add_argument(\n \"-O\",\n \"--optimization-level\",\n action=\"extend\",\n type=int,\n choices=DEFAULT_OPTIMIZATION,\n nargs=\"+\",\n help=\"Set optimization level of output TEAL \/ AVM bytecode\",\n )\n options = CompileAllOptions()\n parser.parse_args(namespace=options)\n main(options)\n","repo_name":"algorandfoundation\/puya","path":"scripts\/compile_all_examples.py","language":"Python","license":"NOASSERTION","size":12912} {"code":"import argparse\nimport contextlib\nimport json\nimport typing\nfrom collections.abc import Iterator\nfrom dataclasses import dataclass\nfrom functools import cached_property\nfrom pathlib import Path\n\nfrom algosdk.atomic_transaction_composer import (\n AccountTransactionSigner,\n AtomicTransactionComposer,\n TransactionWithSigner,\n)\nfrom algosdk.kmd import KMDClient\nfrom algosdk.transaction import ApplicationCallTxn, OnComplete, create_dryrun\nfrom algosdk.v2client.algod import AlgodClient\n\nDEFAULT_ALGOD_ADDRESS = \"http:\/\/localhost:4001\"\nDEFAULT_KMD_ADDRESS = \"http:\/\/localhost:4002\"\nDEFAULT_TOKEN = \"a\" * 64\nDEFAULT_KMD_WALLET_NAME = \"unencrypted-default-wallet\"\nDEFAULT_KMD_WALLET_PASSWORD = \"\"\n\n\ndef main(approval_path: Path, clear_path: Path) -> None:\n response = dryrun_create(approval_path.read_bytes(), clear_path.read_bytes())\n print(json.dumps(response, indent=4))\n\n\ndef dryrun_create(\n approval_binary: bytes,\n clear_binary: bytes,\n) -> dict[str, typing.Any]:\n algod = AlgodClient(algod_token=DEFAULT_TOKEN, algod_address=DEFAULT_ALGOD_ADDRESS)\n account, *_ = get_accounts()\n atc = AtomicTransactionComposer()\n atc.add_transaction(\n TransactionWithSigner(\n txn=ApplicationCallTxn(\n sender=account.address,\n sp=algod.suggested_params(),\n index=0,\n on_complete=OnComplete.NoOpOC,\n approval_program=approval_binary,\n clear_program=clear_binary,\n ),\n signer=account.signer,\n )\n )\n\n atc.execute(algod, 4)\n signed = atc.gather_signatures()\n dryrun_request = create_dryrun(algod, signed)\n\n return algod.dryrun(dryrun_request.dictify())\n\n\n@dataclass(kw_only=True)\nclass LocalAccount:\n \"\"\"LocalAccount is a simple dataclass to hold a localnet account details\"\"\"\n\n #: The address of a localnet account\n address: str\n #: The base64 encoded private key of the account\n private_key: str\n\n #: An AccountTransactionSigner that can be used as a TransactionSigner\n @cached_property\n def signer(self) -> AccountTransactionSigner:\n return AccountTransactionSigner(self.private_key)\n\n\ndef get_accounts(\n kmd_address: str = DEFAULT_KMD_ADDRESS,\n kmd_token: str = DEFAULT_TOKEN,\n wallet_name: str = DEFAULT_KMD_WALLET_NAME,\n wallet_password: str = DEFAULT_KMD_WALLET_PASSWORD,\n) -> list[LocalAccount]:\n \"\"\"gets all the accounts in the localnet kmd, defaults\n to the `unencrypted-default-wallet` created on private networks automatically\"\"\"\n kmd = KMDClient(kmd_token, kmd_address)\n with wallet_handle_by_name(kmd, wallet_name, wallet_password) as wallet_handle:\n return [\n LocalAccount(\n address=address,\n private_key=kmd.export_key(\n wallet_handle,\n wallet_password,\n address,\n ),\n )\n for address in kmd.list_keys(wallet_handle)\n ]\n\n\n@contextlib.contextmanager\ndef wallet_handle_by_name(kmd: KMDClient, wallet_name: str, wallet_password: str) -> Iterator[str]:\n wallets = kmd.list_wallets()\n\n try:\n wallet_id = next(iter(w[\"id\"] for w in wallets if w[\"name\"] == wallet_name))\n except StopIteration:\n raise Exception(f\"Wallet not found: {wallet_name}\") from None\n\n wallet_handle = kmd.init_wallet_handle(\n wallet_id,\n wallet_password,\n )\n try:\n yield wallet_handle\n finally:\n kmd.release_wallet_handle(wallet_handle)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(prog=\"dry_run_create\")\n parser.add_argument(\"approval_file\", type=Path, metavar=\"FILE\")\n parser.add_argument(\"clear_file\", type=Path, metavar=\"FILE\")\n args = parser.parse_args()\n main(args.approval_file, args.clear_file)\n","repo_name":"algorandfoundation\/puya","path":"scripts\/dry_run_create.py","language":"Python","license":"NOASSERTION","size":3852} {"code":"#!\/usr\/bin\/env python3\nimport json\nimport subprocess\nfrom pathlib import Path\n\nfrom puya import log\nfrom puya.ussemble.op_spec_models import ImmediateEnum, ImmediateKind, OpSpec\nfrom scripts.transform_lang_spec import (\n LanguageSpec,\n)\n\nlogger = log.get_logger(__name__)\nVCS_ROOT = Path(__file__).parent.parent\n\n\ndef main() -> None:\n spec_path = VCS_ROOT \/ \"langspec.puya.json\"\n lang_spec_json = json.loads(spec_path.read_text(encoding=\"utf-8\"))\n lang_spec = LanguageSpec.from_json(lang_spec_json)\n\n ops = build_op_spec(lang_spec)\n output_ops(ops)\n\n\ndef build_op_spec(lang_spec: LanguageSpec) -> dict[str, OpSpec]:\n ops = {}\n for op in sorted(lang_spec.ops.values(), key=lambda x: x.code):\n immediates = list[ImmediateKind | ImmediateEnum]()\n for imm in op.immediate_args:\n if imm.arg_enum is None:\n immediates.append(ImmediateKind[imm.immediate_type.name])\n else:\n immediates.append(\n ImmediateEnum(\n codes={e.name: e.value for e in lang_spec.arg_enums[imm.arg_enum]}\n )\n )\n op_spec = OpSpec(name=op.name, code=op.code, immediates=immediates)\n ops[op_spec.name] = op_spec\n\n return ops\n\n\ndef output_ops(\n ops: dict[str, OpSpec],\n) -> None:\n file: list[str] = [\n \"from puya.ussemble.op_spec_models import ImmediateEnum, ImmediateKind, OpSpec\",\n f\"OP_SPECS = {ops!r}\",\n ]\n\n output_path = VCS_ROOT \/ \"src\" \/ \"puya\" \/ \"ussemble\" \/ \"op_spec.py\"\n output_path.write_text(\"\\n\".join(file), encoding=\"utf-8\")\n subprocess.run([\"ruff\", \"format\", str(output_path)], check=True, cwd=VCS_ROOT)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"algorandfoundation\/puya","path":"scripts\/generate_assemble_op_spec.py","language":"Python","license":"NOASSERTION","size":1735} {"code":"import builtins\nimport json\nimport keyword\nimport subprocess\nimport textwrap\nfrom collections.abc import Iterable, Iterator\nfrom pathlib import Path\n\nfrom puya import log\nfrom puya.ir.avm_ops_models import (\n AVMOpData,\n DynamicVariants,\n ImmediateKind,\n OpSignature,\n RunMode,\n StackType,\n Variant,\n)\nfrom puya.utils import normalise_path_to_str\nfrom scripts import transform_lang_spec as langspec\n\nlogger = log.get_logger(__name__)\nVCS_ROOT = Path(__file__).parent.parent\n\nSUPPORTED_IMMEDIATE_KINDS = (langspec.ImmediateKind.uint8, langspec.ImmediateKind.arg_enum)\n\noperator_names = {\n # bool\n \"&&\": \"and\",\n \"||\": \"or\",\n \"!\": \"not\",\n # compare\n \"==\": \"eq\",\n \"!=\": \"neq\",\n \"<\": \"lt\",\n \"<=\": \"lte\",\n \">\": \"gt\",\n \">=\": \"gte\",\n # bitwise\n \"&\": \"bitwise_and\",\n \"^\": \"bitwise_xor\",\n \"|\": \"bitwise_or\",\n \"~\": \"bitwise_not\",\n # math\n \"+\": \"add\",\n \"-\": \"sub\",\n \"*\": \"mul\",\n \"\/\": \"div_floor\",\n \"%\": \"mod\",\n}\n\nEXCLUDED_OPCODES = {\n # flow control\n \"bnz\",\n \"bz\",\n \"b\",\n \"callsub\",\n \"retsub\",\n \"proto\",\n \"switch\",\n \"match\",\n # pure stack manipulation\n \"intc\",\n *[f\"intc_{i}\" for i in range(4)],\n \"bytec\",\n *[f\"bytec_{i}\" for i in range(4)],\n \"pushbytes\",\n \"pushbytess\",\n \"pushint\",\n \"pushints\",\n \"frame_dig\",\n \"frame_bury\",\n \"bury\",\n \"cover\",\n \"dig\",\n \"dup\",\n \"dup2\",\n \"dupn\",\n \"pop\",\n \"popn\",\n \"swap\",\n \"uncover\",\n # modifies what other op codes with immediates point to\n \"intcblock\",\n \"bytecblock\",\n # halting\n \"err\",\n \"return\",\n}\n\n\ndef as_list_str(values: Iterable[str]) -> str | None:\n inner = \", \".join(values)\n if not inner:\n return None\n else:\n return f\"[{inner}]\"\n\n\nBUILTIN_NAMES = frozenset(dir(builtins))\n\n\ndef get_op_name(op: langspec.Op) -> str:\n op_code = op.name\n if op_code.isidentifier():\n op_name = op_code\n elif op_code[0] == \"b\":\n op_name = operator_names[op_code[1:]] + \"_bytes\"\n else:\n op_name = operator_names[op_code]\n if keyword.iskeyword(op_name) or keyword.issoftkeyword(op_name) or op_name in BUILTIN_NAMES:\n op_name += \"_\"\n return op_name\n\n\ndef generate_op_node(\n enums: dict[str, list[langspec.ArgEnum]], op_name: str, op: langspec.Op\n) -> Iterator[str]:\n assert not op.halts, \"op halts\"\n dynamic_im_index: int | None = None\n for idx, im in enumerate(op.immediate_args):\n if im.modifies_stack_input is not None:\n assert im.modifies_stack_output is None, \"\ud83d\udc80\"\n assert dynamic_im_index is None, \"\ud83e\udea6\"\n\n dynamic_im_index = idx\n elif im.modifies_stack_output is not None:\n assert dynamic_im_index is None, \"\ud83e\udea6\"\n dynamic_im_index = idx\n\n immediate_types = tuple(get_immediate_type(im) for im in op.immediate_args)\n op_code = op.name\n cost = op.cost.value\n variant: DynamicVariants | Variant\n\n stack_args = [get_stack_type(arg.stack_type) for arg in op.stack_inputs]\n stack_returns = [get_stack_type(out.stack_type) for out in op.stack_outputs]\n if dynamic_im_index is None:\n variant = Variant(\n enum=None,\n signature=OpSignature(\n args=stack_args,\n returns=stack_returns,\n ),\n supported_modes=_map_run_mode(op.mode),\n min_avm_version=op.min_avm_version,\n )\n else:\n im = op.immediate_args[dynamic_im_index]\n assert im.arg_enum is not None, \"\ud83d\udca5\"\n variant = DynamicVariants(\n immediate_index=dynamic_im_index,\n variant_map={},\n )\n if im.modifies_stack_input is not None:\n list_index = im.modifies_stack_input\n to_mod = stack_args\n else:\n assert im.modifies_stack_output is not None\n list_index = im.modifies_stack_output\n to_mod = stack_returns\n for arg_enum in enums[im.arg_enum]:\n assert arg_enum.stack_type is not None, \"\ud83e\udd15\"\n to_mod[list_index] = get_stack_type(arg_enum.stack_type)\n variant.variant_map[arg_enum.name] = Variant(\n enum=arg_enum.name,\n signature=OpSignature(\n args=list(stack_args),\n returns=list(stack_returns),\n ),\n supported_modes=_map_run_mode(arg_enum.mode),\n min_avm_version=arg_enum.min_avm_version,\n )\n\n data = AVMOpData(\n op_code=op_code,\n immediate_types=immediate_types,\n variants=variant,\n cost=cost,\n min_avm_version=op.min_avm_version,\n supported_modes=_map_run_mode(op.mode),\n )\n yield f\"{op_name} = {data!r}\"\n if op.doc:\n yield '\"\"\"'\n for idx, doc_ln in enumerate(op.doc):\n if idx > 0:\n yield \"\"\n yield from textwrap.wrap(doc_ln, width=99 - 4)\n yield '\"\"\"'\n yield \"\"\n\n\ndef _map_run_mode(mode: langspec.RunMode) -> RunMode:\n match mode:\n case langspec.RunMode.app:\n return RunMode.app\n case langspec.RunMode.sig:\n return RunMode.lsig\n case langspec.RunMode.any:\n return RunMode.any\n case _:\n raise ValueError(f\"Unsupported mode {mode}\")\n\n\ndef get_stack_type(stack_type: langspec.StackType) -> StackType:\n if stack_type.name.startswith(\"bytes_\"):\n return StackType.bytes\n else:\n return StackType[stack_type.name]\n\n\ndef get_immediate_type(immediate: langspec.Immediate) -> ImmediateKind:\n assert immediate.immediate_type in SUPPORTED_IMMEDIATE_KINDS, (\n \"bad immediate kind\",\n immediate.immediate_type,\n )\n return ImmediateKind[immediate.immediate_type.name]\n\n\ndef generate_file(lang_spec: langspec.LanguageSpec) -> Iterator[str]:\n script_path = normalise_path_to_str(Path(__file__).relative_to(VCS_ROOT))\n preamble = f\"\"\"\n# AUTO GENERATED BY {script_path}, DO NOT EDIT\nimport enum\nfrom collections.abc import Sequence\n\nfrom puya.errors import InternalError\nfrom puya.ir.avm_ops_models import (\n AVMOpData,\n DynamicVariants,\n ImmediateKind,\n OpSignature,\n RunMode,\n StackType,\n Variant\n)\n\n\nclass AVMOp(enum.StrEnum):\n code: str\n immediate_types: Sequence[ImmediateKind]\n _variants: Variant | DynamicVariants\n cost: int | None\n min_avm_version: int\n\n def __new__(cls, data: AVMOpData | str) -> \"AVMOp\":\n # the weird union type on data && then assert,\n # is to shut mypy up when it wrongly infers the arg type of\n # e.g. AVMOp(\"+\") to be invalid\n assert isinstance(data, AVMOpData)\n op_code = data.op_code\n obj = str.__new__(cls, op_code)\n obj._value_ = op_code\n obj.code = op_code\n obj.immediate_types = tuple(data.immediate_types)\n obj._variants = data.variants # noqa: SLF001\n obj.cost = data.cost\n obj.min_avm_version = data.min_avm_version\n return obj\n\n def get_variant(self, immediates: Sequence[str | int]) -> Variant:\n if isinstance(self._variants, Variant):\n return self._variants\n im = immediates[self._variants.immediate_index]\n assert isinstance(im, str)\n try:\n return self._variants.variant_map[im]\n except KeyError as ex:\n raise InternalError(f\"Unknown immediate for {{self.code}}: {{im}}\") from ex\n \"\"\"\n yield from preamble.strip().splitlines()\n yield \"\"\n ops_by_name = {}\n for op in lang_spec.ops.values():\n if op.name in EXCLUDED_OPCODES:\n logger.info(f\"Skipping {op.name} due to specific exclusion\")\n else:\n ops_by_name[get_op_name(op)] = op\n for op_name, op in sorted(ops_by_name.items()):\n yield textwrap.indent(\n \"\\n\".join(generate_op_node(lang_spec.arg_enums, op_name, op)), \" \" * 4\n )\n\n\ndef main() -> None:\n spec_path = VCS_ROOT \/ \"langspec.puya.json\"\n\n lang_spec_json = json.loads(spec_path.read_text(encoding=\"utf-8\"))\n lang_spec = langspec.LanguageSpec.from_json(lang_spec_json)\n\n output = \"\\n\".join(generate_file(lang_spec))\n\n ast_gen_path = VCS_ROOT \/ \"src\" \/ \"puya\" \/ \"ir\" \/ \"avm_ops.py\"\n ast_gen_path.write_text(output, encoding=\"utf-8\")\n subprocess.run([\"ruff\", \"format\", str(ast_gen_path)], check=True, cwd=VCS_ROOT)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"algorandfoundation\/puya","path":"scripts\/generate_avm_ops.py","language":"Python","license":"NOASSERTION","size":8430} {"code":"#!\/usr\/bin\/env python3\nimport subprocess\nimport sys\nimport typing\nfrom collections.abc import Callable\nfrom pathlib import Path\n\nsys.path.insert(0, str(Path(__file__).parent.parent \/ \"src\" \/ \"puyapy\" \/ \"_vendor\"))\n\n\nimport attrs\nimport mypy.build\nimport mypy.nodes\nfrom mypy.visitor import NodeVisitor\n\nfrom puyapy.compile import get_mypy_options\nfrom puyapy.parse import parse_and_typecheck\n\nSCRIPTS_DIR = Path(__file__).parent\nVCS_ROOT = SCRIPTS_DIR.parent\nSRC_DIR = VCS_ROOT \/ \"src\"\nDOCS_DIR = VCS_ROOT \/ \"docs\"\nSTUBS_DIR = VCS_ROOT \/ \"stubs\" \/ \"algopy-stubs\"\nSTUBS_DOC_DIR = DOCS_DIR \/ \"algopy-stubs\"\n\n\n@attrs.define\nclass ModuleImports:\n from_imports: dict[str, str | None] = attrs.field(factory=dict)\n import_all: bool = False\n import_module: bool = False\n\n\ndef main() -> None:\n manager, _ = parse_and_typecheck([STUBS_DIR], get_mypy_options())\n output_doc_stubs(manager)\n run_sphinx()\n\n\ndef output_doc_stubs(manager: mypy.build.BuildManager) -> None:\n # parse and output reformatted __init__.pyi\n stub = DocStub.process_module(manager, \"algopy\")\n algopy_direct_imports = stub.collected_imports[\"algopy\"]\n # remove any algopy imports that are now defined in __init__.py itself\n output_combined_stub(stub, STUBS_DOC_DIR \/ \"__init__.pyi\")\n\n # remaining imports from algopy are other public modules\n # parse and output them too\n for other_stub_name in algopy_direct_imports.from_imports:\n stub = DocStub.process_module(manager, f\"algopy.{other_stub_name}\")\n output_combined_stub(stub, STUBS_DOC_DIR \/ f\"{other_stub_name}.pyi\")\n\n\ndef output_combined_stub(stubs: \"DocStub\", output: Path) -> None:\n # remove algopy imports that have been inlined\n lines = [\"# ruff: noqa: A001, E501, F403, PYI021, PYI034, W291\"]\n rexported = list[str]()\n for module, imports in stubs.collected_imports.items():\n if imports.import_module:\n lines.append(f\"import {module}\")\n if imports.from_imports:\n rexported.extend(filter(None, imports.from_imports.values()))\n from_imports = \", \".join(_name_as(k, v) for k, v in imports.from_imports.items())\n lines.append(f\"from {module} import {from_imports}\")\n lines.extend([\"\", \"\"])\n\n # assemble __all__\n lines.append(\"__all__ = [\")\n for symbol in (*rexported, *stubs.collected_symbols):\n if symbol.startswith(\"_\"):\n continue\n lines.append(f' \"{symbol}\",')\n lines.append(\"]\")\n\n # assemble symbols\n lines.extend(stubs.collected_symbols.values())\n\n # output and linting\n output.parent.mkdir(parents=True, exist_ok=True)\n output.write_text(\"\\n\".join(lines))\n\n subprocess.run([\"ruff\", \"format\", str(output)], check=True, cwd=VCS_ROOT)\n subprocess.run([\"ruff\", \"check\", \"--fix\", str(output)], check=True, cwd=VCS_ROOT)\n\n\ndef run_sphinx() -> None:\n subprocess.run(\n [\"sphinx-build\", \".\", \"_build\", \"-W\", \"--keep-going\", \"-n\", \"-E\"], check=True, cwd=DOCS_DIR\n )\n\n\n@attrs.define(kw_only=True)\nclass ClassBases:\n klass: mypy.nodes.ClassDef\n bases: list[mypy.nodes.Expression]\n protocol_bases: list[tuple[mypy.nodes.MypyFile, mypy.nodes.ClassDef]]\n\n\n@attrs.define\nclass SymbolCollector(NodeVisitor[None]):\n file: mypy.nodes.MypyFile\n read_source: Callable[[str], list[str] | None]\n all_classes: dict[str, tuple[mypy.nodes.MypyFile, mypy.nodes.ClassDef]]\n inlined_protocols: dict[str, set[str]]\n symbols: dict[str, str] = attrs.field(factory=dict)\n last_stmt: mypy.nodes.Statement | None = None\n\n def get_src(\n self, node: mypy.nodes.Context, *, path: str | None = None, entire_lines: bool = True\n ) -> str:\n columns: tuple[int, int] | None = None\n if node.end_column and not entire_lines:\n columns = (node.column, node.end_column)\n return self.get_src_from_lines(node.line, node.end_line or node.line, path, columns)\n\n def get_src_from_lines(\n self,\n line: int,\n end_line: int,\n path: str | None = None,\n columns: tuple[int, int] | None = None,\n ) -> str:\n src = self.read_source(path or self.file.path)\n if not src:\n raise Exception(\"Could not get src\")\n lines = src[line - 1 : end_line]\n if columns:\n lines[-1] = lines[-1][: columns[1]]\n lines[0] = lines[0][columns[0] :]\n return \"\\n\".join(lines)\n\n def visit_mypy_file(self, o: mypy.nodes.MypyFile) -> None:\n for stmt in o.defs:\n stmt.accept(self)\n self.last_stmt = stmt\n\n def _get_bases(self, klass: mypy.nodes.ClassDef) -> ClassBases:\n bases = list[mypy.nodes.Expression]()\n inline = list[tuple[mypy.nodes.MypyFile, mypy.nodes.ClassDef]]()\n for base in klass.base_type_exprs:\n if (\n isinstance(base, mypy.nodes.NameExpr)\n and _should_inline_module(base.fullname)\n and self._is_protocol(base.fullname)\n ):\n inline.append(self.all_classes[base.fullname])\n else:\n bases.append(base)\n return ClassBases(klass=klass, bases=bases, protocol_bases=inline)\n\n def _get_inlined_class(self, klass: ClassBases) -> str:\n # TODO: what about class keywords\n klass_str = f\"class {klass.klass.name}\"\n if klass.bases:\n klass_str += f\"({', '.join(self.get_src(b, entire_lines=False) for b in klass.bases)})\"\n src = [f\"{klass_str}:\"]\n src.extend(self.get_src(member) for member in klass.klass.defs.body)\n for base_class_file, base_class in klass.protocol_bases:\n self.inlined_protocols.setdefault(base_class_file.fullname, set()).add(base_class.name)\n src.extend(\n self.get_src(member, path=base_class_file.path) for member in base_class.defs.body\n )\n return \"\\n\".join(src)\n\n def visit_class_def(self, o: mypy.nodes.ClassDef) -> None:\n self.all_classes[o.fullname] = self.file, o\n class_bases = self._get_bases(o)\n if class_bases.protocol_bases:\n self.symbols[o.name] = self._get_inlined_class(class_bases)\n else:\n self.symbols[o.name] = self.get_src(o)\n\n def visit_func_def(self, o: mypy.nodes.FuncDef) -> None:\n self.symbols[o.name] = self.get_src(o)\n\n def visit_overloaded_func_def(self, o: mypy.nodes.OverloadedFuncDef) -> None:\n line = o.line\n end_line = o.end_line or o.line\n for item in o.items:\n end_line = max(end_line, item.end_line or item.line)\n overloaded_src = self.get_src_from_lines(line, end_line)\n best_sig = _get_documented_overload(o)\n\n if not best_sig:\n src = overloaded_src\n else:\n best_sig_src = self.get_src(best_sig)\n src = f\"{overloaded_src}\\n{best_sig_src}\"\n\n self.symbols[o.name] = src\n\n def visit_assignment_stmt(self, o: mypy.nodes.AssignmentStmt) -> None:\n try:\n (lvalue,) = o.lvalues\n except ValueError as ex:\n raise ValueError(f\"Multi assignments are not supported: {o}\") from ex\n if not isinstance(lvalue, mypy.nodes.NameExpr):\n raise TypeError(f\"Multi assignments are not supported: {lvalue}\")\n # find actual rvalue src location by taking the entire statement and subtracting the lvalue\n loc = mypy.nodes.Context()\n loc.set_line(o)\n if lvalue.end_column:\n loc.column = lvalue.end_column\n self.symbols[lvalue.name] = self.get_src(loc)\n\n def visit_expression_stmt(self, o: mypy.nodes.ExpressionStmt) -> None:\n if isinstance(o.expr, mypy.nodes.StrExpr) and isinstance(\n self.last_stmt, mypy.nodes.AssignmentStmt\n ):\n (lvalue,) = self.last_stmt.lvalues\n if isinstance(lvalue, mypy.nodes.NameExpr):\n self.symbols[lvalue.name] += \"\\n\" + self.get_src(o.expr)\n\n def _is_protocol(self, fullname: str) -> bool:\n try:\n klass = self.all_classes[fullname]\n except KeyError:\n return False\n info: mypy.nodes.TypeInfo = klass[1].info\n return info.is_protocol\n\n\ndef _get_documented_overload(o: mypy.nodes.OverloadedFuncDef) -> mypy.nodes.FuncDef | None:\n best_overload: mypy.nodes.FuncDef | None = None\n for overload in o.items:\n match overload:\n case mypy.nodes.Decorator(func=func_def):\n pass\n case mypy.nodes.FuncDef() as func_def:\n pass\n case _:\n raise Exception(\"Only function overloads supported\")\n\n docstring = func_def.docstring\n\n # this is good enough until a more complex case arises\n if docstring and (\n not best_overload or len(func_def.arguments) > len(best_overload.arguments)\n ):\n best_overload = func_def\n return best_overload\n\n\n@attrs.define\nclass ImportCollector(NodeVisitor[None]):\n collected_imports: dict[str, ModuleImports]\n\n def get_imports(self, module_id: str) -> ModuleImports:\n try:\n imports = self.collected_imports[module_id]\n except KeyError:\n imports = self.collected_imports[module_id] = ModuleImports()\n return imports\n\n def visit_mypy_file(self, o: mypy.nodes.MypyFile) -> None:\n for stmt in o.defs:\n stmt.accept(self)\n\n def visit_import_from(self, o: mypy.nodes.ImportFrom) -> None:\n imports = self.get_imports(o.id)\n for name, name_as in o.names:\n imports.from_imports[name] = name_as\n\n def visit_import(self, o: mypy.nodes.Import) -> None:\n for name, name_as in o.ids:\n if name != (name_as or name):\n raise Exception(\"Aliasing symbols in stubs is not supported\")\n\n imports = self.get_imports(name)\n imports.import_module = True\n\n\n@attrs.define\nclass DocStub(NodeVisitor[None]):\n read_source: Callable[[str], list[str] | None]\n file: mypy.nodes.MypyFile\n modules: dict[str, mypy.nodes.MypyFile]\n parsed_modules: dict[str, SymbolCollector] = attrs.field(factory=dict)\n all_classes: dict[str, tuple[mypy.nodes.MypyFile, mypy.nodes.ClassDef]] = attrs.field(\n factory=dict\n )\n collected_imports: dict[str, ModuleImports] = attrs.field(factory=dict)\n inlined_protocols: dict[str, set[str]] = attrs.field(factory=dict)\n collected_symbols: dict[str, str] = attrs.field(factory=dict)\n\n @classmethod\n def process_module(cls, manager: mypy.build.BuildManager, module_id: str) -> typing.Self:\n read_source = manager.errors.read_source\n assert read_source\n modules = manager.modules\n module: mypy.nodes.MypyFile = modules[module_id]\n stub = cls(read_source=read_source, file=module, modules=modules)\n module.accept(stub)\n stub._remove_inlined_symbols() # noqa: SLF001\n return stub\n\n def _get_module(self, module_id: str) -> SymbolCollector:\n try:\n return self.parsed_modules[module_id]\n except KeyError:\n file = self.modules[module_id]\n self.parsed_modules[module_id] = collector = SymbolCollector(\n file=file,\n read_source=self.read_source,\n all_classes=self.all_classes,\n inlined_protocols=self.inlined_protocols,\n )\n file.accept(collector)\n self._collect_imports(file)\n return collector\n\n def _collect_imports(self, o: mypy.nodes.Node) -> None:\n o.accept(ImportCollector(self.collected_imports))\n self._remove_inlined_symbols()\n\n def _remove_inlined_symbols(self) -> None:\n for module, imports in self.collected_imports.items():\n inlined_protocols = self.inlined_protocols.get(module, ())\n if imports.import_module and module in self.collected_symbols:\n raise Exception(f\"Symbol\/import collision: {module}\")\n for name, name_as in list(imports.from_imports.items()):\n if name in inlined_protocols:\n print(f\"Removed inlined protocol: {name}\")\n del imports.from_imports[name]\n del self.collected_symbols[name]\n elif name in self.collected_symbols:\n if name_as is None:\n del imports.from_imports[name]\n else:\n print(f\"Symbol\/import collision: from {module} import {name} as {name_as}\")\n\n def visit_mypy_file(self, o: mypy.nodes.MypyFile) -> None:\n for stmt in o.defs:\n stmt.accept(self)\n self._add_all_symbols(o.fullname)\n\n def visit_import_from(self, o: mypy.nodes.ImportFrom) -> None:\n if not _should_inline_module(o.id):\n self._collect_imports(o)\n return\n module = self._get_module(o.id)\n name_mapping = dict(o.names)\n for name in module.symbols:\n try:\n name_as = name_mapping[name]\n except KeyError:\n continue\n if name != (name_as or name):\n raise Exception(\"Aliasing symbols in stubs is not supported\")\n self.add_symbol(module, name)\n\n def visit_import_all(self, o: mypy.nodes.ImportAll) -> None:\n if _should_inline_module(o.id):\n self._add_all_symbols(o.id)\n else:\n self._collect_imports(o)\n\n def _add_all_symbols(self, module_id: str) -> None:\n module = self._get_module(module_id)\n for sym in module.symbols:\n self.add_symbol(module, sym)\n\n def visit_import(self, o: mypy.nodes.Import) -> None:\n self._collect_imports(o)\n\n def add_symbol(self, module: SymbolCollector, name: str) -> None:\n lines = module.symbols[name]\n existing = self.collected_symbols.get(name)\n if existing is not None and existing != lines:\n raise Exception(f\"Duplicate definitions are not supported: {name}\\n{lines}\")\n self.collected_symbols[name] = lines\n\n\ndef _name_as(name: str, name_as: str | None) -> str:\n if name_as is None:\n return name\n return f\"{name} as {name_as}\"\n\n\ndef _should_inline_module(module_id: str) -> bool:\n return module_id.startswith(\"algopy._\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"algorandfoundation\/puya","path":"scripts\/generate_docs.py","language":"Python","license":"NOASSERTION","size":14331} {"code":"#!\/usr\/bin\/env python3\n\nimport subprocess\nfrom pathlib import Path\n\nSCRIPTS_DIR = Path(__file__).parent\nVCS_ROOT = SCRIPTS_DIR.parent\nLIB_NAME = \"_puya_lib\"\n\n\ndef main() -> None:\n # compile puya lib\n # normalize source_location.path\n # save\n subprocess.run([\"puyapy\", \"--output-awst-json\", f\"src\/{LIB_NAME}\"], check=True, cwd=VCS_ROOT)\n awst_path = VCS_ROOT \/ \"module.awst.json\"\n puya_lib_path = VCS_ROOT \/ \"src\" \/ LIB_NAME\n output_path = VCS_ROOT \/ \"src\" \/ \"puya\" \/ \"ir\" \/ \"_puya_lib.awst.json\"\n replace_awst = awst_path.read_text()\n for lib_path in puya_lib_path.glob(\"*.py\"):\n path_as_str = str(lib_path).replace(\"\\\\\", \"\\\\\\\\\")\n find_str = f'\"file\": \"{path_as_str}\",'\n replace_str = '\"file\": null,'\n replace_awst = replace_awst.replace(find_str, replace_str)\n output_path.write_text(replace_awst)\n awst_path.unlink(missing_ok=True)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"algorandfoundation\/puya","path":"scripts\/generate_puya_lib.py","language":"Python","license":"NOASSERTION","size":935} {"code":"#!\/usr\/bin\/env python3\nimport builtins\nimport copy\nimport json\nimport keyword\nimport subprocess\nimport textwrap\nimport typing\nfrom collections.abc import Iterable, Iterator, Sequence\nfrom pathlib import Path\n\nimport attrs\n\nfrom puya import log\nfrom puya.algo_constants import SUPPORTED_AVM_VERSIONS\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.intrinsic_models import FunctionOpMapping, OpMappingWithOverloads\nfrom puyapy.awst_build.utils import snake_case\nfrom scripts.transform_lang_spec import (\n ArgEnum,\n Immediate,\n ImmediateKind,\n LanguageSpec,\n Op,\n StackType,\n StackValue,\n)\n\nlogger = log.get_logger(__name__)\nINDENT = \" \" * 4\nVCS_ROOT = Path(__file__).parent.parent\nMIN_SUPPORTED_VERSION = min(SUPPORTED_AVM_VERSIONS)\n\nPYTHON_ENUM_CLASS = {\n \"Mimc Configurations\": \"MiMCConfigurations\",\n}\nPYTYPE_TO_LITERAL: dict[pytypes.PyType, pytypes.LiteralOnlyType | None] = {\n pytypes.BytesType: pytypes.BytesLiteralType,\n pytypes.UInt64Type: pytypes.IntLiteralType,\n pytypes.AccountType: None, # pytypes.StrLiteralType, # TODO: should we enable this?\n pytypes.BigUIntType: pytypes.IntLiteralType,\n pytypes.BoolType: None, # already a Python type\n pytypes.ApplicationType: pytypes.IntLiteralType,\n pytypes.AssetType: pytypes.IntLiteralType,\n pytypes.TransactionTypeType: None,\n pytypes.OnCompleteActionType: None,\n}\nPYTYPE_REPR = {\n value: f\"pytypes.{key}\"\n for key, value in pytypes.__dict__.items()\n if isinstance(value, pytypes.PyType)\n}\nSTACK_TYPE_MAPPING: dict[StackType, Sequence[pytypes.PyType]] = {\n StackType.address_or_index: [pytypes.AccountType, pytypes.UInt64Type],\n StackType.application: [pytypes.ApplicationType, pytypes.UInt64Type],\n StackType.asset: [pytypes.AssetType, pytypes.UInt64Type],\n StackType.bytes: [pytypes.BytesType],\n StackType.bytes_8: [pytypes.BytesType],\n StackType.bytes_32: [pytypes.BytesType],\n StackType.bytes_33: [pytypes.BytesType],\n StackType.bytes_64: [pytypes.BytesType],\n StackType.bytes_80: [pytypes.BytesType],\n StackType.bytes_1232: [pytypes.BytesType],\n StackType.bytes_1793: [pytypes.BytesType],\n StackType.bool: [pytypes.BoolType, pytypes.UInt64Type],\n StackType.uint64: [pytypes.UInt64Type],\n StackType.any: [pytypes.BytesType, pytypes.UInt64Type],\n StackType.box_name: [pytypes.BytesType], # TODO: should this be another type..?\n StackType.address: [pytypes.AccountType],\n StackType.bigint: [pytypes.BigUIntType],\n StackType.state_key: [pytypes.BytesType], # TODO: should this be another type..?\n}\n\nBYTES_LITERAL = \"bytes\"\nUINT64_LITERAL = \"int\"\nSTUB_NAMESPACE = \"op\"\nALGORAND_OP_URL = \"https:\/\/developer.algorand.org\/docs\/get-details\/dapps\/avm\/teal\/opcodes\/v10\/\"\n\n\nclass OpCodeGroup(typing.Protocol):\n def handled_ops(self) -> Iterator[str]: ...\n\n\n@attrs.define(kw_only=True)\nclass RenamedOpCode(OpCodeGroup):\n name: str\n stack_aliases: dict[str, list[str]] = attrs.field(factory=dict)\n \"\"\"ops that are aliases for other ops that take stack values instead of immediates\"\"\"\n op: str\n\n def handled_ops(self) -> Iterator[str]:\n yield self.op\n yield from self.stack_aliases.keys()\n\n\n@attrs.define(kw_only=True)\nclass MergedOpCodes(OpCodeGroup):\n name: str\n doc: str\n ops: dict[str, dict[str, list[str]]]\n\n def handled_ops(self) -> Iterator[str]:\n for op, aliases in self.ops.items():\n yield op\n yield from aliases.keys()\n\n\n@attrs.define(kw_only=True)\nclass GroupedOpCodes(OpCodeGroup):\n name: str\n \"\"\"ops that are aliases for other ops that take stack values instead of immediates\"\"\"\n doc: str\n ops: dict[str, str] = attrs.field(factory=dict)\n \"\"\"ops to include in group, mapped to their new name\"\"\"\n\n def handled_ops(self) -> Iterator[str]:\n yield from self.ops.keys()\n\n\nGROUPED_OP_CODES = [\n GroupedOpCodes(\n name=\"AppGlobal\",\n doc=\"Get or modify Global app state\",\n ops={\n \"app_global_get\": \"get\",\n \"app_global_get_ex\": \"get_ex\",\n \"app_global_del\": \"delete\",\n \"app_global_put\": \"put\",\n },\n ),\n GroupedOpCodes(\n name=\"Scratch\",\n doc=\"Load or store scratch values\",\n ops={\"loads\": \"load\", \"stores\": \"store\"},\n ),\n GroupedOpCodes(\n name=\"AppLocal\",\n doc=\"Get or modify Local app state\",\n ops={\n \"app_local_get\": \"get\",\n \"app_local_get_ex\": \"get_ex\",\n \"app_local_del\": \"delete\",\n \"app_local_put\": \"put\",\n },\n ),\n GroupedOpCodes(\n name=\"Box\",\n doc=\"Get or modify box state\",\n ops={\n \"box_create\": \"create\",\n \"box_del\": \"delete\",\n \"box_extract\": \"extract\",\n \"box_get\": \"get\",\n \"box_len\": \"length\",\n \"box_put\": \"put\",\n \"box_replace\": \"replace\",\n \"box_resize\": \"resize\",\n \"box_splice\": \"splice\",\n },\n ),\n GroupedOpCodes(\n name=\"EllipticCurve\",\n doc=\"Elliptic Curve functions\",\n ops={\n \"ec_add\": \"add\",\n \"ec_map_to\": \"map_to\",\n \"ec_multi_scalar_mul\": \"scalar_mul_multi\",\n \"ec_pairing_check\": \"pairing_check\",\n \"ec_scalar_mul\": \"scalar_mul\",\n \"ec_subgroup_check\": \"subgroup_check\",\n },\n ),\n GroupedOpCodes(\n name=\"ITxnCreate\",\n doc=\"Create inner transactions\",\n ops={\n \"itxn_begin\": \"begin\",\n \"itxn_next\": \"next\",\n \"itxn_submit\": \"submit\",\n \"itxn_field\": \"set\",\n },\n ),\n]\nMERGED_OP_CODES = [\n MergedOpCodes(\n name=\"Txn\",\n doc=\"Get values for the current executing transaction\",\n ops={\n \"txn\": {},\n \"txnas\": {\n \"txna\": [\"F\", \"I\"],\n },\n },\n ),\n MergedOpCodes(\n name=\"GTxn\",\n doc=\"Get values for transactions in the current group\",\n ops={\n \"gtxns\": {\n \"gtxn\": [\"F\", \"T\"],\n },\n # field is immediate, first stack arg is txn index, second stack arg is array index\n \"gtxnsas\": {\n \"gtxnsa\": [\"F\", \"A\", \"I\"], # group index on stack\n \"gtxna\": [\"F\", \"T\", \"I\"], # no stack args\n \"gtxnas\": [\"F\", \"T\", \"A\"], # array index on stack\n },\n },\n ),\n MergedOpCodes(\n name=\"ITxn\",\n doc=\"Get values for the last inner transaction\",\n ops={\n \"itxn\": {},\n \"itxnas\": {\n \"itxna\": [\"F\", \"I\"],\n },\n },\n ),\n MergedOpCodes(\n name=\"GITxn\",\n doc=\"Get values for inner transaction in the last group submitted\",\n ops={\n \"gitxn\": {},\n \"gitxnas\": {\n \"gitxna\": [\"T\", \"F\", \"I\"],\n },\n },\n ),\n MergedOpCodes(\n name=\"Global\",\n doc=\"Get Global values\",\n ops={\"global\": {}},\n ),\n]\nRENAMED_OP_CODES = [\n RenamedOpCode(\n name=\"arg\",\n op=\"args\",\n stack_aliases={\"arg\": [\"N\"]},\n ),\n RenamedOpCode(\n name=\"extract\",\n op=\"extract3\",\n stack_aliases={\n \"extract\": [\"A\", \"S\", \"L\"],\n },\n ),\n RenamedOpCode(\n name=\"replace\",\n op=\"replace3\",\n stack_aliases={\n \"replace2\": [\"A\", \"S\", \"B\"],\n },\n ),\n RenamedOpCode(\n name=\"substring\",\n op=\"substring3\",\n stack_aliases={\n \"substring\": [\"A\", \"S\", \"E\"],\n },\n ),\n RenamedOpCode(\n name=\"gload\",\n op=\"gloadss\",\n stack_aliases={\n \"gload\": [\"T\", \"I\"],\n \"gloads\": [\"A\", \"I\"],\n },\n ),\n RenamedOpCode(\n name=\"gaid\",\n op=\"gaids\",\n stack_aliases={\"gaid\": [\"T\"]},\n ),\n RenamedOpCode(\n name=\"exit\",\n op=\"return\",\n ),\n]\n\nEXCLUDED_OPCODES = {\n # low level flow control\n \"bnz\",\n \"bz\",\n \"b\",\n \"callsub\",\n \"retsub\",\n \"proto\",\n \"switch\",\n \"match\",\n # low level stack manipulation\n \"intc\",\n *[f\"intc_{i}\" for i in range(4)],\n \"bytec\",\n *[f\"bytec_{i}\" for i in range(4)],\n \"pushbytes\",\n \"pushbytess\",\n \"pushint\",\n \"pushints\",\n \"frame_dig\",\n \"frame_bury\",\n \"bury\",\n \"cover\",\n \"dig\",\n \"dup\",\n \"dup2\",\n \"dupn\",\n \"pop\",\n \"popn\",\n \"swap\",\n \"uncover\",\n # program scratch slot read\/modification (for current program)\n \"load\",\n \"loads\",\n \"store\",\n \"stores\",\n # maninuplates what other low level ops point to\n \"intcblock\",\n \"bytecblock\",\n # implicit immediates, covered by optimiser and\/or assembler\n \"arg_0\",\n \"arg_1\",\n \"arg_2\",\n \"arg_3\",\n # have a higher level abstraction that supersedes it\n \"log\",\n}\n\n\n# which ops to treat as properties in the generated stubs\nPROPERTY_OPS = {\n \"global\": {\"exclude\": [\"opcode_budget\"]},\n \"txn\": {\"exclude\": list[str]()},\n}\n\n\n@attrs.define\nclass TypedName:\n name: str\n type: StackType | ImmediateKind | str\n doc: str | None\n\n\n@attrs.define(kw_only=True)\nclass FunctionDef:\n name: str\n doc: list[str]\n is_property: bool\n args: list[TypedName] = attrs.field(factory=list)\n return_docs: list[str] = attrs.field(factory=list)\n op_mapping: OpMappingWithOverloads\n min_avm_version: int\n\n\n@attrs.define\nclass ClassDef:\n name: str\n doc: str\n methods: list[FunctionDef] = attrs.field()\n ops: list[str]\n\n\ndef main() -> None:\n spec_path = VCS_ROOT \/ \"langspec.puya.json\"\n\n lang_spec_json = json.loads(spec_path.read_text(encoding=\"utf-8\"))\n lang_spec = LanguageSpec.from_json(lang_spec_json)\n\n non_simple_ops = {\n *EXCLUDED_OPCODES,\n *dir(builtins),\n *keyword.kwlist, # TODO: maybe consider softkwlist too?\n }\n function_defs = list[FunctionDef]()\n class_defs = list[ClassDef]()\n enums_to_build = dict[str, bool]()\n\n for merged in MERGED_OP_CODES:\n non_simple_ops.update(merged.handled_ops())\n class_defs.append(build_merged_ops(lang_spec, merged))\n for grouped in GROUPED_OP_CODES:\n non_simple_ops.update(grouped.handled_ops())\n class_defs.append(build_grouped_ops(lang_spec, grouped, enums_to_build))\n for aliased in RENAMED_OP_CODES:\n function_defs.extend(build_aliased_ops(lang_spec, aliased))\n non_simple_ops.update(aliased.handled_ops())\n\n for op in lang_spec.ops.values():\n if op.name in non_simple_ops or not op.name.isidentifier():\n logger.info(f\"Ignoring: {op.name}\")\n continue\n overriding_immediate = get_overriding_immediate(op)\n if overriding_immediate:\n class_defs.append(\n build_class_from_overriding_immediate(\n lang_spec,\n op,\n class_name=get_python_enum_class(op.name),\n class_doc=\" \".join(op.doc),\n immediate=overriding_immediate,\n aliases=[],\n )\n )\n else:\n for immediate in op.immediate_args:\n if immediate.immediate_type == ImmediateKind.arg_enum and (\n immediate.modifies_stack_input is None\n and immediate.modifies_stack_output is None\n ):\n assert immediate.arg_enum is not None\n enums_to_build[immediate.arg_enum] = True\n function_defs.extend(build_operation_methods(op, op.name, []))\n\n function_defs.sort(key=lambda x: x.name)\n class_defs.sort(key=lambda x: x.name)\n\n enum_names = list(enums_to_build.keys())\n output_stub(lang_spec, enum_names, function_defs, class_defs)\n output_awst_data(lang_spec, enum_names, function_defs, class_defs)\n\n\ndef sub_types(type_name: StackType, *, covariant: bool) -> Sequence[pytypes.PyType]:\n try:\n typs = STACK_TYPE_MAPPING[type_name]\n except KeyError as ex:\n raise NotImplementedError(\n f\"Could not map stack type {type_name} to an algopy type\"\n ) from ex\n else:\n last_index = None if covariant else 1\n return typs[:last_index]\n\n\ndef immediate_kind_to_type(kind: ImmediateKind) -> type[int | str]:\n match kind:\n case ImmediateKind.uint8 | ImmediateKind.int8 | ImmediateKind.varuint:\n return int\n case ImmediateKind.arg_enum:\n return str\n case _:\n raise ValueError(f\"Unexpected ImmediateKind: {kind}\")\n\n\ndef get_python_type(\n typ: StackType | ImmediateKind | str, *, covariant: bool, any_as: str | None\n) -> str:\n match typ:\n case StackType() as stack_type:\n if any_as and stack_type == StackType.any:\n return any_as\n ptypes_ = sub_types(stack_type, covariant=covariant)\n names = [str(wt).removeprefix(\"algopy.\") for wt in ptypes_]\n if covariant:\n for pt in ptypes_:\n lit_t = PYTYPE_TO_LITERAL[pt]\n if lit_t is not None:\n lit_name = str(lit_t)\n if lit_name not in names:\n names.append(lit_name)\n return \" | \".join(names)\n case ImmediateKind() as immediate_kind:\n return immediate_kind_to_type(immediate_kind).__name__\n case _:\n return typ\n\n\ndef build_method_stub(function: FunctionDef, prefix: str = \"\") -> Iterable[str]:\n signature = list[str]()\n doc = function.doc[:]\n signature.append(f\"def {function.name}(\")\n args = list[str]()\n for arg in function.args:\n python_type = get_python_type(arg.type, covariant=True, any_as=None)\n args.append(f\"{arg.name}: {python_type}\")\n if arg.doc:\n doc.append(f\":param {python_type} {arg.name}: {arg.doc}\")\n if function.args:\n args.append(\"\/\") # TODO: remove once we support kwargs\n signature.append(\", \".join(args))\n\n return_docs = function.return_docs\n returns = pytype_stub_repr(function.op_mapping.result)\n if return_docs:\n if doc:\n doc.append(f\":returns {returns}: {return_docs[0]}\")\n doc.extend(return_docs[1:])\n else:\n doc = return_docs\n signature.append(f\") -> {returns}:\")\n teal_ops = sorted({op.op_code for op in function.op_mapping.overloads})\n teal_op_desc = \", \".join(_get_algorand_doc(teal_op) for teal_op in teal_ops)\n doc.append(\"\")\n doc.append(f\"Native TEAL opcode: {teal_op_desc}\")\n body = list[str]()\n if doc:\n body.append('\"\"\"')\n body.extend(doc)\n body.append('\"\"\"')\n else:\n body.append(\"...\")\n\n yield prefix + \"\".join(signature)\n yield from [textwrap.indent(line, prefix=prefix + INDENT) for line in body]\n\n\ndef build_stub_class(klass: ClassDef) -> Iterable[str]:\n ops = [f\"{_get_algorand_doc(op)}\" for op in klass.ops]\n docstring = \"\\n\".join(\n [\n INDENT + '\"\"\"',\n INDENT + klass.doc,\n INDENT + f\"Native TEAL op{'s' if len(ops) > 1 else ''}: {', '.join(ops)}\",\n INDENT + '\"\"\"',\n ]\n )\n method_preamble = f\"{INDENT}@staticmethod\"\n yield f\"class {klass.name}:\"\n yield docstring\n for method in klass.methods:\n if method.is_property:\n yield from build_class_var_stub(method, INDENT)\n else:\n yield method_preamble\n yield from build_method_stub(method, prefix=INDENT)\n yield \"\"\n\n\ndef build_class_var_stub(function: FunctionDef, indent: str) -> Iterable[str]:\n returns = pytype_stub_repr(function.op_mapping.result)\n return_docs = function.return_docs\n doc = return_docs if return_docs else function.doc[:]\n _maybe_add_min_version_doc(doc, function.min_avm_version)\n yield f\"{indent}{function.name}: typing.Final[{returns}] = ...\"\n yield f'{indent}\"\"\"'\n for doc_line in doc:\n yield f\"{indent}{doc_line}\"\n yield f'{indent}\"\"\"'\n\n\ndef _get_modified_stack_value(alias: Op) -> StackValue:\n immediate = get_overriding_immediate(alias)\n assert immediate\n if immediate.modifies_stack_input is not None:\n return alias.stack_inputs[immediate.modifies_stack_input]\n else:\n assert immediate.modifies_stack_output is not None\n return alias.stack_outputs[immediate.modifies_stack_output]\n\n\nAliasT: typing.TypeAlias = tuple[Op, list[str]]\n\n\ndef build_class_from_overriding_immediate(\n spec: LanguageSpec,\n op: Op,\n class_name: str,\n class_doc: str,\n immediate: Immediate,\n aliases: list[AliasT],\n) -> ClassDef:\n assert immediate.arg_enum\n logger.info(f\"Using overriding immediate for {op.name}\")\n\n arg_enum_values = spec.arg_enums[immediate.arg_enum]\n\n # copy inputs so they can be mutated safely\n op = copy.deepcopy(op)\n aliases = copy.deepcopy(aliases)\n\n # obtain a list of stack values that will be modified for each enum\n stacks_to_modify = [_get_modified_stack_value(o) for o, _ in [(op, None), *aliases]]\n\n # build a method for each arg enum value\n methods = list[FunctionDef]()\n class_ops = {op.name}\n for value in arg_enum_values:\n stack_type = value.stack_type\n assert stack_type\n\n for stack_to_modify in stacks_to_modify:\n stack_to_modify.stack_type = stack_type\n stack_to_modify.doc = value.doc\n\n method = build_operation_method(\n op, snake_case(value.name), aliases, const_immediate_value=(immediate, value)\n )\n # some enums are reused across ops, so need to take the max minimum of op and enum version\n method.min_avm_version = max(op.min_avm_version, value.min_avm_version)\n _maybe_add_min_version_doc(method.doc, method.min_avm_version)\n\n for op_mapping in method.op_mapping.overloads:\n class_ops.add(op_mapping.op_code)\n\n methods.append(method)\n\n return ClassDef(name=class_name, doc=class_doc, methods=methods, ops=sorted(class_ops))\n\n\ndef get_op_doc(op: Op) -> list[str]:\n doc = [d.replace(\"\\\\\", \"\\\\\\\\\") for d in op.doc]\n _maybe_add_min_version_doc(doc, op.min_avm_version)\n return doc\n\n\ndef get_python_enum_class(arg_enum: str) -> str:\n try:\n return PYTHON_ENUM_CLASS[arg_enum]\n except KeyError:\n pass\n # don't change acronyms\n if arg_enum.isupper():\n return arg_enum\n return snake_case(arg_enum).replace(\"_\", \" \").title().replace(\" \", \"\")\n\n\ndef get_overriding_immediate(op: Op) -> Immediate | None:\n return next(\n (\n immediate\n for immediate in op.immediate_args\n if immediate.modifies_stack_input is not None\n or immediate.modifies_stack_output is not None\n ),\n None,\n )\n\n\ndef build_enum(spec: LanguageSpec, arg_enum: str) -> Iterable[str]:\n values = spec.arg_enums[arg_enum]\n enum_name = get_python_enum_class(arg_enum)\n yield f\"class {enum_name}(str):\"\n yield f'{INDENT}\"\"\"Available values for the `{arg_enum}` enum\"\"\"'\n for value in values:\n yield f\"{INDENT}{value.name}: {enum_name} = ...\"\n enum_doc = []\n if value.doc:\n enum_doc.append(value.doc)\n _maybe_add_min_version_doc(enum_doc, value.min_avm_version)\n if enum_doc:\n yield f'{INDENT}\"\"\"'\n for doc_line in enum_doc:\n yield f\"{INDENT}{doc_line}\"\n yield f'{INDENT}\"\"\"'\n yield \"\"\n\n\ndef _maybe_add_min_version_doc(doc: list[str], version: int) -> None:\n # only output min AVM version if it is greater than our min supported version\n if version > MIN_SUPPORTED_VERSION:\n doc.append(f\"Min AVM version: {version}\")\n\n\ndef build_operation_method(\n op: Op,\n op_function_name: str,\n aliases: list[AliasT],\n const_immediate_value: tuple[Immediate, ArgEnum] | None = None,\n) -> FunctionDef:\n args = []\n # python stub args can be different to mapping args, due to immediate args\n # that are inferred based on the method\/property used\n function_args = []\n doc = get_op_doc(op)\n for immediate in op.immediate_args:\n arg_type: ImmediateKind | str\n if immediate.immediate_type == ImmediateKind.arg_enum:\n assert immediate.arg_enum, \"Arg enum expected\"\n arg_type = get_python_enum_class(immediate.arg_enum)\n else:\n arg_type = immediate.immediate_type\n im_arg = TypedName(name=immediate.name.lower(), type=arg_type, doc=immediate.doc)\n args.append(im_arg)\n if const_immediate_value and const_immediate_value[0] == immediate:\n # omit immediate arg from signature\n doc = []\n else:\n function_args.append(im_arg)\n for si in op.stack_inputs:\n stack_arg = TypedName(name=si.name.lower(), type=si.stack_type, doc=si.doc)\n args.append(stack_arg)\n function_args.append(stack_arg)\n\n if op.halts:\n return_docs = [\"Halts program\"]\n else:\n return_docs = [so.doc for so in op.stack_outputs if so.doc]\n\n try:\n property_op = PROPERTY_OPS[op.name]\n except KeyError:\n is_property = False\n else:\n is_property = op_function_name not in property_op[\"exclude\"]\n\n if op.halts:\n result_typ = pytypes.NeverType\n else:\n # replace immediate reference to arg enum with a constant enum value\n result_ptypes = [sub_types(o.stack_type, covariant=False)[0] for o in op.stack_outputs]\n if not result_ptypes:\n result_typ = pytypes.NoneType\n elif len(op.stack_outputs) == 1:\n (result_typ,) = result_ptypes\n else:\n result_typ = pytypes.GenericTupleType.parameterise(result_ptypes, source_location=None)\n if result_typ == pytypes.UInt64Type:\n if op_function_name == \"on_completion\":\n result_typ = pytypes.OnCompleteActionType\n elif op_function_name == \"type_enum\":\n result_typ = pytypes.TransactionTypeType\n op_mappings = []\n ops_with_aliases = [(op, list[str]()), *aliases]\n for map_op, alias_args in ops_with_aliases:\n assert map_op.stack_outputs == op.stack_outputs\n if alias_args:\n # map the stack or immediate input name to the function signature position\n name_to_sig_idx = {n: idx2 for idx2, n in enumerate(alias_args)}\n else:\n name_to_sig_idx = {tn.name.upper(): idx2 for idx2, tn in enumerate(args)}\n map_immediates = list[str | int | type[str | int]]()\n map_args_map = dict[int, Sequence[pytypes.PyType] | int]()\n for idx, i_arg in enumerate(map_op.immediate_args):\n if const_immediate_value and const_immediate_value[0] == i_arg:\n map_immediates.append(const_immediate_value[1].name)\n else:\n im_typ = immediate_kind_to_type(i_arg.immediate_type)\n map_immediates.append(im_typ)\n sig_idx = name_to_sig_idx[i_arg.name]\n map_args_map[sig_idx] = idx\n\n for s_arg in map_op.stack_inputs:\n allowed_types = tuple(sub_types(s_arg.stack_type, covariant=True))\n sig_idx = name_to_sig_idx[s_arg.name]\n map_args_map[sig_idx] = allowed_types\n\n op_mappings.append(\n FunctionOpMapping(\n op_code=map_op.name,\n immediates=map_immediates,\n args=[map_args_map[k] for k in sorted(map_args_map)],\n )\n )\n proto_function = FunctionDef(\n name=op_function_name,\n doc=doc,\n is_property=is_property,\n args=function_args,\n return_docs=return_docs,\n op_mapping=OpMappingWithOverloads(\n arity=len(function_args),\n result=result_typ,\n overloads=op_mappings,\n ),\n min_avm_version=op.min_avm_version,\n )\n\n return proto_function\n\n\ndef build_operation_methods(\n op: Op, op_function_name: str, aliases: list[AliasT]\n) -> Iterable[FunctionDef]:\n logger.info(f\"Mapping {op.name} to {op_function_name}\")\n\n if StackType.any in (s.stack_type for s in op.stack_outputs):\n logger.info(f\"Found any output for {op.name}\")\n for replace_any_with in (StackType.bytes, StackType.uint64):\n new_op = op_any_replaced(op, replace_any_with)\n new_name = f\"{op_function_name}_{replace_any_with.name}\"\n new_aliases = [\n (op_any_replaced(alias_op, replace_any_with), names) for alias_op, names in aliases\n ]\n yield build_operation_method(new_op, new_name, new_aliases)\n else:\n yield build_operation_method(op, op_function_name, aliases)\n\n\ndef op_any_replaced(op: Op, replace_any_with: StackType) -> Op:\n stack_inputs = []\n input_replaced = 0\n for si in op.stack_inputs:\n if si.stack_type != StackType.any:\n stack_inputs.append(si)\n else:\n input_replaced += 1\n stack_inputs.append(attrs.evolve(si, stack_type=replace_any_with))\n\n stack_outputs = []\n outputs_replaced = 0\n for so in op.stack_outputs:\n if so.stack_type != StackType.any:\n stack_outputs.append(so)\n else:\n outputs_replaced += 1\n stack_outputs.append(attrs.evolve(so, stack_type=replace_any_with))\n assert outputs_replaced == 1\n return attrs.evolve(op, stack_inputs=stack_inputs, stack_outputs=stack_outputs)\n\n\ndef build_aliased_ops(spec: LanguageSpec, group: RenamedOpCode) -> Iterable[FunctionDef]:\n op = spec.ops[group.op]\n aliases = [\n (spec.ops[stack_alias], arg_map) for stack_alias, arg_map in group.stack_aliases.items()\n ]\n methods = build_operation_methods(op, group.name, aliases)\n return methods\n\n\ndef build_merged_ops(spec: LanguageSpec, group: MergedOpCodes) -> ClassDef:\n merge_methods = dict[str, FunctionDef]()\n\n for other_op_name, alias_dict in group.ops.items():\n aliases = [(spec.ops[alias_op], arg_map) for alias_op, arg_map in alias_dict.items()]\n other_op = spec.ops[other_op_name]\n overriding_immediate = get_overriding_immediate(other_op)\n assert overriding_immediate\n other_class = build_class_from_overriding_immediate(\n spec,\n other_op,\n class_name=group.name,\n class_doc=group.doc,\n immediate=overriding_immediate,\n aliases=aliases,\n )\n for method in other_class.methods:\n merge_methods[method.name] = method\n\n methods = list(merge_methods.values())\n return ClassDef(name=group.name, doc=group.doc, methods=methods, ops=sorted(group.ops))\n\n\ndef build_grouped_ops(\n spec: LanguageSpec, group: GroupedOpCodes, enums_to_build: dict[str, bool]\n) -> ClassDef:\n methods = list[FunctionDef]()\n for rename_op_name, python_name in group.ops.items():\n rename_op = spec.ops[rename_op_name]\n rename_immediate = get_overriding_immediate(rename_op)\n if rename_immediate:\n rename_class = build_class_from_overriding_immediate(\n spec,\n rename_op,\n class_name=group.name,\n class_doc=group.doc,\n immediate=rename_immediate,\n aliases=[],\n )\n # when grouping an op with immediate overrides, treat python_name as a prefix\n for method in rename_class.methods:\n method.name = f\"{python_name}_{method.name}\"\n methods.extend(rename_class.methods)\n\n else:\n methods.extend(build_operation_methods(rename_op, python_name, aliases=[]))\n for arg in rename_op.immediate_args:\n if arg.immediate_type == ImmediateKind.arg_enum and (\n arg.modifies_stack_input is None and arg.modifies_stack_output is None\n ):\n assert arg.arg_enum is not None\n enums_to_build[arg.arg_enum] = True\n\n class_def = ClassDef(\n name=group.name,\n doc=group.doc,\n methods=methods,\n ops=sorted(group.ops),\n )\n return class_def\n\n\ndef pytype_repr(typ: pytypes.PyType) -> str:\n try:\n return PYTYPE_REPR[typ]\n except KeyError:\n pass\n match typ:\n case pytypes.TupleType(items=tuple_items) if len(tuple_items) > 1:\n item_strs = [pytype_repr(item) for item in tuple_items]\n return (\n f\"pytypes.GenericTupleType.parameterise(\"\n f\"({', '.join(item_strs)}), source_location=None)\"\n )\n raise ValueError(f\"Unexpected pytype: {typ}\")\n\n\ndef build_op_specification_body(function: FunctionDef) -> Iterable[str]:\n if function.is_property:\n (op_mapping,) = function.op_mapping.overloads\n (immediate,) = op_mapping.immediates\n yield (\n f\"{function.name}=PropertyOpMapping(\"\n f\"{op_mapping.op_code!r}, {immediate!r}, {pytype_repr(function.op_mapping.result)},\"\n f\"),\"\n )\n else:\n yield f\"{function.name}=OpMappingWithOverloads(\"\n if function.op_mapping.result is not pytypes.NoneType:\n yield f\" result={pytype_repr(function.op_mapping.result)},\"\n yield f\" arity={function.op_mapping.arity}, \"\n yield \" overloads=[\"\n for op_mapping in function.op_mapping.overloads:\n yield f\"FunctionOpMapping({op_mapping.op_code!r},\"\n if op_mapping.immediates:\n yield \" immediates=[\"\n for idx, item in enumerate(op_mapping.immediates):\n if idx:\n yield \", \"\n if not isinstance(item, type):\n yield repr(item)\n else:\n yield item.__name__\n yield \"],\"\n if op_mapping.args:\n yield \" args=[\"\n for idx, allowed_types_or_idx in enumerate(op_mapping.args):\n if idx:\n yield \", \"\n if isinstance(allowed_types_or_idx, int):\n yield repr(allowed_types_or_idx)\n else: # noqa: PLR5501\n if len(allowed_types_or_idx) == 1:\n yield f\"({pytype_repr(*allowed_types_or_idx)},)\"\n else:\n yield \"(\"\n for idx2, allowed_type in enumerate(allowed_types_or_idx):\n if idx2:\n yield \",\"\n yield pytype_repr(allowed_type)\n yield \")\"\n yield \"],\"\n\n yield \"),\"\n yield \"]\"\n yield \"),\"\n\n\ndef build_awst_data(\n lang_spec: LanguageSpec,\n enums: list[str],\n function_ops: list[FunctionDef],\n class_ops: list[ClassDef],\n) -> Iterable[str]:\n yield \"import typing\"\n yield \"from collections.abc import Mapping, Sequence\"\n yield \"from puyapy.awst_build import pytypes\"\n yield (\n \"from puyapy.awst_build.intrinsic_models\"\n \" import FunctionOpMapping, OpMappingWithOverloads, PropertyOpMapping\"\n )\n yield \"ENUM_CLASSES: typing.Final[Mapping[str, Mapping[str, str]]] = dict(\"\n for enum_name in enums:\n yield f\"{get_python_enum_class(enum_name)}=dict(\"\n for enum_value in lang_spec.arg_enums[enum_name]:\n # enum names currently match enum immediate values\n yield f'{enum_value.name}=\"{enum_value.name}\",'\n yield \"),\"\n yield \")\"\n yield \"\"\n yield \"FUNC_TO_AST_MAPPER: typing.Final[Mapping[str, OpMappingWithOverloads]] = dict(\"\n for function_op in function_ops:\n yield \"\".join(build_op_specification_body(function_op))\n yield \")\"\n\n yield (\n \"NAMESPACE_CLASSES: \"\n \"typing.Final[Mapping[str, Mapping[str, PropertyOpMapping | OpMappingWithOverloads]]]\"\n \" = dict(\"\n )\n for class_op in class_ops:\n yield f\"{class_op.name}=dict(\"\n for method in class_op.methods:\n yield \"\".join(build_op_specification_body(method))\n yield \"),\"\n yield \")\"\n\n\ndef output_stub(\n lang_spec: LanguageSpec,\n enums: list[str],\n function_ops: list[FunctionDef],\n class_ops: list[ClassDef],\n) -> None:\n references = \", \".join(\n sorted(\n str(pt).removeprefix(\"algopy.\")\n for pt, lit_t in PYTYPE_TO_LITERAL.items()\n if str(pt).startswith(\"algopy.\")\n )\n )\n stub: list[str] = [\n \"import typing\",\n \"\",\n f\"from algopy import {references}\",\n ]\n\n for arg_enum in enums:\n stub.extend(build_enum(lang_spec, arg_enum))\n\n for function in function_ops:\n stub.extend(build_method_stub(function))\n\n for class_op in class_ops:\n stub.extend(build_stub_class(class_op))\n\n stub_out_path = VCS_ROOT \/ \"stubs\" \/ \"algopy-stubs\" \/ f\"{STUB_NAMESPACE}.pyi\"\n stub_out_path.write_text(\"\\n\".join(stub), encoding=\"utf-8\")\n subprocess.run([\"ruff\", \"format\", str(stub_out_path)], check=True, cwd=VCS_ROOT)\n\n\ndef pytype_stub_repr(pytype: pytypes.PyType) -> str:\n return str(pytype).replace(\"algopy.\", \"\")\n\n\ndef output_awst_data(\n lang_spec: LanguageSpec,\n enums: list[str],\n function_ops: list[FunctionDef],\n class_ops: list[ClassDef],\n) -> None:\n awst_data = build_awst_data(lang_spec, enums, function_ops, class_ops)\n\n awst_data_path = VCS_ROOT \/ \"src\" \/ \"puyapy\" \/ \"awst_build\" \/ \"intrinsic_data.py\"\n awst_data_path.write_text(\"\\n\".join(awst_data), encoding=\"utf-8\")\n subprocess.run([\"ruff\", \"format\", str(awst_data_path)], check=True, cwd=VCS_ROOT)\n subprocess.run([\"ruff\", \"check\", \"--fix\", str(awst_data_path)], check=False, cwd=VCS_ROOT)\n\n\ndef _get_algorand_doc(op: str) -> str:\n return f\"[`{op}`]({ALGORAND_OP_URL}#{op})\"\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"algorandfoundation\/puya","path":"scripts\/generate_stubs.py","language":"Python","license":"NOASSERTION","size":33877} {"code":"#!\/usr\/bin\/env python3\nimport contextlib\nimport enum\nimport json\nimport logging\nimport typing\nfrom pathlib import Path\n\nimport attrs\nimport cattrs\n\nlogger = logging.getLogger(__name__)\n\n\nSTACK_INPUT_NAMES = \"ABCDE\"\nSTACK_OUTPUT_NAMES_FEW = \"XYZ\" # 3 or less var\nSTACK_OUTPUT_NAMES_MANY = \"WXYZ\" # 4 var\n\n\nVARIABLE_SIZE_OPCODES = {\n \"intcblock\",\n \"bytecblock\",\n \"pushbytes\",\n \"pushbytess\",\n \"pushint\",\n \"pushints\",\n \"switch\",\n \"match\",\n}\n\n\nclass NamedType(typing.TypedDict):\n \"\"\"\n {\n \"Name\": \"uint64\",\n \"Abbreviation\": \"i\",\n \"Bound\": [\n 0,\n 18446744073709551615\n ],\n \"AVMType\": \"uint64\"\n },\n \"\"\"\n\n Name: str\n Abbreviation: str\n AVMType: str\n\n\nclass ImmediateNote(typing.TypedDict, total=False):\n \"\"\"\n {\n \"Comment\": \"transaction field index\",\n \"Encoding\": \"uint8\",\n \"Name\": \"F\",\n \"Reference\": \"txn\"\n }\n \"\"\"\n\n Comment: str\n Encoding: str\n Name: str\n Reference: str\n\n\nclass Operation(typing.TypedDict, total=False):\n \"\"\"\n {\n \"Opcode\": 0,\n \"Name\": \"err\",\n \"Size\": 1,\n \"Doc\": \"Fail immediately.\",\n \"IntroducedVersion\": 1,\n \"Groups\": [\n \"Flow Control\"\n ]\n },\n {\n \"Opcode\": 1,\n \"Name\": \"sha256\",\n \"Args\": [\n \"[]byte\"\n ],\n \"Returns\": [\n \"[32]byte\"\n ],\n \"Size\": 1,\n \"Doc\": \"SHA256 hash of value A, yields [32]byte\",\n \"IntroducedVersion\": 1,\n \"Groups\": [\n \"Arithmetic\"\n ]\n }\n \"\"\"\n\n Doc: str\n Opcode: int\n Size: int\n Name: str\n IntroducedVersion: int\n Groups: list[str]\n Args: list[str]\n Returns: list[str]\n DocExtra: str\n ArgEnum: list[str]\n ArgEnumTypes: list[str]\n ArgEnumBytes: list[int]\n ArgModes: list[int]\n ArgEnumVersion: list[int]\n ImmediateNote: list[ImmediateNote]\n\n # the following values are not in the original langspec.json\n # these values are manually patched in during transform\n ArgEnumIsInput: bool\n Halts: bool\n # these values are output by a modified opdoc.go from go-algorand repo\n Cost: str\n ArgEnumDoc: list[str]\n Modes: int\n\n\nclass AlgorandLanguageSpec(typing.TypedDict):\n NamedTypes: list[NamedType]\n Ops: list[Operation]\n\n\nclass StackType(enum.StrEnum):\n uint64 = enum.auto()\n bytes = \"[]byte\"\n bytes_8 = \"[8]byte\"\n bytes_32 = \"[32]byte\"\n bytes_33 = \"[33]byte\"\n bytes_64 = \"[64]byte\"\n bytes_80 = \"[80]byte\"\n bytes_1232 = \"[1232]byte\"\n bytes_1793 = \"[1793]byte\"\n bool = enum.auto()\n address = enum.auto()\n address_or_index = enum.auto()\n any = enum.auto()\n bigint = enum.auto()\n box_name = \"boxName\"\n asset = enum.auto()\n application = enum.auto()\n state_key = \"stateKey\"\n\n\nclass RunMode(enum.StrEnum):\n app = enum.auto()\n sig = enum.auto()\n any = enum.auto()\n\n\n@attrs.define\nclass StackValue:\n name: str\n \"\"\"Name used to refer to this value in the Op.doc\"\"\"\n stack_type: StackType\n doc: str | None = None\n\n\n@attrs.define\nclass ArgEnum:\n name: str\n doc: str | None\n stack_type: StackType | None\n mode: RunMode\n value: int\n min_avm_version: int\n\n\nclass ImmediateKind(enum.StrEnum):\n uint8 = enum.auto()\n int8 = enum.auto()\n label = enum.auto()\n varuint = enum.auto()\n bytes = enum.auto()\n\n # array types\n label_array = enum.auto()\n varuint_array = enum.auto()\n bytes_array = enum.auto()\n\n # not in original lang spec\n arg_enum = enum.auto()\n\n\n@attrs.frozen(kw_only=True)\nclass Immediate:\n name: str\n \"\"\"Name used to refer to this value in the Op.doc\"\"\"\n immediate_type: ImmediateKind\n arg_enum: str | None = None\n modifies_stack_input: int | None = None\n \"\"\"Index of stack input type that this immediate modifies\"\"\"\n modifies_stack_output: int | None = None\n \"\"\"Index of stack output type that this immediate modifies\"\"\"\n \"\"\"field_group reference if immediate_type is field_group\"\"\"\n doc: str | None = None\n\n\n@attrs.define\nclass Cost:\n value: int | None\n \"\"\"Static cost of op, or None if cost is not static\"\"\"\n doc: str\n \"\"\"Documentation describing how cost is calculated\"\"\"\n\n\n@attrs.define\nclass Op:\n name: str\n \"\"\"Name of op in TEAL\"\"\"\n code: int\n \"\"\"Bytecode value\"\"\"\n size: int\n \"\"\"Size in bytes of compiled op, 0 indicate size is variable\"\"\"\n doc: list[str]\n cost: Cost\n min_avm_version: int\n \"\"\"AVM version op was introduced\"\"\"\n halts: bool\n mode: RunMode\n \"\"\"True if this op halts the program\"\"\"\n groups: list[str] = attrs.field(factory=list)\n \"\"\"Groups op belongs to\"\"\"\n stack_inputs: list[StackValue] = attrs.field(factory=list)\n \"\"\"Inputs that come from the stack\"\"\"\n immediate_args: list[Immediate] = attrs.field(factory=list)\n \"\"\"Arguments that are passed as immediate values in TEAL\"\"\"\n stack_outputs: list[StackValue] = attrs.field(factory=list)\n \"\"\"Outputs left on the stack\"\"\"\n\n\n@attrs.define\nclass LanguageSpec:\n ops: dict[str, Op] = attrs.field(factory=dict)\n arg_enums: dict[str, list[ArgEnum]] = attrs.field(factory=dict)\n\n @staticmethod\n def from_json(json: dict[str, typing.Any]) -> \"LanguageSpec\":\n return cattrs.structure(json, LanguageSpec)\n\n def to_json(self) -> dict[str, typing.Any]:\n return attrs.asdict(self)\n\n\ndef _patch_lang_spec(lang_spec: dict[str, typing.Any]) -> None:\n ops = {op[\"Name\"]: op for op in lang_spec[\"Ops\"]}\n\n # patch ops that use a stack type of any\n # for arguments that should be an Address or Address index\n for op_name in (\n \"acct_params_get\",\n \"app_local_get\",\n \"app_local_put\",\n \"app_local_del\",\n \"app_local_get_ex\",\n \"app_opted_in\",\n \"asset_holding_get\",\n \"balance\",\n \"min_balance\",\n \"voter_params_get\",\n ):\n _patch_arg_type(ops, op_name, 0, \"any\", \"address_or_index\")\n\n # patch ops that use a stack type of uint64\n # for arguments that should be an Application\n for op_name, arg_index in {\n \"app_opted_in\": 1,\n \"app_global_get_ex\": 0,\n \"app_local_get_ex\": 1,\n \"app_params_get\": 0,\n }.items():\n _patch_arg_type(ops, op_name, arg_index, \"uint64\", \"application\")\n\n # patch ops that use a stack type of uint64\n # for return types that should be a bool\n for op_name in [\n \"!\",\n ]:\n _patch_return_type(ops, op_name, 0, \"uint64\", \"bool\")\n\n # patch ops that use a stack type of uint64\n # for arguments that should be an Asset\n for op_name, arg_index in {\n \"asset_holding_get\": 1,\n \"asset_params_get\": 0,\n }.items():\n _patch_arg_type(ops, op_name, arg_index, \"uint64\", \"asset\")\n\n for op_name, arg_index in {\n \"select\": 2,\n }.items():\n _patch_arg_type(ops, op_name, arg_index, \"uint64\", \"bool\")\n\n # patch return bytes -> bigint\n for op_name in [\n \"b+\",\n \"b*\",\n ]:\n _patch_return_type(ops, op_name, 0, \"[]byte\", \"bigint\")\n\n # patch txn enum fields with asset and application types\n txn = ops[\"txn\"]\n itxn_field = ops[\"itxn_field\"]\n for op in (txn, itxn_field):\n for immediate in [\n \"XferAsset\",\n \"ConfigAsset\",\n \"FreezeAsset\",\n ]:\n _patch_arg_enum_type(op, immediate, \"uint64\", \"asset\")\n\n _patch_arg_enum_type(op, \"ApplicationID\", \"uint64\", \"application\")\n _patch_arg_enum_type(txn, \"CreatedApplicationID\", \"uint64\", \"application\")\n _patch_arg_enum_type(txn, \"CreatedAssetID\", \"uint64\", \"asset\")\n\n # patch txna enums\n txna = ops[\"txna\"]\n _patch_arg_enum_type(txna, \"Assets\", \"uint64\", \"asset\")\n _patch_arg_enum_type(txna, \"Applications\", \"uint64\", \"application\")\n\n # patch global enums\n _patch_arg_enum_type(ops[\"global\"], \"CurrentApplicationID\", \"uint64\", \"application\")\n\n # base64_decode has an ArgEnumTypes array when it probably shouldn't\n # as all stack outputs are bytes\n del ops[\"base64_decode\"][\"ArgEnumTypes\"]\n\n # itxn_field reuses the same field group as txn, however it only uses a subset of fields\n # additionally ArgEnumTypes refers to the stack input types not the output types\n itxn_field = ops[\"itxn_field\"]\n itxn_field[\"ImmediateNote\"][0][\"Reference\"] = \"itxn_field\"\n itxn_field[\"ArgEnumIsInput\"] = True\n # ops that never return encode this with a single return type of none\n # however currently this information is stripped when generating langspec.json\n ops[\"err\"][\"Halts\"] = True\n ops[\"return\"][\"Halts\"] = True\n\n\ndef _patch_arg_enum_type(\n op: dict[str, typing.Any], immediate: str, current_type: str, new_type: str\n) -> None:\n arg_enum = op[\"ArgEnum\"]\n assert immediate in arg_enum, f\"Expected {immediate} arg enum for {op['Name']}\"\n immediate_index = arg_enum.index(immediate)\n arg_enum_types = op[\"ArgEnumTypes\"]\n assert (\n arg_enum_types[immediate_index] == current_type\n ), f\"Expected {immediate} to be {current_type}\"\n arg_enum_types[immediate_index] = new_type\n\n\ndef _patch_arg_type(\n ops: dict[str, typing.Any], op_name: str, arg_index: int, current_type: str, new_type: str\n) -> None:\n op_args = ops[op_name][\"Args\"]\n assert (\n op_args[arg_index] == current_type\n ), f\"Expected {op_name} arg {arg_index} to be {current_type}\"\n op_args[arg_index] = new_type\n\n\ndef _patch_return_type(\n ops: dict[str, typing.Any], op_name: str, return_index: int, current_type: str, new_type: str\n) -> None:\n returns = ops[op_name][\"Returns\"]\n assert (\n returns[return_index] == current_type\n ), f\"Expected {op_name} return {return_index} to be {current_type}\"\n returns[return_index] = new_type\n\n\ndef create_indexed_enum(op: Operation) -> list[ArgEnum]:\n enum_names = op[\"ArgEnum\"]\n enum_types: list[str] | list[None] = op.get(\"ArgEnumTypes\", [])\n enum_docs = op[\"ArgEnumDoc\"]\n enum_bytes = op[\"ArgEnumBytes\"]\n enum_modes = op[\"ArgModes\"]\n enum_versions = op[\"ArgEnumVersion\"]\n\n if not enum_types:\n enum_types = [None] * len(enum_names)\n\n result = list[ArgEnum]()\n for enum_name, enum_type, enum_doc, enum_mode, enum_byte, enum_version in zip(\n enum_names, enum_types, enum_docs, enum_modes, enum_bytes, enum_versions, strict=True\n ):\n stack_type = None if enum_type is None else StackType(enum_type)\n enum_value = ArgEnum(\n name=enum_name,\n doc=enum_doc if enum_doc else None,\n stack_type=stack_type,\n mode=_map_enum_mode(op[\"Modes\"], enum_mode),\n value=enum_byte,\n min_avm_version=enum_version,\n )\n result.append(enum_value)\n return result\n\n\ndef _map_enum_mode(op_mode: int, arg_mode: int = 0) -> RunMode:\n mode = arg_mode or op_mode\n match mode:\n case 1:\n return RunMode.sig\n case 2:\n return RunMode.app\n case 3:\n return RunMode.any\n case _:\n raise ValueError(\"Unexpected run mode\")\n\n\ndef transform_encoding(value: str) -> ImmediateKind:\n match value:\n case \"uint8\":\n result = ImmediateKind.uint8\n case \"int8\":\n result = ImmediateKind.int8\n case \"int16 (big-endian)\":\n result = ImmediateKind.label\n case \"varuint\":\n result = ImmediateKind.varuint\n case \"varuint length, bytes\":\n result = ImmediateKind.bytes\n case \"varuint count, [varuint ...]\":\n result = ImmediateKind.varuint_array\n case \"varuint count, [varuint length, bytes ...]\":\n result = ImmediateKind.bytes_array\n case \"varuint count, [int16 (big-endian) ...]\":\n result = ImmediateKind.label_array\n case _:\n raise ValueError(f\"Unknown Encoding: {value}\")\n return result\n\n\ndef transform_stack_args(op: Operation) -> list[StackValue]:\n result = list[StackValue]()\n args = op.get(\"Args\", [])\n assert len(args) <= len(STACK_INPUT_NAMES), f\"More args than expected for {op['Name']}\"\n for index, arg_type in enumerate(op.get(\"Args\", [])):\n name = STACK_INPUT_NAMES[index]\n stack_type = StackType(arg_type)\n result.append(StackValue(name=name, stack_type=stack_type))\n return result\n\n\ndef transform_immediates(\n arg_enums: dict[str, list[ArgEnum]],\n algorand_ops: dict[str, Operation],\n op: Operation,\n) -> list[Immediate]:\n op_name = op[\"Name\"]\n result = list[Immediate]()\n for immediate in op.get(\"ImmediateNote\", []):\n arg_enum_reference = immediate.get(\"Reference\")\n if arg_enum_reference is not None:\n arg_enum = op.get(\"ArgEnum\")\n if arg_enum_reference not in arg_enums:\n try:\n enum_op = algorand_ops[arg_enum_reference]\n except KeyError:\n enum_op = op\n assert arg_enum, f\"Expected enum for {op_name}\"\n arg_enums[arg_enum_reference] = create_indexed_enum(enum_op)\n\n if arg_enum is not None:\n assert len(arg_enum) == len(\n arg_enums[arg_enum_reference]\n ), f\"Arg Enum lengths don't match for {op_name}\"\n\n modifies_stack_input: int | None = None\n modifies_stack_output: int | None = None\n\n if arg_enum_reference and any(a.stack_type for a in arg_enums[arg_enum_reference]):\n assert all(a.stack_type for a in arg_enums[arg_enum_reference])\n if op.get(\"ArgEnumIsInput\"):\n modifies_stack_input = 0\n else:\n modifies_stack_output = 0\n\n result.append(\n Immediate(\n name=immediate[\"Name\"],\n immediate_type=(\n transform_encoding(immediate[\"Encoding\"])\n if arg_enum_reference is None\n else ImmediateKind.arg_enum\n ),\n modifies_stack_input=modifies_stack_input,\n modifies_stack_output=modifies_stack_output,\n arg_enum=arg_enum_reference,\n doc=immediate[\"Comment\"],\n )\n )\n return result\n\n\ndef transform_returns(op: Operation) -> list[StackValue]:\n try:\n returns = op[\"Returns\"]\n except KeyError:\n return []\n num_returns = len(returns)\n if num_returns <= len(STACK_OUTPUT_NAMES_FEW):\n return_argument_names = STACK_OUTPUT_NAMES_FEW\n elif num_returns <= len(STACK_OUTPUT_NAMES_MANY):\n return_argument_names = STACK_OUTPUT_NAMES_MANY\n else:\n raise AssertionError(f\"More returns than expected for {op['Name']}\")\n return [\n StackValue(\n name=name,\n stack_type=StackType(return_type),\n )\n for name, return_type in zip(return_argument_names, returns, strict=False)\n ]\n\n\ndef transform_doc(op: Operation) -> list[str]:\n doc = op[\"Doc\"].splitlines()\n\n doc_extra = op.get(\"DocExtra\")\n if doc_extra:\n doc.extend(doc_extra.splitlines())\n return doc\n\n\ndef get_immediate_encoded_size(immediate: Immediate) -> int:\n match immediate.immediate_type:\n case ImmediateKind.uint8 | ImmediateKind.int8 | ImmediateKind.arg_enum:\n return 1\n case ImmediateKind.label:\n return 2\n case ImmediateKind():\n return 0\n case _:\n raise ValueError(f\"Cannot determine size of {immediate.immediate_type}\")\n\n\ndef transform_cost(op: Operation) -> Cost:\n algorand_cost = op[\"Cost\"]\n cost = Cost(value=None, doc=algorand_cost)\n with contextlib.suppress(ValueError):\n cost.value = int(algorand_cost)\n\n return cost\n\n\ndef transform_spec(lang_spec: AlgorandLanguageSpec) -> LanguageSpec:\n result = LanguageSpec()\n arg_enums = result.arg_enums\n algorand_ops = {o[\"Name\"]: o for o in sorted(lang_spec[\"Ops\"], key=lambda x: x[\"Name\"])}\n for op_name, algorand_op in algorand_ops.items():\n op = Op(\n name=op_name,\n code=algorand_op[\"Opcode\"],\n size=algorand_op[\"Size\"],\n doc=transform_doc(algorand_op),\n cost=transform_cost(algorand_op),\n min_avm_version=algorand_op[\"IntroducedVersion\"],\n groups=algorand_op[\"Groups\"],\n immediate_args=transform_immediates(arg_enums, algorand_ops, algorand_op),\n stack_inputs=transform_stack_args(algorand_op),\n stack_outputs=transform_returns(algorand_op),\n halts=algorand_op.get(\"Halts\", False),\n mode=_map_enum_mode(algorand_op[\"Modes\"]),\n )\n validate_op(result, op)\n result.ops[op.name] = op\n return result\n\n\ndef validate_op(lang_spec: LanguageSpec, op: Op) -> None:\n # validate op size\n instruction_size = 0 if op.name in VARIABLE_SIZE_OPCODES else 1\n expected_size = (\n sum([get_immediate_encoded_size(a) for a in op.immediate_args]) + instruction_size\n )\n assert op.size == expected_size, f\"Unexpected size for specified immediate args for {op.name}\"\n\n # validate immediate modifiers\n for immediate in op.immediate_args:\n if immediate.immediate_type == ImmediateKind.arg_enum:\n assert immediate.arg_enum in lang_spec.arg_enums\n if immediate.modifies_stack_input is not None:\n assert immediate.modifies_stack_input < len(op.stack_inputs), (\n f\"Immediate for {op.name} references stack input \"\n f\"that does not exist {immediate.modifies_stack_input}\"\n )\n if immediate.modifies_stack_output is not None:\n assert immediate.modifies_stack_output < len(op.stack_outputs), (\n f\"Immediate for {op.name} references stack output \"\n f\"that does not exist {immediate.modifies_stack_output}\"\n )\n else:\n assert not immediate.arg_enum\n assert not immediate.modifies_stack_input\n assert not immediate.modifies_stack_output\n\n\ndef main() -> None:\n vcs_root = Path(__file__).parent.parent\n spec_path = vcs_root \/ \"langspec.json\"\n\n output_path = vcs_root \/ \"langspec.puya.json\"\n logger.info(f\"Transforming {spec_path} to {output_path}\")\n\n lang_spec_json = json.loads(spec_path.read_text(encoding=\"utf-8\"))\n _patch_lang_spec(lang_spec_json)\n lang_spec = typing.cast(AlgorandLanguageSpec, lang_spec_json)\n\n puya_spec = transform_spec(lang_spec)\n puya_json = json.dumps(puya_spec.to_json(), indent=4)\n output_path.write_text(puya_json, encoding=\"utf-8\")\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO, format=\"%(message)s\")\n main()\n","repo_name":"algorandfoundation\/puya","path":"scripts\/transform_lang_spec.py","language":"Python","license":"NOASSERTION","size":18689} {"code":"#!\/usr\/bin\/env python3\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nfrom pathlib import Path\n\nMYPY_REPO = \"https:\/\/github.com\/python\/mypy.git\"\nVCS_ROOT = Path(__file__).parent.parent\nTYPESHED_README = \"\"\"\nThis is PuyaPy's custom typeshed, which is a curated subset of the official MyPy typeshed.\nIt only includes the required stubs used by PuyaPy as this speeds up MyPy's parsing speed\nsignificantly.\n\nHowever this means certain python modules such as `enum` or `dataclasses` cannot be used in\nPuyaPy stubs unless this typeshed is updated.\n\nThe contents of the typeshed are populated by the `scripts\/vendor_mypy.py` script, which is used\nto vendor new versions of MyPy or to update the stubs included in this typeshed. So to add new\nstubs, update that script and rerun.\n\"\"\".strip()\n\n\ndef clone_branch(version: str) -> str:\n git_clone = f\"git clone --depth=1 --branch={version} --single-branch {MYPY_REPO} .\"\n print(f\"Executing: {git_clone}\")\n subprocess.run(git_clone.split(), check=True)\n\n git_hash = subprocess.run(\"git rev-parse HEAD\".split(), capture_output=True, check=True).stdout\n assert git_hash is not None\n subprocess.run(\"rm -rf .git\".split(), check=True)\n return git_hash.decode(\"utf8\").strip()\n\n\ndef vendor_mypy(version: str) -> None:\n puya_src_dir = VCS_ROOT \/ \"src\" \/ \"puyapy\"\n vendor_dir = puya_src_dir \/ \"_vendor\"\n mypy_vendor = vendor_dir \/ \"mypy\"\n print(f\"Vendoring mypy into: {mypy_vendor}\")\n\n print(\"Removing existing mypy files...\")\n shutil.rmtree(mypy_vendor, ignore_errors=True)\n\n print(f\"Cloning mypy {version}...\")\n with tempfile.TemporaryDirectory() as tmp_dir:\n os.chdir(tmp_dir)\n git_hash = clone_branch(version)\n print(f\"Checked out mypy {version} @ {git_hash}\")\n\n print(f\"Copying mypy into {mypy_vendor}...\")\n shutil.copytree(Path(tmp_dir) \/ \"mypy\", mypy_vendor)\n (mypy_vendor \/ \".version\").write_text(f\"{version}: {git_hash}\")\n print(\"Updating custom typeshed\")\n update_puya_typeshed(mypy_vendor \/ \"typeshed\", puya_src_dir \/ \"_typeshed\")\n\n\ndef update_puya_typeshed(mypy_typeshed: Path, puya_typeshed: Path) -> None:\n shutil.rmtree(puya_typeshed, ignore_errors=True)\n\n stubs = Path(\"stubs\")\n stdlib = Path(\"stdlib\")\n relative_to_copy = [\n # hard coded in mpyy\/modulefinder.py, minimum requirements for mypy\n stubs \/ \"mypy-extensions\" \/ \"mypy_extensions.pyi\",\n stdlib \/ \"VERSIONS\",\n # hard coded in mpyy\/build.py, minimum requirements for mypy\n stdlib \/ \"builtins.pyi\",\n stdlib \/ \"typing.pyi\",\n stdlib \/ \"types.pyi\",\n stdlib \/ \"typing_extensions.pyi\",\n stdlib \/ \"_typeshed\" \/ \"__init__.pyi\",\n stdlib \/ \"_collections_abc.pyi\",\n stdlib \/ \"collections\" \/ \"abc.pyi\",\n stdlib \/ \"sys\" \/ \"__init__.pyi\",\n stdlib \/ \"abc.pyi\",\n # needed for puyapy\n # stdlib \/ \"enum.pyi\"\n ]\n\n (puya_typeshed \/ stdlib).mkdir(exist_ok=True, parents=True)\n (puya_typeshed \/ stubs).mkdir(exist_ok=True, parents=True)\n for relative in relative_to_copy:\n copy_src = mypy_typeshed \/ relative\n copy_dst = puya_typeshed \/ relative\n if copy_src.is_dir():\n shutil.copytree(copy_src, copy_dst)\n else:\n copy_dst.parent.mkdir(exist_ok=True, parents=True)\n shutil.copy(copy_src, copy_dst)\n (puya_typeshed \/ stdlib \/ \"collections\" \/ \"__init__.pyi\").touch()\n (puya_typeshed \/ \"README.md\").write_text(TYPESHED_README)\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n vendor_mypy(version=sys.argv[1])\n else:\n print(\"Usage: python vendor_mypy.py \")\n print(\"e.g. python vendor_mypy.py v1.5.0\")\n","repo_name":"algorandfoundation\/puya","path":"scripts\/vendor_mypy.py","language":"Python","license":"NOASSERTION","size":3730} {"code":"","repo_name":"algorandfoundation\/puya","path":"src\/_puya_lib\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"from algopy import (\n Bytes,\n UInt64,\n subroutine,\n urange,\n)\nfrom algopy.op import (\n btoi,\n bzero,\n extract,\n extract_uint16,\n getbit,\n itob,\n replace,\n select_uint64,\n setbit_bytes,\n substring,\n)\n\nUINT16_SIZE = 2\nUINT64_SIZE = 8\nUINT16_OFFSET = UINT64_SIZE - UINT16_SIZE\n\n\n@subroutine\ndef dynamic_array_pop_bit(array: Bytes) -> tuple[Bytes, Bytes]:\n \"\"\"\n Pop the last item from an arc4 dynamic array of arc4 encoded boolean items\n\n array: The bytes for the source array\n\n returns: tuple of (The popped item, The updated bytes for the source array)\n \"\"\"\n array_length = extract_uint16(array, 0)\n length_minus_1 = array_length - 1\n result = replace(array, 0, extract(itob(length_minus_1), UINT16_OFFSET, 0))\n popped_location = length_minus_1 + UINT16_SIZE * 8\n popped = setbit_bytes(b\"\\x00\", 0, getbit(result, popped_location))\n result = setbit_bytes(result, popped_location, 0)\n result = substring(result, 0, UINT16_SIZE + ((length_minus_1 + 7) \/\/ 8))\n return popped, result\n\n\n@subroutine\ndef dynamic_array_pop_fixed_size(array: Bytes, fixed_byte_size: UInt64) -> tuple[Bytes, Bytes]:\n \"\"\"\n Pop the last item from an arc4 dynamic array of fixed sized items\n\n array: The bytes for the source array\n\n returns: tuple of (The popped item, The updated bytes for the source array)\n \"\"\"\n array_length = extract_uint16(array, 0)\n length_minus_1 = array_length - 1\n result = replace(array, 0, extract(itob(length_minus_1), UINT16_OFFSET, 0))\n item_location = result.length - fixed_byte_size\n popped = extract(result, item_location, fixed_byte_size)\n result = substring(result, 0, item_location)\n return popped, result\n\n\n@subroutine\ndef dynamic_array_pop_byte_length_head(array: Bytes) -> tuple[Bytes, Bytes]:\n \"\"\"\n Pop the last item from an arc4 dynamic array of items that are prefixed with their length in\n bytes, e.g. arc4.String, arc4.DynamicBytes\n\n source: The bytes for the source array\n\n returns: tuple of (The popped item, The updated bytes for the source array)\n \"\"\"\n array_length = extract_uint16(array, 0)\n length_minus_1 = array_length - 1\n popped_header_offset = length_minus_1 * UINT16_SIZE\n head_and_tail = extract(array, UINT16_SIZE, 0)\n popped_offset = extract_uint16(head_and_tail, popped_header_offset)\n\n popped = substring(head_and_tail, popped_offset, head_and_tail.length)\n head_and_tail = substring(head_and_tail, 0, popped_header_offset) + substring(\n head_and_tail, popped_header_offset + 2, popped_offset\n )\n\n updated = extract(\n itob(length_minus_1), UINT16_OFFSET, UINT16_SIZE\n ) + recalculate_head_for_elements_with_byte_length_head(\n array_head_and_tail=head_and_tail, length=length_minus_1, start_at_index=UInt64(0)\n )\n\n return popped, updated\n\n\n@subroutine\ndef dynamic_array_pop_dynamic_element(array: Bytes) -> tuple[Bytes, Bytes]:\n \"\"\"\n Pop the last item from an arc4 dynamic array of dynamically sized items\n\n array: The bytes for the source array\n\n returns: tuple of (The popped item, The updated bytes for the source array)\n \"\"\"\n array_length = extract_uint16(array, 0)\n length_minus_1 = array_length - 1\n popped_header_offset = length_minus_1 * UINT16_SIZE\n head_and_tail = extract(array, UINT16_SIZE, 0)\n popped_offset = extract_uint16(head_and_tail, popped_header_offset)\n\n popped = substring(head_and_tail, popped_offset, head_and_tail.length)\n\n new_head = Bytes()\n for head_offset in urange(0, length_minus_1 * UINT16_SIZE, UINT16_SIZE):\n item_offset = extract_uint16(head_and_tail, head_offset)\n item_offset -= UINT16_SIZE\n new_head += extract(itob(item_offset), UINT16_OFFSET, UINT16_SIZE)\n\n updated = (\n extract(itob(length_minus_1), UINT16_OFFSET, UINT16_SIZE)\n + new_head\n + substring(head_and_tail, popped_header_offset + UINT16_SIZE, popped_offset)\n )\n\n return popped, updated\n\n\n@subroutine\ndef dynamic_array_concat_bits(\n *, array: Bytes, new_items_bytes: Bytes, new_items_count: UInt64, is_packed: bool\n) -> Bytes:\n \"\"\"\n Concat data to an arc4 dynamic array of arc4 encoded boolean values\n\n array: The bytes for the source array\n new_items_bytes: Either the data portion of an arc4 packed array of booleans\n or\n a sparse array of concatenated arc4 booleans\n new_items_count: The count of new items being added\n is_packed: True if new_items_bytes represents a packed array, else False\n\n returns: The updated bytes for the source array\n \"\"\"\n array_length = extract_uint16(array, 0)\n new_array_length = array_length + new_items_count\n new_array_length_b = extract(itob(new_array_length), UINT16_OFFSET, 0)\n result = replace(array, 0, new_array_length_b)\n current_bytes = (array_length + 7) \/\/ 8\n required_bytes = (new_array_length + 7) \/\/ 8\n if current_bytes < required_bytes:\n result += bzero(required_bytes - current_bytes)\n\n write_offset = array_length + 8 * UINT16_SIZE\n for i in urange(0, new_items_count, UInt64(1) if is_packed else UInt64(8)):\n result = setbit_bytes(result, write_offset, getbit(new_items_bytes, i))\n write_offset += 1\n\n return result\n\n\n@subroutine\ndef dynamic_array_concat_byte_length_head(\n array: Bytes, new_items_bytes: Bytes, new_items_count: UInt64\n) -> Bytes:\n \"\"\"\n Replace a single item in an arc4 dynamic array of items that are prefixed with\n their byte length\n\n array: The bytes of the source array\n new_items_bytes: The bytes for all new items, concatenated\n new_items_counts: The count of new items being added\n\n returns: The updated bytes for the source array\n \"\"\"\n array_length = extract_uint16(array, 0)\n new_length = array_length + new_items_count\n header_end = array_length * UINT16_SIZE + 2\n\n return extract(\n itob(new_length), UINT16_OFFSET, UINT16_SIZE\n ) + recalculate_head_for_elements_with_byte_length_head(\n array_head_and_tail=(\n substring(array, 2, header_end)\n + bzero(new_items_count * UINT16_SIZE)\n + substring(array, header_end, array.length)\n + new_items_bytes\n ),\n length=new_length,\n start_at_index=UInt64(0),\n )\n\n\n@subroutine\ndef dynamic_array_concat_dynamic_element(\n *,\n array_items_count: UInt64,\n array_head_and_tail: Bytes,\n new_items_count: UInt64,\n new_head_and_tail: Bytes,\n) -> Bytes:\n new_head = Bytes()\n item_offset_adjustment = new_items_count * UINT16_SIZE\n for head_offset in urange(0, array_items_count * UINT16_SIZE, UINT16_SIZE):\n item_offset = extract_uint16(array_head_and_tail, head_offset)\n new_head += extract(itob(item_offset_adjustment + item_offset), UINT16_OFFSET, UINT16_SIZE)\n\n item_offset_adjustment = array_head_and_tail.length\n for head_offset in urange(0, new_items_count * UINT16_SIZE, UINT16_SIZE):\n item_offset = extract_uint16(new_head_and_tail, head_offset)\n new_head += extract(itob(item_offset_adjustment + item_offset), UINT16_OFFSET, UINT16_SIZE)\n return (\n extract(itob(array_items_count + new_items_count), UINT16_OFFSET, UINT16_SIZE)\n + new_head\n + substring(\n array_head_and_tail, array_items_count * UINT16_SIZE, array_head_and_tail.length\n )\n + substring(new_head_and_tail, new_items_count * UINT16_SIZE, new_head_and_tail.length)\n )\n\n\n@subroutine\ndef dynamic_array_replace_byte_length_head(array: Bytes, new_item: Bytes, index: UInt64) -> Bytes:\n \"\"\"\n Replace a single item in an arc4 dynamic array of items that are prefixed with\n their byte length\n\n array: The bytes of the source array\n new_item: The bytes of the new item to be inserted\n index: The index to insert the new item at\n array_length: The length of the array\n\n returns: The updated bytes for the source array\n \"\"\"\n size_b = substring(array, 0, UINT16_SIZE)\n array_length = btoi(size_b)\n return size_b + static_array_replace_byte_length_head(\n array_head_and_tail=extract(array, UINT16_SIZE, 0),\n new_item=new_item,\n index=index,\n array_length=array_length,\n )\n\n\n@subroutine\ndef dynamic_array_replace_dynamic_element(source: Bytes, new_item: Bytes, index: UInt64) -> Bytes:\n size_b = substring(source, 0, UINT16_SIZE)\n array_length = btoi(size_b)\n return size_b + static_array_replace_dynamic_element(\n array_head_and_tail=extract(source, UINT16_SIZE, 0),\n new_item=new_item,\n index=index,\n array_length=array_length,\n )\n\n\n@subroutine\ndef static_array_replace_dynamic_element(\n *, array_head_and_tail: Bytes, new_item: Bytes, index: UInt64, array_length: UInt64\n) -> Bytes:\n original_offset = extract_uint16(array_head_and_tail, index * 2)\n next_item_offset = extract_uint16(array_head_and_tail, (index + 1) * 2)\n end_of_tail = array_head_and_tail.length\n is_before_end = array_length - index - 1\n end_offset = select_uint64(end_of_tail, next_item_offset, is_before_end)\n\n original_item_length = end_offset - original_offset\n new_item_length = new_item.length\n new_head_and_tail = (\n substring(array_head_and_tail, 0, original_offset)\n + new_item\n + substring(array_head_and_tail, end_offset, end_of_tail)\n )\n for head_offset in urange((index + 1) * 2, array_length * 2, 2):\n tail_offset = extract_uint16(new_head_and_tail, head_offset)\n tail_offset += new_item_length\n tail_offset -= original_item_length\n tail_offset_bytes = extract(itob(tail_offset), UINT16_OFFSET, UINT16_SIZE)\n new_head_and_tail = replace(new_head_and_tail, head_offset, tail_offset_bytes)\n return new_head_and_tail\n\n\n@subroutine\ndef static_array_replace_byte_length_head(\n array_head_and_tail: Bytes, new_item: Bytes, index: UInt64, array_length: UInt64\n) -> Bytes:\n \"\"\"\n Replace a single item in an arc4 dynamic array of items that are prefixed with\n their byte length\n\n array_head_and_tail: The head and tail bytes of the source array\n new_item: The bytes of the new item to be inserted\n index: The index to insert the new item at\n array_length: The length of the array\n\n returns: The updated bytes for the source array\n \"\"\"\n assert index < array_length, \"Index out of bounds\"\n offset_for_index = extract_uint16(array_head_and_tail, index * UINT16_SIZE)\n old_item_length = extract_uint16(array_head_and_tail, offset_for_index)\n old_item_end = offset_for_index + old_item_length + UINT16_SIZE\n return recalculate_head_for_elements_with_byte_length_head(\n array_head_and_tail=substring(array_head_and_tail, 0, offset_for_index)\n + new_item\n + substring(array_head_and_tail, old_item_end, array_head_and_tail.length),\n length=array_length,\n start_at_index=index,\n )\n\n\n@subroutine\ndef recalculate_head_for_elements_with_byte_length_head(\n array_head_and_tail: Bytes, length: UInt64, start_at_index: UInt64\n) -> Bytes:\n \"\"\"\n Recalculates the offset values of an arc4 static array, where each item's head consists of\n its length in bytes as uint16\n\n array_data: The static array data\n length: The length of the static array\n start_at_index: Optionally start at a non-zero index for performance optimisation. The offset\n at this index is assumed to be correct if start_at_index is not 0\n\n returns: The updated bytes for the source array\n \"\"\"\n tail_offset = select_uint64(\n length * UINT16_SIZE,\n extract_uint16(array_head_and_tail, start_at_index * UINT16_SIZE),\n start_at_index, # use length * UINT16_SIZE if 0 otherwise inspect head\n )\n\n for head_offset in urange(start_at_index * UINT16_SIZE, length * UINT16_SIZE, UINT16_SIZE):\n tail_offset_bytes = extract(itob(tail_offset), UINT16_OFFSET, UINT16_SIZE)\n array_head_and_tail = replace(array_head_and_tail, head_offset, tail_offset_bytes)\n tail_offset += extract_uint16(array_head_and_tail, tail_offset) + UINT16_SIZE\n head_offset += UINT16_SIZE\n return array_head_and_tail\n","repo_name":"algorandfoundation\/puya","path":"src\/_puya_lib\/arc4.py","language":"Python","license":"NOASSERTION","size":12234} {"code":"from algopy import Bytes, UInt64, op, subroutine\n\n\n@subroutine\ndef is_substring(item: Bytes, sequence: Bytes) -> bool:\n \"\"\"\n Search for a shorter string in a larger one.\n \"\"\"\n\n start = UInt64(0)\n while start + item.length <= sequence.length:\n if item == op.substring(sequence, start, start + item.length):\n return True\n start += 1\n return False\n","repo_name":"algorandfoundation\/puya","path":"src\/_puya_lib\/bytes_.py","language":"Python","license":"NOASSERTION","size":388} {"code":"from algopy import (\n Bytes,\n OnCompleteAction,\n OpUpFeeSource,\n TransactionType,\n UInt64,\n op,\n subroutine,\n)\n\n\n@subroutine\ndef ensure_budget(required_budget: UInt64, fee_source: OpUpFeeSource) -> None:\n # A budget buffer is necessary to deal with an edge case of ensure_budget():\n # if the current budget is equal to or only slightly higher than the\n # required budget then it's possible for ensure_budget() to return with a\n # current budget less than the required budget. The buffer prevents this\n # from being the case.\n required_budget_with_buffer = required_budget + 10\n while required_budget_with_buffer > op.Global.opcode_budget():\n op.ITxnCreate.begin()\n op.ITxnCreate.set_type_enum(TransactionType.ApplicationCall)\n op.ITxnCreate.set_on_completion(OnCompleteAction.DeleteApplication)\n op.ITxnCreate.set_approval_program(Bytes.from_hex(\"068101\"))\n op.ITxnCreate.set_clear_state_program(Bytes.from_hex(\"068101\"))\n match fee_source:\n case OpUpFeeSource.GroupCredit:\n op.ITxnCreate.set_fee(0)\n case OpUpFeeSource.AppAccount:\n op.ITxnCreate.set_fee(op.Global.min_txn_fee)\n # case OpUpFeeSource.Any:\n # any means no fee set\n op.ITxnCreate.submit()\n","repo_name":"algorandfoundation\/puya","path":"src\/_puya_lib\/util.py","language":"Python","license":"NOASSERTION","size":1326} {"code":"","repo_name":"algorandfoundation\/puya","path":"src\/puya\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"import argparse\nfrom importlib.metadata import version\nfrom pathlib import Path\n\nimport attrs\n\nfrom puya.log import LogFormat, LogLevel, configure_logging\nfrom puya.main import main\n\n\n@attrs.define(kw_only=True)\nclass _PuyaCLIArgs:\n options: Path | None = None\n awst: Path | None = None\n source_annotations: Path | None = None\n log_level: LogLevel = LogLevel.info\n log_format: LogFormat = LogFormat.default\n\n\ndef cli() -> None:\n parser = argparse.ArgumentParser(\n prog=\"puya\", formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n # TODO: use version of puya instead once package is split\n parser.add_argument(\"--version\", action=\"version\", version=f\"%(prog)s {version('puyapy')}\")\n parser.add_argument(\n \"--log-level\", type=LogLevel.from_string, choices=list(LogLevel), default=LogLevel.info\n )\n parser.add_argument(\n \"--log-format\",\n type=LogFormat.from_string,\n choices=list(LogFormat),\n default=LogFormat.default,\n )\n parser.add_argument(\"--options\", type=Path, required=True)\n parser.add_argument(\"--awst\", type=Path, required=True)\n parser.add_argument(\"--source-annotations\", type=Path)\n parsed_args = _PuyaCLIArgs()\n parser.parse_args(namespace=parsed_args)\n configure_logging(min_log_level=parsed_args.log_level, log_format=parsed_args.log_format)\n\n assert parsed_args.options\n options_json = parsed_args.options.read_text(\"utf8\")\n assert parsed_args.awst\n awst_json = parsed_args.awst.read_text(\"utf8\")\n source_annotations_json = None\n if parsed_args.source_annotations:\n source_annotations_json = parsed_args.source_annotations.read_text(\"utf8\")\n main(\n options_json=options_json,\n awst_json=awst_json,\n source_annotations_json=source_annotations_json,\n )\n\n\nif __name__ == \"__main__\":\n cli()\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/__main__.py","language":"Python","license":"NOASSERTION","size":1862} {"code":"ZERO_ADDRESS = \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ\"\nENCODED_ADDRESS_LENGTH = 58\nPUBLIC_KEY_HASH_LENGTH = 32\nADDRESS_CHECKSUM_LENGTH = 4\nMAX_BIGUINT_BITS = 512\nMAX_UINT64 = 2**64 - 1\nMAX_BIGUINT_BYTES = MAX_BIGUINT_BITS \/\/ 8\nMAX_BYTES_LENGTH = 4096\nMAX_SCRATCH_SLOT_NUMBER = 255\nMAX_GLOBAL_STATE_KEYS = 64\nMAX_LOCAL_STATE_KEYS = 16\nMAX_STATE_KEY_LENGTH = 64\nMIN_BOX_KEY_LENGTH = 1\nMAX_BOX_KEY_LENGTH = 64\nMAX_TRANSACTION_GROUP_SIZE = 16\nMAX_APP_PAGE_SIZE = 2048\nHASH_PREFIX_PROGRAM = b\"Program\"\n\"\"\"Represents the prefix added to a program before hashing e.g. for a LogicSigs address\"\"\"\n# Which language versions does this version of puya support targeting\n# This will typically just be the current mainnet version and potentially the vNext if it doesn't\n# contain breaking changes\nSUPPORTED_AVM_VERSIONS = [10, 11, 12]\n# Which language version is currently deployed to mainnet\nMAINNET_AVM_VERSION = 10\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/algo_constants.py","language":"Python","license":"NOASSERTION","size":925} {"code":"import base64\nimport json\nimport typing\nfrom collections.abc import Collection, Mapping, Sequence\n\nfrom puya import (\n artifact_metadata as md,\n log,\n)\nfrom puya.avm import OnCompletionAction\nfrom puya.awst.nodes import (\n AppStorageKind,\n ARC4CreateOption,\n)\nfrom puya.parse import SourceLocation\n\nOCA_ARC32_MAPPING = {\n OnCompletionAction.NoOp: \"no_op\",\n OnCompletionAction.OptIn: \"opt_in\",\n OnCompletionAction.CloseOut: \"close_out\",\n OnCompletionAction.ClearState: \"clear_state\",\n OnCompletionAction.UpdateApplication: \"update_application\",\n OnCompletionAction.DeleteApplication: \"delete_application\",\n}\n\nJSONValue: typing.TypeAlias = \"str | int | float | bool | None | Sequence[JSONValue] | JSONDict\"\nJSONDict: typing.TypeAlias = Mapping[str, \"JSONValue\"]\n\nlogger = log.get_logger(__name__)\n\n\ndef _encode_source(teal_text: str) -> str:\n return base64.b64encode(teal_text.encode()).decode(\"utf-8\")\n\n\ndef _encode_schema_declaration(state: md.ContractState) -> JSONDict:\n return {\n \"type\": state.storage_type.name,\n \"key\": state.key_or_prefix.decode(\"utf-8\"), # TODO: support not utf8 keys?\n \"descr\": state.description,\n }\n\n\ndef _encode_state_declaration(state: md.StateTotals) -> JSONDict:\n return {\n \"global\": {\n \"num_byte_slices\": state.global_bytes,\n \"num_uints\": state.global_uints,\n },\n \"local\": {\n \"num_byte_slices\": state.local_bytes,\n \"num_uints\": state.local_uints,\n },\n }\n\n\ndef _encode_schema(state: Collection[md.ContractState]) -> JSONDict:\n return {\n \"declared\": {\n s.name: _encode_schema_declaration(s) for s in sorted(state, key=lambda s: s.name)\n },\n \"reserved\": {}, # TODO?\n }\n\n\ndef _encode_call_config(method: md.ARC4Method) -> JSONDict:\n match method.create:\n case ARC4CreateOption.require:\n call_config = \"CREATE\"\n case ARC4CreateOption.allow:\n call_config = \"ALL\"\n case ARC4CreateOption.disallow:\n call_config = \"CALL\"\n case never:\n typing.assert_never(never)\n return {OCA_ARC32_MAPPING[oca]: call_config for oca in method.allowed_completion_types}\n\n\ndef _encode_bare_method_configs(methods: Sequence[md.ARC4BareMethod]) -> JSONDict:\n result: dict[str, JSONValue] = {}\n for method in methods:\n result.update(**_encode_call_config(method))\n return result\n\n\ndef _get_signature(method: md.ARC4ABIMethod) -> str:\n return f\"{method.name}({','.join(m.type_ for m in method.args)}){method.returns.type_}\"\n\n\ndef _encode_default_arg(arg: md.ARC4MethodArg, loc: SourceLocation | None) -> JSONDict | None:\n match arg.client_default:\n case None:\n return None\n case md.MethodArgDefaultConstant(data=constant_data, type_=constant_arc4_type):\n if constant_arc4_type == \"string\":\n string = constant_data[2:].decode(\"utf8\")\n return {\"source\": \"constant\", \"data\": string}\n elif constant_arc4_type.startswith(\"uint\"):\n number = int.from_bytes(constant_data, signed=False)\n return {\"source\": \"constant\", \"data\": number}\n else:\n logger.warning(\n f\"parameter {arg.name!r} has unsupported default constant type for ARC-32\",\n location=loc,\n )\n return None\n case md.MethodArgDefaultFromMethod(\n name=method_name, return_type=return_type, readonly=readonly\n ):\n return {\n \"source\": \"abi-method\",\n \"data\": {\n \"name\": method_name,\n \"args\": [],\n \"readonly\": readonly, # ARC-22\n \"returns\": {\"type\": return_type},\n },\n }\n case md.MethodArgDefaultFromState(kind=kind, key=key):\n match kind:\n case AppStorageKind.app_global:\n source_name = \"global-state\"\n case AppStorageKind.account_local:\n source_name = \"local-state\"\n case AppStorageKind.box:\n logger.error(\n \"default argument from box storage are not supported by ARC-32\",\n location=loc,\n )\n case unexpected:\n typing.assert_never(unexpected)\n return {\n \"source\": source_name,\n # TODO: handle non utf-8 bytes\n \"data\": key.decode(\"utf-8\"),\n }\n\n\ndef _encode_arc32_method_hint(metadata: md.ContractMetaData, method: md.ARC4ABIMethod) -> JSONDict:\n structs = {a.name: metadata.structs[a.struct] for a in method.args if a.struct}\n if method.returns.struct:\n structs[\"output\"] = metadata.structs[method.returns.struct]\n default_arguments = {\n arg.name: default\n for arg in method.args\n if (default := _encode_default_arg(arg, method.config_location)) is not None\n }\n return {\n # deprecated by ARC-22\n \"read_only\": True if method.readonly else None,\n \"default_arguments\": default_arguments or None,\n \"call_config\": _encode_call_config(method),\n \"structs\": _encode_arc32_method_structs(structs),\n }\n\n\ndef _encode_arc32_method_structs(structs: Mapping[str, md.ARC4Struct]) -> JSONDict | None:\n if len(structs):\n return {\n struct_purpose: {\n \"name\": struct_def.name,\n \"elements\": [[f.name, f.type] for f in struct_def.fields],\n }\n for struct_purpose, struct_def in structs.items()\n }\n return None\n\n\ndef _encode_arc32_hints(\n metadata: md.ContractMetaData, methods: list[md.ARC4ABIMethod]\n) -> JSONDict:\n return {\n _get_signature(method): _encode_arc32_method_hint(metadata, method) for method in methods\n }\n\n\ndef _encode_abi_method(method: md.ARC4ABIMethod) -> JSONDict:\n return {\n \"name\": method.name,\n \"args\": [\n {\n \"type\": arg.type_,\n \"name\": arg.name,\n \"desc\": arg.desc,\n }\n for arg in method.args\n ],\n \"readonly\": method.readonly, # ARC-22\n \"returns\": {\n \"type\": method.returns.type_,\n \"desc\": method.returns.desc,\n },\n \"desc\": method.desc,\n }\n\n\ndef _encode_arc4_contract(\n name: str, desc: str | None, methods: Sequence[md.ARC4ABIMethod]\n) -> JSONDict:\n return {\n \"name\": name,\n \"desc\": desc,\n \"methods\": [_encode_abi_method(m) for m in methods],\n \"networks\": {},\n }\n\n\ndef _filter_none(value: JSONDict) -> JSONValue:\n if isinstance(value, dict):\n return {k: _filter_none(v) for k, v in value.items() if v is not None}\n if isinstance(value, list):\n return list(map(_filter_none, value))\n return value\n\n\ndef create_arc32_json(\n approval_program: str, clear_program: str, metadata: md.ContractMetaData\n) -> str:\n bare_methods = [m for m in metadata.arc4_methods if isinstance(m, md.ARC4BareMethod)]\n abi_methods = [m for m in metadata.arc4_methods if isinstance(m, md.ARC4ABIMethod)]\n app_spec = {\n \"hints\": _encode_arc32_hints(metadata, abi_methods),\n \"source\": {\n \"approval\": _encode_source(approval_program),\n \"clear\": _encode_source(clear_program),\n },\n \"state\": _encode_state_declaration(metadata.state_totals),\n \"schema\": {\n \"global\": _encode_schema(metadata.global_state.values()),\n \"local\": _encode_schema(metadata.local_state.values()),\n },\n \"contract\": _encode_arc4_contract(metadata.name, metadata.description, abi_methods),\n \"bare_call_config\": _encode_bare_method_configs(bare_methods),\n }\n return json.dumps(_filter_none(app_spec), indent=4)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/arc32.py","language":"Python","license":"NOASSERTION","size":7940} {"code":"import base64\nimport itertools\nimport typing\nfrom collections import defaultdict\nfrom collections.abc import Iterable, Mapping, Sequence\nfrom importlib.metadata import version as metadata_version\n\nfrom cattrs.preconf.json import make_converter\nfrom packaging import version\n\nfrom puya import (\n arc56_models as models,\n log,\n)\nfrom puya.artifact_metadata import (\n ARC4ABIMethod,\n ARC4BareMethod,\n ARC4Struct,\n ContractMetaData,\n ContractState,\n MethodArgDefault,\n MethodArgDefaultConstant,\n MethodArgDefaultFromMethod,\n MethodArgDefaultFromState,\n)\nfrom puya.awst.nodes import (\n AppStorageKind,\n ARC4CreateOption,\n)\nfrom puya.compilation_artifacts import CompiledProgram, DebugInfo\nfrom puya.utils import unique\n\n# TODO: use puya once the backend is shipped as separate package\n_ALGOPY_VERSION = version.parse(metadata_version(\"puyapy\"))\nlogger = log.get_logger(__name__)\n\n\ndef create_arc56_json(\n *,\n metadata: ContractMetaData,\n approval_program: CompiledProgram,\n clear_program: CompiledProgram,\n template_prefix: str,\n) -> str:\n assert approval_program.debug_info is not None\n assert clear_program.debug_info is not None\n\n converter = make_converter(omit_if_default=True)\n bare_methods = [m for m in metadata.arc4_methods if isinstance(m, ARC4BareMethod)]\n abi_methods = [m for m in metadata.arc4_methods if isinstance(m, ARC4ABIMethod)]\n\n # use shorter name for structs unless there is a collision\n aliases = _StructAliases(metadata.structs.values())\n\n schema = metadata.state_totals\n app_spec = models.Contract(\n arcs=(22, 28),\n name=metadata.name,\n desc=metadata.description,\n networks={},\n structs={\n aliases.resolve(n): [\n models.StructField(\n name=e.name,\n type=aliases.resolve(e.struct) or e.type,\n )\n for e in s.fields\n ]\n for n, s in metadata.structs.items()\n },\n methods=[\n models.Method(\n name=m.name,\n desc=m.desc,\n args=[\n models.MethodArg(\n type=a.type_,\n name=a.name,\n desc=a.desc,\n struct=aliases.resolve(a.struct),\n defaultValue=_encode_default_arg(a.client_default),\n )\n for a in m.args\n ],\n returns=models.MethodReturns(\n type=m.returns.type_,\n desc=m.returns.desc,\n struct=aliases.resolve(m.returns.struct),\n ),\n actions=_method_actions(m),\n readonly=m.readonly,\n events=[_struct_to_event(aliases, struct) for struct in m.events],\n # left for users to fill in for now\n recommendations=models.MethodRecommendations(\n innerTransactionCount=None,\n boxes=None,\n accounts=None,\n apps=None,\n assets=None,\n ),\n )\n for m in abi_methods\n ],\n state=models.ContractState(\n schema={\n \"global\": {\"ints\": schema.global_uints, \"bytes\": schema.global_bytes},\n \"local\": {\"ints\": schema.local_uints, \"bytes\": schema.local_bytes},\n },\n keys={\n \"global\": _storage_keys(aliases, metadata.global_state),\n \"local\": _storage_keys(aliases, metadata.local_state),\n \"box\": _storage_keys(aliases, metadata.boxes),\n },\n maps={\n # note: at present there is no way of defining global\/local maps\n \"global\": _storage_maps(aliases, metadata.global_state),\n \"local\": _storage_maps(aliases, metadata.local_state),\n \"box\": _storage_maps(aliases, metadata.boxes),\n },\n ),\n bareActions=_combine_actions(list(map(_method_actions, bare_methods))),\n sourceInfo={\n \"approval\": models.ProgramSourceInfo(\n sourceInfo=_get_source_info(approval_program.debug_info),\n pcOffsetMethod=\"cblocks\" if approval_program.debug_info.op_pc_offset else \"none\",\n ),\n \"clear\": models.ProgramSourceInfo(\n sourceInfo=_get_source_info(clear_program.debug_info),\n pcOffsetMethod=\"cblocks\" if clear_program.debug_info.op_pc_offset else \"none\",\n ),\n },\n source={\n \"approval\": _encode_str(approval_program.teal_src),\n \"clear\": _encode_str(clear_program.teal_src),\n },\n byteCode=(\n {\n \"approval\": _encode_bytes(approval_program.bytecode),\n \"clear\": _encode_bytes(clear_program.bytecode),\n }\n if approval_program.bytecode and clear_program.bytecode\n else None\n ),\n compilerInfo=(\n _compiler_info() if approval_program.bytecode and clear_program.bytecode else None\n ),\n events=[\n _struct_to_event(aliases, struct)\n for struct in unique(\n e for m in metadata.arc4_methods if isinstance(m, ARC4ABIMethod) for e in m.events\n )\n ],\n templateVariables={\n name.removeprefix(template_prefix): models.TemplateVariable(\n type=aliases.resolve(metadata.template_variable_types[name]),\n value=(\n _encode_bytes(value.to_bytes(length=8) if isinstance(value, int) else value)\n if value is not None\n else None\n ),\n )\n for program in (approval_program, clear_program)\n for name, value in program.template_variables.items()\n },\n # TODO: provide a way for contracts to declare \"public\" scratch vars\n scratchVariables=None,\n )\n return converter.dumps(app_spec, indent=4)\n\n\ndef _get_source_info(debug_info: DebugInfo) -> Sequence[models.SourceInfo]:\n errors = defaultdict[str, list[int]](list)\n for pc, event in debug_info.pc_events.items():\n if error := event.get(\"error\"):\n errors[error].append(pc)\n return [\n models.SourceInfo(\n pc=errors[error],\n errorMessage=error,\n )\n for error in sorted(errors)\n ]\n\n\nclass _StructAliases:\n def __init__(self, structs: Iterable[ARC4Struct]) -> None:\n alias_to_fullname = dict[str, str]()\n for struct in structs:\n alias = (\n struct.fullname\n if struct.name in alias_to_fullname or struct.name in models.AVMType\n else struct.name\n )\n alias_to_fullname[alias] = struct.fullname\n self.aliases = {v: k for k, v in alias_to_fullname.items()}\n\n @typing.overload\n def resolve(self, struct: str) -> str: ...\n\n @typing.overload\n def resolve(self, struct: None) -> None: ...\n\n def resolve(self, struct: str | None) -> str | None:\n if struct is None:\n return None\n return self.aliases.get(struct, struct)\n\n\ndef _struct_to_event(structs: _StructAliases, struct: ARC4Struct) -> models.Event:\n return models.Event(\n name=structs.resolve(struct.name),\n desc=struct.desc,\n args=[\n models.EventArg(\n name=f.name,\n type=f.type,\n struct=structs.resolve(f.struct),\n )\n for f in struct.fields\n ],\n )\n\n\ndef _storage_keys(\n structs: _StructAliases, state: Mapping[str, ContractState]\n) -> models.StorageKeys:\n return {\n n: models.StorageKey(\n desc=m.description,\n keyType=structs.resolve(m.arc56_key_type),\n valueType=structs.resolve(m.arc56_value_type),\n key=_encode_bytes(m.key_or_prefix),\n )\n for n, m in state.items()\n if not m.is_map\n }\n\n\ndef _storage_maps(\n structs: _StructAliases, state: Mapping[str, ContractState]\n) -> models.StorageMaps:\n return {\n n: models.StorageMap(\n desc=m.description,\n keyType=structs.resolve(m.arc56_key_type),\n valueType=structs.resolve(m.arc56_value_type),\n prefix=_encode_bytes(m.key_or_prefix),\n )\n for n, m in state.items()\n if m.is_map\n }\n\n\ndef _method_actions(method: ARC4BareMethod | ARC4ABIMethod) -> models.MethodActions:\n return models.MethodActions(\n create=[\n oca.name\n for oca in method.allowed_completion_types\n if method.create != ARC4CreateOption.disallow and allowed_create_oca(oca.name)\n ],\n call=[\n oca.name\n for oca in method.allowed_completion_types\n if method.create != ARC4CreateOption.require and allowed_call_oca(oca.name)\n ],\n )\n\n\ndef _encode_default_arg(default: MethodArgDefault | None) -> models.MethodArgDefaultValue | None:\n match default:\n case None:\n return None\n case MethodArgDefaultConstant(data=data, type_=type_string):\n return models.MethodArgDefaultValue(\n data=_encode_bytes(data),\n type=type_string,\n source=models.DefaultValueSource.literal,\n )\n case MethodArgDefaultFromState(key=key, kind=kind, key_type=key_type):\n match kind:\n case AppStorageKind.account_local:\n source = models.DefaultValueSource.local_\n case AppStorageKind.app_global:\n source = models.DefaultValueSource.global_\n case AppStorageKind.box:\n source = models.DefaultValueSource.box\n case unexpected:\n typing.assert_never(unexpected)\n return models.MethodArgDefaultValue(\n data=_encode_bytes(key), type=key_type, source=source\n )\n case MethodArgDefaultFromMethod(signature=signature):\n return models.MethodArgDefaultValue(\n data=signature,\n source=models.DefaultValueSource.method,\n )\n case unexpected:\n typing.assert_never(unexpected)\n\n\ndef _combine_actions(actions: Sequence[models.MethodActions]) -> models.MethodActions:\n return models.MethodActions(\n create=sorted(set(itertools.chain.from_iterable(a.create for a in actions))),\n call=sorted(set(itertools.chain.from_iterable(a.call for a in actions))),\n )\n\n\ndef allowed_create_oca(\n oca: str,\n) -> typing.TypeGuard[typing.Literal[\"NoOp\", \"OptIn\", \"DeleteApplication\"]]:\n return oca in (\"NoOp\", \"OptIn\", \"DeleteApplication\")\n\n\ndef allowed_call_oca(\n oca: str,\n) -> typing.TypeGuard[\n typing.Literal[\"NoOp\", \"OptIn\", \"CloseOut\", \"UpdateApplication\", \"DeleteApplication\"]\n]:\n return oca in (\"NoOp\", \"OptIn\", \"CloseOut\", \"UpdateApplication\", \"DeleteApplication\")\n\n\ndef _encode_str(value: str) -> str:\n return _encode_bytes(value.encode(\"utf8\"))\n\n\ndef _encode_bytes(value: bytes) -> str:\n return base64.b64encode(value).decode(\"utf-8\")\n\n\ndef _compiler_info() -> models.CompilerInfo:\n return models.CompilerInfo(\n compiler=\"puya\",\n compilerVersion=models.CompilerVersion(\n major=_ALGOPY_VERSION.major,\n minor=_ALGOPY_VERSION.minor,\n patch=_ALGOPY_VERSION.micro,\n commitHash=None,\n ),\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/arc56.py","language":"Python","license":"NOASSERTION","size":11621} {"code":"# ruff: noqa: N815\nimport enum\nimport typing\nfrom collections.abc import Mapping, Sequence\n\nimport attrs\n\nABIType = str\n\"\"\"An ABI-encoded type\"\"\"\nStructName = str\n\"\"\"The name of a defined struct\"\"\"\nProgramType = typing.Literal[\"approval\", \"clear\"]\n\n\nclass AVMType(enum.StrEnum):\n \"\"\"A native AVM type\"\"\"\n\n bytes = \"AVMBytes\"\n \"\"\"Raw byteslice without the length prefixed that is specified in ARC-4\"\"\"\n string = \"AVMString\"\n \"\"\"A utf-8 string without the length prefix that is specified in ARC-4\"\"\"\n uint64 = \"AVMUint64\"\n \"\"\"A 64-bit unsigned integer\"\"\"\n\n\n@attrs.frozen\nclass SourceInfo:\n pc: Sequence[int]\n \"\"\"The program counter value(s). Could be offset if pcOffsetMethod is not 'none'\"\"\"\n errorMessage: str\n \"\"\"A human-readable string that describes the error when the program fails at the given PC\"\"\"\n\n\n@attrs.frozen\nclass ProgramSourceInfo:\n sourceInfo: Sequence[SourceInfo]\n \"\"\"The source information for the program\"\"\"\n pcOffsetMethod: typing.Literal[\"none\", \"cblocks\"]\n \"\"\"\n How the program counter offset is calculated\n none: The pc values in sourceInfo are not offset\n cblocks: The pc values in sourceInfo are offset by the PC of the first op after the\n last cblock at the top of the program\n \"\"\"\n\n\n@attrs.frozen(kw_only=True)\nclass StorageKey:\n \"\"\"Describes a single key in app storage\"\"\"\n\n desc: str | None = None\n \"\"\"Description of what this storage key holds\"\"\"\n keyType: ABIType | AVMType | StructName\n \"\"\"The type of the key\"\"\"\n valueType: ABIType | AVMType | StructName\n \"\"\"The type of the value\"\"\"\n key: str\n \"\"\"The base64-encoded key\"\"\"\n\n\n@attrs.frozen(kw_only=True)\nclass StorageMap:\n \"\"\"Describes a mapping of key-value pairs in storage\"\"\"\n\n desc: str | None = None\n \"\"\"Description of what the key-value pairs in this mapping hold\"\"\"\n keyType: ABIType | AVMType | StructName\n \"\"\"The type of the keys in the map\"\"\"\n valueType: ABIType | AVMType | StructName\n \"\"\"The type of the values in the map\"\"\"\n prefix: str | None = None\n \"\"\"The base64-encoded prefix of the map keys\"\"\"\n\n\n@attrs.frozen\nclass StructField:\n \"\"\"Information about a single field in a struct\"\"\"\n\n name: str\n \"\"\"The name of the struct field\"\"\"\n type: ABIType | StructName | Sequence[\"StructField\"]\n \"\"\"The type of the struct field's value\"\"\"\n\n\n@attrs.frozen\nclass EventArg:\n type: ABIType\n \"\"\"\n The type of the argument.\n The `struct` field should also be checked to determine if this arg is a struct.\n \"\"\"\n name: str | None = None\n \"\"\"Optional, user-friendly name for the argument\"\"\"\n desc: str | None = None\n \"\"\"Optional, user-friendly description for the argument\"\"\"\n struct: StructName | None = None\n \"\"\"\n If the type is a struct, the name of the struct\n Note: this is a separate field to maintain backwards compatability with ARC-23\n \"\"\"\n\n\n@attrs.frozen(kw_only=True)\nclass Event:\n name: str\n \"\"\"The name of the event\"\"\"\n desc: str | None = None\n \"\"\"Optional, user-friendly description for the event\"\"\"\n args: Sequence[EventArg]\n \"\"\"The arguments of the event, in order\"\"\"\n\n\nclass DefaultValueSource(enum.Enum):\n box = \"box\"\n \"\"\"The data key signifies the box key to read the value from\"\"\"\n global_ = \"global\"\n \"\"\"The data key signifies the global state key to read the value from\"\"\"\n local_ = \"local\"\n \"\"\"The data key signifies the local state key to read the value from (for the sender)\"\"\"\n literal = \"literal\"\n \"\"\"the value is a literal and should be passed directly as the argument\"\"\"\n method = \"method\"\n \"\"\"\n The utf8 signature of the method in this contract to call to get the default value.\n If the method has arguments, they all must have default values.\n The method **MUST** be readonly so simulate can be used to get the default value.\n \"\"\"\n\n\n@attrs.frozen(kw_only=True)\nclass MethodArgDefaultValue:\n source: DefaultValueSource\n \"\"\"Where the default value is coming from\"\"\"\n type: ABIType | AVMType | None = None\n \"\"\"\n How the data is encoded.\n This is the encoding for the data provided here, not the arg type.\n Not relevant if source is method\n \"\"\"\n data: str\n \"\"\"Base64 encoded bytes, base64 ARC4 encoded uint64, or UTF-8 method selector\"\"\"\n\n\n@attrs.frozen(kw_only=True)\nclass MethodArg:\n type: ABIType\n \"\"\"\n The type of the argument.\n The `struct` field should also be checked to determine if this arg is a struct.\n \"\"\"\n struct: StructName | None = None\n \"\"\"\n If the type is a struct, the name of the struct.\n Note: this is a separate field to maintain backwards compatability with ARC-4\n \"\"\"\n name: str | None = None\n \"\"\"Optional, user-friendly name for the argument\"\"\"\n desc: str | None = None\n \"\"\"Optional, user-friendly description for the argument\"\"\"\n defaultValue: MethodArgDefaultValue | None = None\n\n\n@attrs.frozen(kw_only=True)\nclass MethodReturns:\n type: ABIType\n \"\"\"\n The type of the return value, or \"void\" to indicate no return value.\n The `struct` field should also be checked to determine if this return value is a struct.\n \"\"\"\n struct: StructName | None = None\n \"\"\"\n If the type is a struct, the name of the struct\n \"\"\"\n desc: str | None = None\n \"\"\"Optional, user-friendly description for the return value\"\"\"\n\n\n@attrs.frozen\nclass MethodActions:\n \"\"\"An action is a combination of call\/create and an OnComplete\"\"\"\n\n create: Sequence[typing.Literal[\"NoOp\", \"OptIn\", \"DeleteApplication\"]]\n \"\"\"OnCompletes this method allows when appID === 0\"\"\"\n call: Sequence[\n typing.Literal[\"NoOp\", \"OptIn\", \"CloseOut\", \"UpdateApplication\", \"DeleteApplication\"]\n ]\n \"\"\"OnCompletes this method allows when appID !== 0\"\"\"\n\n\n@attrs.frozen(kw_only=True)\nclass MethodBoxRecommendation:\n app: int | None = None\n \"\"\"The app ID for the box\"\"\"\n key: str\n \"\"\"The base64 encoded box key\"\"\"\n readBytes: int\n \"\"\"The number of bytes being read from the box\"\"\"\n writeBytes: int\n \"\"\"The number of bytes being written to the box\"\"\"\n\n\n@attrs.frozen(kw_only=True)\nclass MethodRecommendations:\n innerTransactionCount: int | None = None\n \"\"\"The number of inner transactions the caller should cover the fees for\"\"\"\n boxes: MethodBoxRecommendation | None = None\n \"\"\"Recommended box references to include\"\"\"\n accounts: Sequence[str] | None = None\n \"\"\"Recommended foreign accounts\"\"\"\n apps: Sequence[int] | None = None\n \"\"\"Recommended foreign apps\"\"\"\n assets: Sequence[int] | None = None\n \"\"\"Recommended foreign assets\"\"\"\n\n\n@attrs.frozen(kw_only=True)\nclass Method:\n \"\"\"\n Describes a method in the contract.\n This interface is an extension of the interface described in ARC-4\n \"\"\"\n\n name: str\n \"\"\"The name of the method\"\"\"\n desc: str | None = None\n \"\"\"Optional, user-friendly description for the method\"\"\"\n args: Sequence[MethodArg]\n \"\"\"The arguments of the method, in order\"\"\"\n returns: MethodReturns\n \"\"\"Information about the method's return value\"\"\"\n actions: MethodActions\n \"\"\"Allowed actions for this method\"\"\"\n readonly: bool\n \"\"\"If this method does not write anything to the ledger (ARC-22)\"\"\"\n events: Sequence[Event] = ()\n \"\"\"ARC-28 events that MAY be emitted by this method\"\"\"\n recommendations: MethodRecommendations | None = None\n \"\"\"Information that clients can use when calling the method\"\"\"\n\n\n@attrs.frozen\nclass Network:\n appID: int\n \"\"\"The app ID of the deployed contract in this network\"\"\"\n\n\nclass SchemaSizes(typing.TypedDict):\n ints: int\n bytes: int\n\n\nContractSchema = typing.TypedDict(\"ContractSchema\", {\"global\": SchemaSizes, \"local\": SchemaSizes})\nStorageMaps = Mapping[str, StorageMap]\nStorageKeys = Mapping[str, StorageKey]\nContractStorage = typing.TypedDict(\n \"ContractStorage\", {\"global\": StorageMaps, \"local\": StorageMaps, \"box\": StorageMaps}\n)\nContractKeys = typing.TypedDict(\n \"ContractKeys\", {\"global\": StorageKeys, \"local\": StorageKeys, \"box\": StorageKeys}\n)\n\n\n@attrs.frozen\nclass ContractState:\n schema: ContractSchema\n \"\"\"\n Defines the values that should be used for GlobalNumUint, GlobalNumByteSlice, LocalNumUint,\n and LocalNumByteSlice when creating the application\n \"\"\"\n keys: ContractKeys\n \"\"\"Mapping of human-readable names to StorageKey objects\"\"\"\n maps: ContractStorage\n \"\"\"Mapping of human-readable names to StorageMap objects\"\"\"\n\n\n@attrs.frozen(kw_only=True)\nclass CompilerVersion:\n major: int\n minor: int\n patch: int\n commitHash: str | None = None\n\n\n@attrs.frozen\nclass CompilerInfo:\n compiler: str\n \"\"\"The name of the compiler\"\"\"\n compilerVersion: CompilerVersion\n\n\n@attrs.frozen(kw_only=True)\nclass TemplateVariable:\n type: ABIType | AVMType | StructName\n \"\"\"The type of the template variable\"\"\"\n value: str | None = None\n \"\"\"If given, the the base64 encoded value used for the given app\/program\"\"\"\n\n\n@attrs.frozen\nclass ScratchVariable:\n slot: int\n type: ABIType | AVMType | StructName\n\n\n@attrs.frozen(kw_only=True)\nclass Contract:\n \"\"\"\n Describes the entire contract.\n This interface is an extension of the interface described in ARC-4\n \"\"\"\n\n arcs: Sequence[int] = ()\n \"\"\"\n The ARCs used and\/or supported by this contract.\n All contracts implicitly support ARC-4 and ARC-56\n \"\"\"\n name: str\n \"\"\"A user-friendly name for the contract\"\"\"\n desc: str | None = None\n \"\"\"Optional, user-friendly description for the interface\"\"\"\n networks: Mapping[str, Network] | None = None\n \"\"\"\n Optional object listing the contract instances across different networks.\n The key is the base64 genesis hash of the network, and the value contains\n information about the deployed contract in the network indicated by the\n key. A key containing the human-readable name of the network MAY be\n included, but the corresponding genesis hash key MUST also be define\n \"\"\"\n structs: Mapping[str, Sequence[StructField]]\n \"\"\"\n Named structs use by the application.\n Each struct field appears in the same order as ABI encoding\n \"\"\"\n methods: Sequence[Method]\n \"\"\"All of the methods that the contract implements\"\"\"\n state: ContractState | None = None\n bareActions: MethodActions | None = None\n \"\"\"Supported bare actions for the contract\"\"\"\n sourceInfo: Mapping[ProgramType, ProgramSourceInfo] | None = None\n \"\"\"Information about the TEAL programs\"\"\"\n source: Mapping[ProgramType, str] | None = None\n \"\"\"\n The pre-compiled TEAL that may contain template variables.\n MUST be omitted if included as part of ARC23\n \"\"\"\n byteCode: Mapping[ProgramType, str] | None = None\n \"\"\"\n The compiled bytecode for the application.\n MUST be omitted if included as part of ARC23\n \"\"\"\n compilerInfo: CompilerInfo | None = None\n \"\"\"\n Information used to get the given byteCode and\/or PC values in sourceInfo.\n MUST be given if byteCode or PC values are present\n \"\"\"\n events: Sequence[Event] | None = None\n \"\"\"ARC-28 events that MAY be emitted by this contract\"\"\"\n templateVariables: Mapping[str, TemplateVariable] | None = None\n \"\"\"\n A mapping of template variable names as they appear in the teal (not including TMPL_ prefix)\n to their respective types and values (if applicable)\n \"\"\"\n scratchVariables: Mapping[str, ScratchVariable] | None = None\n \"\"\"The scratch variables used during runtime\"\"\"\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/arc56_models.py","language":"Python","license":"NOASSERTION","size":11510} {"code":"import re\nimport typing\nfrom collections.abc import Sequence\n\nimport attrs\nfrom immutabledict import immutabledict\n\nfrom puya import avm\nfrom puya.avm import AVMType\nfrom puya.awst import nodes as awst_nodes\nfrom puya.parse import SourceLocation\nfrom puya.program_refs import ContractReference, LogicSigReference\n\n\n@attrs.frozen\nclass ARC4StructField:\n name: str\n type: str\n struct: str | None\n\n\n@attrs.frozen(kw_only=True)\nclass ARC4Struct:\n fullname: str\n desc: str | None = None\n fields: Sequence[ARC4StructField] = attrs.field(\n default=(), converter=tuple[ARC4StructField, ...]\n )\n\n @property\n def name(self) -> str:\n return re.split(r\"\\W\", self.fullname)[-1]\n\n\n@attrs.frozen(kw_only=True)\nclass MethodArgDefaultConstant:\n data: bytes\n type_: str\n\n\n@attrs.frozen(kw_only=True)\nclass MethodArgDefaultFromState:\n kind: awst_nodes.AppStorageKind\n key: bytes\n key_type: str\n\n\n@attrs.frozen(kw_only=True)\nclass MethodArgDefaultFromMethod:\n name: str\n return_type: str\n readonly: bool\n\n @property\n def signature(self) -> str:\n return f\"{self.name}(){self.return_type}\"\n\n\nMethodArgDefault = (\n MethodArgDefaultConstant | MethodArgDefaultFromState | MethodArgDefaultFromMethod\n)\n\n\n@attrs.frozen\nclass ARC4MethodArg:\n name: str\n type_: str\n struct: str | None\n desc: str | None = attrs.field(hash=False)\n client_default: MethodArgDefault | None\n\n\n@attrs.frozen\nclass ARC4Returns:\n type_: str\n struct: str | None\n desc: str | None = attrs.field(hash=False)\n\n\n@attrs.frozen(kw_only=True)\nclass ARC4ABIMethod:\n id: str\n desc: str | None = attrs.field(hash=False)\n args: Sequence[ARC4MethodArg] = attrs.field(converter=tuple[ARC4MethodArg, ...])\n returns: ARC4Returns\n events: Sequence[ARC4Struct] = attrs.field(converter=tuple[ARC4Struct, ...])\n _config: awst_nodes.ARC4ABIMethodConfig\n\n @property\n def name(self) -> str:\n return self._config.name\n\n @property\n def allowed_completion_types(self) -> Sequence[avm.OnCompletionAction]:\n return self._config.allowed_completion_types\n\n @property\n def create(self) -> awst_nodes.ARC4CreateOption:\n return self._config.create\n\n @property\n def readonly(self) -> bool:\n return self._config.readonly\n\n @property\n def config_location(self) -> SourceLocation:\n return self._config.source_location\n\n @property\n def signature(self) -> str:\n return f\"{self.name}({','.join(a.type_ for a in self.args)}){self.returns.type_}\"\n\n\n@attrs.frozen(kw_only=True)\nclass ARC4BareMethod:\n id: str\n desc: str | None = attrs.field(hash=False)\n _config: awst_nodes.ARC4BareMethodConfig\n\n @property\n def allowed_completion_types(self) -> Sequence[avm.OnCompletionAction]:\n return self._config.allowed_completion_types\n\n @property\n def create(self) -> awst_nodes.ARC4CreateOption:\n return self._config.create\n\n @property\n def config_location(self) -> SourceLocation:\n return self._config.source_location\n\n\nARC4Method = ARC4BareMethod | ARC4ABIMethod\n\n\n@attrs.define(eq=False)\nclass ContractState:\n name: str\n source_location: SourceLocation\n key_or_prefix: bytes\n \"\"\"Key value as bytes, or prefix if it is a map\"\"\"\n arc56_key_type: str\n arc56_value_type: str\n storage_type: typing.Literal[AVMType.uint64, AVMType.bytes]\n description: str | None\n is_map: bool\n \"\"\"State describes a map\"\"\"\n\n\n@attrs.frozen(kw_only=True)\nclass LogicSignatureMetaData:\n ref: LogicSigReference\n name: str\n description: str | None\n\n\n@attrs.frozen\nclass StateTotals:\n global_uints: int\n local_uints: int\n global_bytes: int\n local_bytes: int\n\n\n@attrs.frozen(kw_only=True)\nclass ContractMetaData:\n ref: ContractReference\n name: str\n description: str | None\n global_state: immutabledict[str, ContractState]\n local_state: immutabledict[str, ContractState]\n boxes: immutabledict[str, ContractState]\n state_totals: StateTotals\n arc4_methods: Sequence[ARC4Method]\n structs: immutabledict[str, ARC4Struct]\n template_variable_types: immutabledict[str, str]\n \"\"\"Mapping of template variable names to their ARC-56 type\"\"\"\n\n @property\n def is_arc4(self) -> bool:\n return bool(self.arc4_methods) # TODO: should this be an explicit flag instead?\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/artifact_metadata.py","language":"Python","license":"NOASSERTION","size":4366} {"code":"import graphlib\nimport typing\nfrom collections.abc import Iterable, Mapping, Sequence\n\nimport attrs\n\nfrom puya import log\nfrom puya.errors import CodeError\nfrom puya.ir.models import CompiledContractReference, CompiledLogicSigReference, ModuleArtifact\nfrom puya.ir.visitor import IRTraverser\nfrom puya.parse import SourceLocation\nfrom puya.program_refs import ContractReference, LogicSigReference\n\nlogger = log.get_logger(__name__)\n\n\n@attrs.frozen(eq=False)\nclass Artifact:\n ir: ModuleArtifact\n depends_on: dict[ContractReference | LogicSigReference, SourceLocation | None] = attrs.field(\n factory=dict\n )\n\n @typing.final\n @property\n def id(self) -> ContractReference | LogicSigReference:\n return self.ir.metadata.ref\n\n @typing.final\n @property\n def source_location(self) -> SourceLocation:\n return self.ir.source_location\n\n\n@attrs.define\nclass ArtifactCompilationSorter(IRTraverser):\n \"\"\"\n Sorts IR artifacts so that programs that depend on the byte code of other programs\n are processed after their dependencies\n \"\"\"\n\n artifacts: Mapping[ContractReference | LogicSigReference, Artifact]\n artifact: Artifact\n\n @classmethod\n def sort(\n cls,\n all_ir: Sequence[ModuleArtifact],\n ) -> Iterable[Artifact]:\n all_artifacts = {artifact.metadata.ref: Artifact(ir=artifact) for artifact in all_ir}\n artifacts = list(all_artifacts.values())\n for artifact in artifacts:\n reference_collector = cls(\n artifacts=all_artifacts,\n artifact=artifact,\n )\n for program in artifact.ir.all_programs():\n for subroutine in program.subroutines:\n reference_collector.visit_all_blocks(subroutine.body)\n sorter = graphlib.TopologicalSorter(\n {artifact: [all_artifacts[n] for n in artifact.depends_on] for artifact in artifacts}\n )\n try:\n result = list(sorter.static_order())\n except graphlib.CycleError as ex:\n artifact_cycle: Sequence[Artifact] = ex.args[1]\n *_, before, last = artifact_cycle\n cycle_loc = last.depends_on[before.id]\n programs = \" -> \".join(a.id for a in reversed(artifact_cycle))\n raise CodeError(f\"cyclical program reference: {programs}\", cycle_loc) from None\n return result\n\n def visit_compiled_contract_reference(self, const: CompiledContractReference) -> None:\n self._check_reference(const.artifact)\n # add unique references with source_location\n # will re-add a reference if current location is None\n if self.artifact.depends_on.get(const.artifact) is None:\n self.artifact.depends_on[const.artifact] = const.source_location\n\n def visit_compiled_logicsig_reference(self, const: CompiledLogicSigReference) -> None:\n self._check_reference(const.artifact)\n # add unique references with source_location\n # will re-add a reference if current location is None\n if self.artifact.depends_on.get(const.artifact) is None:\n self.artifact.depends_on[const.artifact] = const.source_location\n\n def _check_reference(self, ref: ContractReference | LogicSigReference) -> None:\n if ref not in self.artifacts:\n logger.critical(f\"missing reference: {ref}\")\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/artifact_sorter.py","language":"Python","license":"NOASSERTION","size":3355} {"code":"import enum\n\n\n@enum.unique\nclass AVMType(enum.Flag):\n bytes = enum.auto()\n uint64 = enum.auto()\n any = bytes | uint64\n\n\n# values and names are matched to AVM definitions\nclass OnCompletionAction(enum.IntEnum):\n NoOp = 0\n OptIn = 1\n CloseOut = 2\n ClearState = 3\n UpdateApplication = 4\n DeleteApplication = 5\n\n\nclass TransactionType(enum.IntEnum):\n pay = 1\n keyreg = 2\n acfg = 3\n axfer = 4\n afrz = 5\n appl = 6\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/avm.py","language":"Python","license":"NOASSERTION","size":453} {"code":"","repo_name":"algorandfoundation\/puya","path":"src\/puya\/awst\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"from immutabledict import immutabledict\n\nfrom puya.awst import wtypes\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\n\n\ndef wtype_to_arc4(wtype: wtypes.WType, loc: SourceLocation | None = None) -> str:\n match wtype:\n case wtypes.ARC4Type(arc4_name=arc4_name):\n return arc4_name\n case (\n wtypes.void_wtype\n | wtypes.asset_wtype\n | wtypes.account_wtype\n | wtypes.application_wtype\n ):\n return wtype.name\n case wtypes.WGroupTransaction(transaction_type=transaction_type):\n return transaction_type.name if transaction_type else \"txn\"\n converted = maybe_avm_to_arc4_equivalent_type(wtype)\n if converted is None:\n raise CodeError(f\"not an ARC4 type or native equivalent: {wtype}\", loc)\n return wtype_to_arc4(converted, loc)\n\n\ndef maybe_avm_to_arc4_equivalent_type(wtype: wtypes.WType) -> wtypes.ARC4Type | None:\n match wtype:\n case wtypes.bool_wtype:\n return wtypes.arc4_bool_wtype\n case wtypes.uint64_wtype:\n return wtypes.ARC4UIntN(n=64, source_location=None)\n case wtypes.biguint_wtype:\n return wtypes.ARC4UIntN(n=512, source_location=None)\n case wtypes.bytes_wtype:\n return wtypes.ARC4DynamicArray(\n element_type=wtypes.arc4_byte_alias, native_type=wtype, source_location=None\n )\n case wtypes.string_wtype:\n return wtypes.arc4_string_alias\n case wtypes.WTuple(types=tuple_item_types) as wtuple:\n arc4_item_types = []\n for t in tuple_item_types:\n if isinstance(t, wtypes.ARC4Type):\n arc4_item_types.append(t)\n else:\n converted = maybe_avm_to_arc4_equivalent_type(t)\n if converted is None:\n return None\n arc4_item_types.append(converted)\n if wtuple.fields:\n return wtypes.ARC4Struct(\n name=wtuple.name,\n desc=wtuple.desc,\n frozen=True,\n fields=immutabledict(zip(wtuple.fields, arc4_item_types, strict=True)),\n )\n else:\n return wtypes.ARC4Tuple(types=arc4_item_types, source_location=None)\n case _:\n return None\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/awst\/arc4_types.py","language":"Python","license":"NOASSERTION","size":2393} {"code":"import typing\n\nfrom puya.awst import nodes as awst_nodes\nfrom puya.awst.function_traverser import FunctionTraverser\nfrom puya.awst.visitors import ContractMemberVisitor, RootNodeVisitor\n\n\nclass AWSTTraverser(FunctionTraverser, RootNodeVisitor[None], ContractMemberVisitor[None]):\n @typing.override\n def visit_subroutine(self, statement: awst_nodes.Subroutine) -> None:\n statement.body.accept(self)\n\n @typing.override\n def visit_contract(self, statement: awst_nodes.Contract) -> None:\n for storage in statement.app_state:\n storage.accept(self)\n for method in statement.all_methods:\n method.accept(self)\n\n @typing.override\n def visit_logic_signature(self, statement: awst_nodes.LogicSignature) -> None:\n statement.program.accept(self)\n\n @typing.override\n def visit_app_storage_definition(self, defn: awst_nodes.AppStorageDefinition) -> None:\n defn.key.accept(self)\n\n @typing.override\n def visit_contract_method(self, statement: awst_nodes.ContractMethod) -> None:\n statement.body.accept(self)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/awst\/awst_traverser.py","language":"Python","license":"NOASSERTION","size":1085} {"code":"import typing\n\nimport puya.awst.visitors\nfrom puya.awst import nodes as awst_nodes\n\n\nclass FunctionTraverser(\n puya.awst.visitors.ExpressionVisitor[None],\n puya.awst.visitors.StatementVisitor[None],\n):\n @typing.override\n def visit_assignment_statement(self, statement: awst_nodes.AssignmentStatement) -> None:\n statement.target.accept(self)\n statement.value.accept(self)\n\n @typing.override\n def visit_copy(self, expr: awst_nodes.Copy) -> None:\n expr.value.accept(self)\n\n @typing.override\n def visit_goto(self, statement: awst_nodes.Goto) -> None:\n pass\n\n @typing.override\n def visit_assignment_expression(self, expr: awst_nodes.AssignmentExpression) -> None:\n expr.target.accept(self)\n expr.value.accept(self)\n\n @typing.override\n def visit_uint64_binary_operation(self, expr: awst_nodes.UInt64BinaryOperation) -> None:\n expr.left.accept(self)\n expr.right.accept(self)\n\n @typing.override\n def visit_biguint_binary_operation(self, expr: awst_nodes.BigUIntBinaryOperation) -> None:\n expr.left.accept(self)\n expr.right.accept(self)\n\n @typing.override\n def visit_reversed(self, expr: awst_nodes.Reversed) -> None:\n if isinstance(expr.expr, awst_nodes.Expression):\n expr.expr.accept(self)\n\n @typing.override\n def visit_integer_constant(self, expr: awst_nodes.IntegerConstant) -> None:\n pass\n\n @typing.override\n def visit_decimal_constant(self, expr: awst_nodes.DecimalConstant) -> None:\n pass\n\n @typing.override\n def visit_bool_constant(self, expr: awst_nodes.BoolConstant) -> None:\n pass\n\n @typing.override\n def visit_bytes_constant(self, expr: awst_nodes.BytesConstant) -> None:\n pass\n\n @typing.override\n def visit_string_constant(self, expr: awst_nodes.StringConstant) -> None:\n pass\n\n @typing.override\n def visit_void_constant(self, expr: awst_nodes.VoidConstant) -> None:\n pass\n\n @typing.override\n def visit_compiled_contract(self, expr: awst_nodes.CompiledContract) -> None:\n for value in expr.template_variables.values():\n value.accept(self)\n\n @typing.override\n def visit_compiled_logicsig(self, expr: awst_nodes.CompiledLogicSig) -> None:\n for value in expr.template_variables.values():\n value.accept(self)\n\n @typing.override\n def visit_arc4_decode(self, expr: awst_nodes.ARC4Decode) -> None:\n expr.value.accept(self)\n\n @typing.override\n def visit_arc4_encode(self, expr: awst_nodes.ARC4Encode) -> None:\n expr.value.accept(self)\n\n @typing.override\n def visit_array_concat(self, expr: awst_nodes.ArrayConcat) -> None:\n expr.left.accept(self)\n expr.right.accept(self)\n\n @typing.override\n def visit_array_pop(self, expr: awst_nodes.ArrayPop) -> None:\n expr.base.accept(self)\n\n @typing.override\n def visit_array_extend(self, expr: awst_nodes.ArrayExtend) -> None:\n expr.base.accept(self)\n expr.other.accept(self)\n\n @typing.override\n def visit_method_constant(self, expr: awst_nodes.MethodConstant) -> None:\n pass\n\n @typing.override\n def visit_address_constant(self, expr: awst_nodes.AddressConstant) -> None:\n pass\n\n @typing.override\n def visit_numeric_comparison_expression(\n self, expr: awst_nodes.NumericComparisonExpression\n ) -> None:\n expr.lhs.accept(self)\n expr.rhs.accept(self)\n\n @typing.override\n def visit_var_expression(self, expr: awst_nodes.VarExpression) -> None:\n pass\n\n @typing.override\n def visit_assert_expression(self, expr: awst_nodes.AssertExpression) -> None:\n if expr.condition is not None:\n expr.condition.accept(self)\n\n @typing.override\n def visit_checked_maybe(self, expr: awst_nodes.CheckedMaybe) -> None:\n expr.expr.accept(self)\n\n @typing.override\n def visit_intrinsic_call(self, call: awst_nodes.IntrinsicCall) -> None:\n for arg in call.stack_args:\n arg.accept(self)\n\n @typing.override\n def visit_puya_lib_call(self, call: awst_nodes.PuyaLibCall) -> None:\n for arg in call.args:\n arg.value.accept(self)\n\n @typing.override\n def visit_group_transaction_reference(self, ref: awst_nodes.GroupTransactionReference) -> None:\n ref.index.accept(self)\n\n @typing.override\n def visit_create_inner_transaction(self, call: awst_nodes.CreateInnerTransaction) -> None:\n for expr in call.fields.values():\n expr.accept(self)\n\n @typing.override\n def visit_update_inner_transaction(self, call: awst_nodes.UpdateInnerTransaction) -> None:\n call.itxn.accept(self)\n for value in call.fields.values():\n value.accept(self)\n\n @typing.override\n def visit_submit_inner_transaction(self, call: awst_nodes.SubmitInnerTransaction) -> None:\n for expr in call.itxns:\n expr.accept(self)\n\n @typing.override\n def visit_inner_transaction_field(self, itxn_field: awst_nodes.InnerTransactionField) -> None:\n itxn_field.itxn.accept(self)\n if itxn_field.array_index:\n itxn_field.array_index.accept(self)\n\n @typing.override\n def visit_tuple_expression(self, expr: awst_nodes.TupleExpression) -> None:\n for item in expr.items:\n item.accept(self)\n\n @typing.override\n def visit_tuple_item_expression(self, expr: awst_nodes.TupleItemExpression) -> None:\n expr.base.accept(self)\n\n @typing.override\n def visit_field_expression(self, expr: awst_nodes.FieldExpression) -> None:\n expr.base.accept(self)\n\n @typing.override\n def visit_slice_expression(self, expr: awst_nodes.SliceExpression) -> None:\n expr.base.accept(self)\n if isinstance(expr.begin_index, awst_nodes.Expression):\n expr.begin_index.accept(self)\n if isinstance(expr.end_index, awst_nodes.Expression):\n expr.end_index.accept(self)\n\n @typing.override\n def visit_intersection_slice_expression(\n self, expr: awst_nodes.IntersectionSliceExpression\n ) -> None:\n expr.base.accept(self)\n if isinstance(expr.begin_index, awst_nodes.Expression):\n expr.begin_index.accept(self)\n if isinstance(expr.end_index, awst_nodes.Expression):\n expr.end_index.accept(self)\n\n @typing.override\n def visit_index_expression(self, expr: awst_nodes.IndexExpression) -> None:\n expr.base.accept(self)\n expr.index.accept(self)\n\n @typing.override\n def visit_conditional_expression(self, expr: awst_nodes.ConditionalExpression) -> None:\n expr.condition.accept(self)\n expr.true_expr.accept(self)\n expr.false_expr.accept(self)\n\n @typing.override\n def visit_single_evaluation(self, expr: awst_nodes.SingleEvaluation) -> None:\n expr.source.accept(self)\n\n @typing.override\n def visit_app_state_expression(self, expr: awst_nodes.AppStateExpression) -> None:\n expr.key.accept(self)\n\n @typing.override\n def visit_app_account_state_expression(\n self, expr: awst_nodes.AppAccountStateExpression\n ) -> None:\n expr.key.accept(self)\n expr.account.accept(self)\n\n @typing.override\n def visit_new_array(self, expr: awst_nodes.NewArray) -> None:\n for element in expr.values:\n element.accept(self)\n\n @typing.override\n def visit_new_struct(self, expr: awst_nodes.NewStruct) -> None:\n for element in expr.values.values():\n element.accept(self)\n\n @typing.override\n def visit_bytes_comparison_expression(\n self, expr: awst_nodes.BytesComparisonExpression\n ) -> None:\n expr.lhs.accept(self)\n expr.rhs.accept(self)\n\n @typing.override\n def visit_subroutine_call_expression(self, expr: awst_nodes.SubroutineCallExpression) -> None:\n for arg in expr.args:\n arg.value.accept(self)\n\n @typing.override\n def visit_bytes_binary_operation(self, expr: awst_nodes.BytesBinaryOperation) -> None:\n expr.left.accept(self)\n expr.right.accept(self)\n\n @typing.override\n def visit_boolean_binary_operation(self, expr: awst_nodes.BooleanBinaryOperation) -> None:\n expr.left.accept(self)\n expr.right.accept(self)\n\n @typing.override\n def visit_uint64_unary_operation(self, expr: awst_nodes.UInt64UnaryOperation) -> None:\n expr.expr.accept(self)\n\n @typing.override\n def visit_bytes_unary_operation(self, expr: awst_nodes.BytesUnaryOperation) -> None:\n expr.expr.accept(self)\n\n @typing.override\n def visit_not_expression(self, expr: awst_nodes.Not) -> None:\n expr.expr.accept(self)\n\n @typing.override\n def visit_block(self, statement: awst_nodes.Block) -> None:\n for stmt in statement.body:\n stmt.accept(self)\n\n @typing.override\n def visit_if_else(self, statement: awst_nodes.IfElse) -> None:\n statement.condition.accept(self)\n statement.if_branch.accept(self)\n if statement.else_branch:\n statement.else_branch.accept(self)\n\n @typing.override\n def visit_switch(self, statement: awst_nodes.Switch) -> None:\n statement.value.accept(self)\n for case, block in statement.cases.items():\n case.accept(self)\n block.accept(self)\n if statement.default_case:\n statement.default_case.accept(self)\n\n @typing.override\n def visit_while_loop(self, statement: awst_nodes.WhileLoop) -> None:\n statement.condition.accept(self)\n statement.loop_body.accept(self)\n\n @typing.override\n def visit_loop_exit(self, statement: awst_nodes.LoopExit) -> None:\n pass\n\n @typing.override\n def visit_return_statement(self, statement: awst_nodes.ReturnStatement) -> None:\n if statement.value is not None:\n statement.value.accept(self)\n\n @typing.override\n def visit_loop_continue(self, statement: awst_nodes.LoopContinue) -> None:\n pass\n\n @typing.override\n def visit_expression_statement(self, statement: awst_nodes.ExpressionStatement) -> None:\n statement.expr.accept(self)\n\n @typing.override\n def visit_template_var(self, statement: awst_nodes.TemplateVar) -> None:\n pass\n\n @typing.override\n def visit_uint64_augmented_assignment(\n self, statement: awst_nodes.UInt64AugmentedAssignment\n ) -> None:\n statement.target.accept(self)\n statement.value.accept(self)\n\n @typing.override\n def visit_biguint_augmented_assignment(\n self, statement: awst_nodes.BigUIntAugmentedAssignment\n ) -> None:\n statement.target.accept(self)\n statement.value.accept(self)\n\n @typing.override\n def visit_bytes_augmented_assignment(\n self, statement: awst_nodes.BytesAugmentedAssignment\n ) -> None:\n statement.target.accept(self)\n statement.value.accept(self)\n\n @typing.override\n def visit_for_in_loop(self, statement: awst_nodes.ForInLoop) -> None:\n statement.sequence.accept(self)\n statement.items.accept(self)\n statement.loop_body.accept(self)\n\n @typing.override\n def visit_reinterpret_cast(self, expr: awst_nodes.ReinterpretCast) -> None:\n expr.expr.accept(self)\n\n @typing.override\n def visit_enumeration(self, expr: awst_nodes.Enumeration) -> None:\n expr.expr.accept(self)\n\n @typing.override\n def visit_state_get_ex(self, expr: awst_nodes.StateGetEx) -> None:\n expr.field.accept(self)\n\n @typing.override\n def visit_state_delete(self, statement: awst_nodes.StateDelete) -> None:\n statement.field.accept(self)\n\n @typing.override\n def visit_state_get(self, expr: awst_nodes.StateGet) -> None:\n expr.field.accept(self)\n expr.default.accept(self)\n\n @typing.override\n def visit_state_exists(self, expr: awst_nodes.StateExists) -> None:\n expr.field.accept(self)\n\n @typing.override\n def visit_box_value_expression(self, expr: awst_nodes.BoxValueExpression) -> None:\n expr.key.accept(self)\n\n @typing.override\n def visit_biguint_postfix_unary_operation(\n self, expr: awst_nodes.BigUIntPostfixUnaryOperation\n ) -> None:\n expr.target.accept(self)\n\n @typing.override\n def visit_uint64_postfix_unary_operation(\n self, expr: awst_nodes.UInt64PostfixUnaryOperation\n ) -> None:\n expr.target.accept(self)\n\n @typing.override\n def visit_arc4_router(self, expr: awst_nodes.ARC4Router) -> None:\n pass\n\n @typing.override\n def visit_range(self, node: awst_nodes.Range) -> None:\n node.start.accept(self)\n node.stop.accept(self)\n node.step.accept(self)\n\n @typing.override\n def visit_emit(self, expr: awst_nodes.Emit) -> None:\n expr.value.accept(self)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/awst\/function_traverser.py","language":"Python","license":"NOASSERTION","size":12822} {"code":"import abc\nimport decimal\nimport enum\nimport typing\nfrom abc import ABC, abstractmethod\nfrom collections.abc import Iterator, Mapping, Sequence, Set\nfrom functools import cached_property\n\nimport attrs\nfrom immutabledict import immutabledict\n\nfrom puya.algo_constants import SUPPORTED_AVM_VERSIONS\nfrom puya.avm import AVMType, OnCompletionAction\nfrom puya.awst import wtypes\nfrom puya.awst.txn_fields import TxnField\nfrom puya.awst.visitors import (\n ContractMemberVisitor,\n ExpressionVisitor,\n RootNodeVisitor,\n StatementVisitor,\n)\nfrom puya.awst.wtypes import WType\nfrom puya.errors import CodeError, InternalError\nfrom puya.parse import SourceLocation\nfrom puya.program_refs import ContractReference, LogicSigReference\nfrom puya.utils import unique\n\nT = typing.TypeVar(\"T\")\n\n\n@attrs.frozen\nclass Node:\n source_location: SourceLocation\n\n\n@attrs.frozen\nclass Statement(Node, ABC):\n @abstractmethod\n def accept(self, visitor: StatementVisitor[T]) -> T: ...\n\n\n@attrs.frozen\nclass Expression(Node, ABC):\n wtype: WType\n\n @abstractmethod\n def accept(self, visitor: ExpressionVisitor[T]) -> T: ...\n\n\n@attrs.frozen\nclass ExpressionStatement(Statement):\n expr: Expression\n source_location: SourceLocation = attrs.field(init=False)\n\n @source_location.default\n def _source_location(self) -> SourceLocation:\n return self.expr.source_location\n\n def accept(self, visitor: StatementVisitor[T]) -> T:\n return visitor.visit_expression_statement(self)\n\n\n@attrs.frozen(repr=False)\nclass _ExpressionHasWType:\n instances: tuple[WType, ...]\n types: tuple[type[WType], ...]\n\n def __call__(\n self,\n inst: Node,\n attr: attrs.Attribute, # type: ignore[type-arg]\n value: Expression,\n ) -> None:\n \"\"\"\n We use a callable class to be able to change the ``__repr__``.\n \"\"\"\n wtype = value.wtype\n if wtype in self.instances:\n return\n for allowed_t in self.types:\n if isinstance(wtype, allowed_t):\n return\n raise InternalError(\n f\"{type(inst).__name__}.{attr.name}: expression of WType {wtype} received,\"\n f\" expected {' or '.join(self._names)}\"\n )\n\n def __repr__(self) -> str:\n return f\"\"\n\n @property\n def _names(self) -> Iterator[str]:\n for inst in self.instances:\n yield inst.name\n for typ in self.types:\n yield typ.__name__\n\n\ndef expression_has_wtype(*one_of_these: WType | type[WType]) -> _ExpressionHasWType:\n instances = []\n types = list[type[WType]]()\n for item in one_of_these:\n if isinstance(item, type):\n types.append(item)\n else:\n instances.append(item)\n return _ExpressionHasWType(instances=tuple(instances), types=tuple(types))\n\n\n@attrs.frozen(repr=False)\nclass _WTypeIsOneOf:\n instances: tuple[WType, ...]\n types: tuple[type[WType], ...]\n\n def __call__(\n self,\n inst: Node,\n attr: attrs.Attribute, # type: ignore[type-arg]\n value: WType,\n ) -> None:\n \"\"\"\n We use a callable class to be able to change the ``__repr__``.\n \"\"\"\n wtype = value\n if wtype in self.instances:\n return\n for allowed_t in self.types:\n if isinstance(wtype, allowed_t):\n return\n raise InternalError(\n f\"{type(inst).__name__}.{attr.name}: set to {wtype},\"\n f\" expected {' or '.join(self._names)}\"\n )\n\n def __repr__(self) -> str:\n return f\"\"\n\n @property\n def _names(self) -> Iterator[str]:\n for inst in self.instances:\n yield inst.name\n for typ in self.types:\n yield typ.__name__\n\n\ndef wtype_is_one_of(*one_of_these: WType | type[WType]) -> _WTypeIsOneOf:\n instances = []\n types = list[type[WType]]()\n for item in one_of_these:\n if isinstance(item, type):\n types.append(item)\n else:\n instances.append(item)\n return _WTypeIsOneOf(instances=tuple(instances), types=tuple(types))\n\n\nwtype_is_uint64 = expression_has_wtype(wtypes.uint64_wtype)\nwtype_is_biguint = expression_has_wtype(wtypes.biguint_wtype)\nwtype_is_bool = expression_has_wtype(wtypes.bool_wtype)\nwtype_is_bytes = expression_has_wtype(wtypes.bytes_wtype)\n\nLabel = typing.NewType(\"Label\", str)\n\n\n@attrs.frozen(kw_only=True)\nclass Block(Statement):\n \"\"\"\n A (non-basic) block used to group statements. Can contain nested blocks, loops, and branching\n structures. No lexical scoping is offered or implied by this block.\n\n body: A sequence of statements which represent this block\n comment: An optional comment of what this block represents. Only influences\n non-functional output\n label: An optional label for this block allowing goto statements to jump to this block.\n Must be unique per subroutine.\n \"\"\"\n\n body: Sequence[Statement] = attrs.field(converter=tuple[Statement, ...])\n label: Label | None = None\n comment: str | None = None\n\n def accept(self, visitor: StatementVisitor[T]) -> T:\n return visitor.visit_block(self)\n\n\n@attrs.frozen(kw_only=True)\nclass Goto(Statement):\n \"\"\"\n Branch unconditionally to the block with the specified label.\n\n target: The label of a block within the same subroutine\n \"\"\"\n\n target: Label\n\n def accept(self, visitor: StatementVisitor[T]) -> T:\n return visitor.visit_goto(self)\n\n\n@attrs.frozen\nclass IfElse(Statement):\n condition: Expression = attrs.field(validator=[wtype_is_bool])\n if_branch: Block\n else_branch: Block | None\n\n def accept(self, visitor: StatementVisitor[T]) -> T:\n return visitor.visit_if_else(self)\n\n\n@attrs.frozen\nclass Switch(Statement):\n value: Expression\n cases: Mapping[Expression, Block] = attrs.field(converter=immutabledict)\n default_case: Block | None\n\n def accept(self, visitor: StatementVisitor[T]) -> T:\n return visitor.visit_switch(self)\n\n\n@attrs.frozen\nclass WhileLoop(Statement):\n condition: Expression = attrs.field(validator=[wtype_is_bool])\n loop_body: Block\n\n def accept(self, visitor: StatementVisitor[T]) -> T:\n return visitor.visit_while_loop(self)\n\n\n@attrs.frozen\nclass LoopExit(Statement):\n \"\"\"break out of the current innermost loop\"\"\"\n\n def accept(self, visitor: StatementVisitor[T]) -> T:\n return visitor.visit_loop_exit(self)\n\n\n@attrs.frozen\nclass LoopContinue(Statement):\n \"\"\"continue with the next iteration of the current innermost loop\"\"\"\n\n def accept(self, visitor: StatementVisitor[T]) -> T:\n return visitor.visit_loop_continue(self)\n\n\n@attrs.frozen\nclass ReturnStatement(Statement):\n value: Expression | None\n\n def accept(self, visitor: StatementVisitor[T]) -> T:\n return visitor.visit_return_statement(self)\n\n\n@attrs.frozen\nclass AssertExpression(Expression):\n condition: Expression | None\n error_message: str | None\n wtype: WType = attrs.field(default=wtypes.void_wtype, init=False)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_assert_expression(self)\n\n\n@attrs.frozen(kw_only=True)\nclass IntegerConstant(Expression):\n wtype: WType = attrs.field(\n validator=[\n wtype_is_one_of(\n wtypes.uint64_wtype,\n wtypes.biguint_wtype,\n wtypes.ARC4UIntN,\n )\n ]\n )\n value: int = attrs.field()\n teal_alias: str | None = None\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_integer_constant(self)\n\n\n@attrs.frozen\nclass DecimalConstant(Expression):\n wtype: wtypes.ARC4UFixedNxM\n value: decimal.Decimal = attrs.field()\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_decimal_constant(self)\n\n\ndef UInt64Constant( # noqa: N802\n *, source_location: SourceLocation, value: int, teal_alias: str | None = None\n) -> IntegerConstant:\n return IntegerConstant(\n source_location=source_location,\n value=value,\n wtype=wtypes.uint64_wtype,\n teal_alias=teal_alias,\n )\n\n\ndef BigUIntConstant( # noqa: N802\n *, source_location: SourceLocation, value: int\n) -> IntegerConstant:\n return IntegerConstant(\n source_location=source_location,\n value=value,\n wtype=wtypes.biguint_wtype,\n )\n\n\n@attrs.frozen\nclass BoolConstant(Expression):\n value: bool\n wtype: WType = attrs.field(\n default=wtypes.bool_wtype,\n validator=wtype_is_one_of(wtypes.bool_wtype, wtypes.arc4_bool_wtype),\n )\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_bool_constant(self)\n\n\n@enum.unique\nclass BytesEncoding(enum.StrEnum):\n unknown = enum.auto()\n base16 = enum.auto()\n base32 = enum.auto()\n base64 = enum.auto()\n utf8 = enum.auto()\n\n\n@attrs.frozen(repr=False)\nclass _WTypeIsBackedBy:\n backed_by: typing.Literal[AVMType.uint64, AVMType.bytes]\n\n def __call__(\n self,\n inst: Node,\n attr: attrs.Attribute, # type: ignore[type-arg]\n value: WType,\n ) -> None:\n \"\"\"\n We use a callable class to be able to change the ``__repr__``.\n \"\"\"\n if not isinstance(inst, Node):\n raise InternalError(f\"{self!r} used on type {type(inst).__name__}, expected Node\")\n if value.scalar_type != self.backed_by:\n raise InternalError(\n f\"{type(inst).__name__}.{attr.name}: set to {value},\"\n f\" which is not backed by {value.scalar_type}, not {self.backed_by.name}\"\n )\n\n def __repr__(self) -> str:\n return f\"\"\n\n\nwtype_is_bytes_backed: typing.Final = _WTypeIsBackedBy(backed_by=AVMType.bytes)\nwtype_is_uint64_backed: typing.Final = _WTypeIsBackedBy(backed_by=AVMType.uint64)\n\n\n@attrs.frozen(kw_only=True)\nclass BytesConstant(Expression):\n wtype: WType = attrs.field(default=wtypes.bytes_wtype, validator=wtype_is_bytes_backed)\n value: bytes = attrs.field()\n encoding: BytesEncoding = attrs.field()\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_bytes_constant(self)\n\n\n@attrs.frozen\nclass StringConstant(Expression):\n value: str = attrs.field()\n wtype: WType = attrs.field(\n default=wtypes.string_wtype,\n validator=[\n wtype_is_one_of(\n wtypes.string_wtype,\n wtypes.arc4_string_alias,\n )\n ],\n )\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_string_constant(self)\n\n\n@attrs.frozen\nclass VoidConstant(Expression):\n # useful as a \"no-op\"\n wtype: WType = attrs.field(default=wtypes.void_wtype, init=False)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_void_constant(self)\n\n\n@attrs.frozen\nclass TemplateVar(Expression):\n wtype: WType\n name: str\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_template_var(self)\n\n\n@attrs.frozen\nclass MethodConstant(Expression):\n wtype: WType = attrs.field(default=wtypes.bytes_wtype, init=False)\n value: str\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_method_constant(self)\n\n\n@attrs.frozen(kw_only=True)\nclass AddressConstant(Expression):\n wtype: WType = attrs.field(\n default=wtypes.account_wtype,\n validator=wtype_is_one_of(wtypes.account_wtype, wtypes.arc4_address_alias),\n )\n value: str\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_address_constant(self)\n\n\n@attrs.frozen\nclass ARC4Encode(Expression):\n value: Expression\n wtype: wtypes.ARC4Type = attrs.field()\n\n @wtype.validator\n def _wtype_validator(self, _attribute: object, wtype: wtypes.ARC4Type) -> None:\n if not wtype.can_encode_type(self.value.wtype):\n raise InternalError(\n f\"cannot ARC4 encode {self.value.wtype} to {wtype}\", self.source_location\n )\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_arc4_encode(self)\n\n\n@attrs.frozen\nclass Copy(Expression):\n \"\"\"\n Create a new copy of 'value'\n \"\"\"\n\n value: Expression\n wtype: WType = attrs.field(init=False)\n\n @wtype.default\n def _wtype(self) -> WType:\n return self.value.wtype\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_copy(self)\n\n\n@attrs.frozen\nclass ArrayConcat(Expression):\n \"\"\"\n Given 'left' or 'right' that is logically an array - concat it with the other value which is\n an iterable type with the same element type\n \"\"\"\n\n left: Expression\n right: Expression\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_array_concat(self)\n\n\n@attrs.frozen\nclass ArrayPop(Expression):\n base: Expression\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_array_pop(self)\n\n\n@attrs.frozen\nclass ArrayExtend(Expression):\n \"\"\"\n Given 'base' that is logically an array - extend it with 'other' which is an iterable type with\n the same element type\n \"\"\"\n\n base: Expression\n other: Expression\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_array_extend(self)\n\n\n@attrs.frozen\nclass ARC4Decode(Expression):\n value: Expression = attrs.field(\n validator=expression_has_wtype(\n wtypes.arc4_bool_wtype,\n wtypes.ARC4UIntN,\n wtypes.ARC4Tuple,\n wtypes.ARC4Struct,\n wtypes.ARC4DynamicArray, # only if element type is bytes for now\n )\n )\n\n @value.validator\n def _value_wtype_validator(self, _attribute: object, value: Expression) -> None:\n assert isinstance(value.wtype, wtypes.ARC4Type) # validated by `value`\n if not value.wtype.can_encode_type(self.wtype):\n raise InternalError(\n f\"ARC4Decode from {value.wtype} should have non ARC4 target type {self.wtype}\",\n self.source_location,\n )\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_arc4_decode(self)\n\n\nCompileTimeConstantExpression: typing.TypeAlias = (\n IntegerConstant\n | DecimalConstant\n | BoolConstant\n | BytesConstant\n | AddressConstant\n | MethodConstant\n)\n\n\n@attrs.define\nclass IntrinsicCall(Expression):\n op_code: str\n immediates: Sequence[str | int] = attrs.field(default=(), converter=tuple[str | int, ...])\n stack_args: Sequence[Expression] = attrs.field(default=(), converter=tuple[Expression, ...])\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_intrinsic_call(self)\n\n\n@attrs.define\nclass CreateInnerTransaction(Expression):\n wtype: wtypes.WInnerTransactionFields\n fields: Mapping[TxnField, Expression] = attrs.field(converter=immutabledict)\n\n @fields.validator\n def _validate_fields(self, _attribute: object, fields: Mapping[TxnField, Expression]) -> None:\n for field, value in fields.items():\n if not field.valid_argument_type(value.wtype):\n raise CodeError(\"invalid type for field\", value.source_location)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_create_inner_transaction(self)\n\n\n@attrs.define\nclass UpdateInnerTransaction(Expression):\n itxn: Expression = attrs.field(validator=expression_has_wtype(wtypes.WInnerTransactionFields))\n fields: Mapping[TxnField, Expression] = attrs.field(converter=immutabledict)\n wtype: WType = attrs.field(default=wtypes.void_wtype, init=False)\n\n @fields.validator\n def _validate_fields(self, _attribute: object, fields: Mapping[TxnField, Expression]) -> None:\n for field, value in fields.items():\n if not field.valid_argument_type(value.wtype):\n raise CodeError(\"invalid type for field\", value.source_location)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_update_inner_transaction(self)\n\n\n@attrs.frozen\nclass GroupTransactionReference(Expression):\n index: Expression = attrs.field(validator=wtype_is_uint64)\n wtype: wtypes.WGroupTransaction\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_group_transaction_reference(self)\n\n\n@attrs.define\nclass CheckedMaybe(Expression):\n \"\"\"Allows evaluating a maybe type i.e. tuple[_T, bool] as _T, but with the assertion that\n the 2nd bool element is true\"\"\"\n\n expr: Expression\n comment: str\n wtype: wtypes.WType = attrs.field(init=False)\n source_location: SourceLocation = attrs.field(init=False)\n\n @source_location.default\n def _source_location(self) -> SourceLocation:\n return self.expr.source_location\n\n @wtype.default\n def _wtype(self) -> wtypes.WType:\n match self.expr.wtype:\n case wtypes.WTuple(types=(wtype, wtypes.bool_wtype)):\n return wtype\n case _:\n raise InternalError(\n f\"{type(self).__name__}.expr: expression of WType {self.expr.wtype} received,\"\n f\" expected tuple[_T, bool]\"\n )\n\n @classmethod\n def from_tuple_items(\n cls,\n expr: Expression,\n check: Expression,\n source_location: SourceLocation,\n comment: str,\n ) -> typing.Self:\n if check.wtype != wtypes.bool_wtype:\n raise InternalError(\n \"Check condition for CheckedMaybe should be a boolean\", source_location\n )\n tuple_expr = TupleExpression.from_items((expr, check), source_location)\n return cls(expr=tuple_expr, comment=comment)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_checked_maybe(self)\n\n\n@attrs.frozen\nclass TupleExpression(Expression):\n items: Sequence[Expression] = attrs.field(converter=tuple[Expression, ...])\n wtype: wtypes.WTuple = attrs.field()\n\n @classmethod\n def from_items(cls, items: Sequence[Expression], location: SourceLocation) -> typing.Self:\n return cls(\n items=items,\n wtype=wtypes.WTuple((i.wtype for i in items), location),\n source_location=location,\n )\n\n @wtype.validator\n def _wtype_validator(self, _attribute: object, wtype: wtypes.WTuple) -> None:\n if tuple(it.wtype for it in self.items) != wtype.types:\n raise CodeError(\"Tuple type mismatch\", self.source_location)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_tuple_expression(self)\n\n\n@attrs.frozen\nclass TupleItemExpression(Expression):\n \"\"\"Represents tuple element access.\n\n Note: this is its own item (vs IndexExpression) for two reasons:\n 1. It's not a valid lvalue (tuples are immutable)\n 2. The index must always be a literal, and can be negative\n \"\"\"\n\n base: Expression\n index: int\n wtype: wtypes.WType = attrs.field(init=False)\n\n @wtype.default\n def _wtype(self) -> wtypes.WType:\n base_wtype = self.base.wtype\n if not isinstance(base_wtype, wtypes.WTuple | wtypes.ARC4Tuple):\n raise InternalError(\n f\"Tuple item expression should be for a tuple type, got {base_wtype}\",\n self.source_location,\n )\n try:\n wtype = base_wtype.types[self.index]\n except IndexError as ex:\n raise CodeError(\"invalid index into tuple expression\", self.source_location) from ex\n return wtype\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_tuple_item_expression(self)\n\n\n@attrs.frozen\nclass VarExpression(Expression):\n name: str\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_var_expression(self)\n\n\n@attrs.frozen(kw_only=True)\nclass InnerTransactionField(Expression):\n itxn: Expression = attrs.field(validator=expression_has_wtype(wtypes.WInnerTransaction))\n field: TxnField\n array_index: Expression | None = None\n\n def __attrs_post_init__(self) -> None:\n has_array = self.array_index is not None\n if has_array != self.field.is_array:\n raise InternalError(\n f\"Inconsistent field and array_index combination: \"\n f\"{self.field} and {'' if has_array else 'no '} array provided\",\n self.source_location,\n )\n if self.wtype.scalar_type != self.field.avm_type:\n raise InternalError(\n f\"wtype of field {self.field.immediate} is {self.field.wtype}\"\n f\" which is not compatible with specified result type {self.wtype}\",\n self.source_location,\n )\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_inner_transaction_field(self)\n\n\n@attrs.define\nclass SubmitInnerTransaction(Expression):\n itxns: Sequence[Expression] = attrs.field(converter=tuple[Expression, ...])\n wtype: WType = attrs.field(init=False)\n\n @wtype.default\n def _wtype(self) -> wtypes.WType:\n txn_types = []\n for expr in self.itxns:\n if not isinstance(expr.wtype, wtypes.WInnerTransactionFields):\n raise CodeError(\"invalid expression type for submit\", expr.source_location)\n txn_types.append(wtypes.WInnerTransaction.from_type(expr.wtype.transaction_type))\n try:\n (single_txn,) = txn_types\n except ValueError:\n return wtypes.WTuple(txn_types, self.source_location)\n else:\n return single_txn\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_submit_inner_transaction(self)\n\n\n@attrs.frozen\nclass FieldExpression(Expression):\n base: Expression = attrs.field(\n validator=expression_has_wtype(wtypes.WStructType, wtypes.ARC4Struct, wtypes.WTuple)\n )\n name: str\n wtype: wtypes.WType = attrs.field(init=False)\n\n @wtype.default\n def _wtype_factory(self) -> wtypes.WType:\n dataclass_type = self.base.wtype\n assert isinstance(dataclass_type, wtypes.WStructType | wtypes.ARC4Struct | wtypes.WTuple)\n try:\n return dataclass_type.fields[self.name]\n except KeyError:\n raise CodeError(f\"invalid field for {dataclass_type}\", self.source_location) from None\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_field_expression(self)\n\n\n@attrs.frozen\nclass IndexExpression(Expression):\n base: Expression = attrs.field(\n validator=expression_has_wtype(\n wtypes.bytes_wtype,\n wtypes.ARC4StaticArray,\n wtypes.ARC4DynamicArray,\n # NOTE: tuples (native or arc4) use TupleItemExpression instead\n )\n )\n index: Expression = attrs.field(validator=expression_has_wtype(wtypes.uint64_wtype))\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_index_expression(self)\n\n\n@attrs.frozen\nclass SliceExpression(Expression):\n base: Expression = attrs.field(\n validator=expression_has_wtype(\n wtypes.bytes_wtype,\n wtypes.WTuple,\n )\n )\n\n begin_index: Expression | None\n end_index: Expression | None\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_slice_expression(self)\n\n\n@attrs.frozen\nclass IntersectionSliceExpression(Expression):\n \"\"\"\n Returns the intersection of the slice indexes and the base\n \"\"\"\n\n base: Expression = attrs.field(\n validator=expression_has_wtype(\n wtypes.bytes_wtype,\n wtypes.WTuple,\n )\n )\n\n begin_index: Expression | int | None\n end_index: Expression | int | None\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_intersection_slice_expression(self)\n\n\n@attrs.frozen\nclass AppStateExpression(Expression):\n key: Expression = attrs.field(validator=expression_has_wtype(wtypes.state_key))\n exists_assertion_message: str | None\n \"\"\"TEAL comment that will be emitted in a checked-read scenario\"\"\"\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_app_state_expression(self)\n\n\n@attrs.frozen\nclass AppAccountStateExpression(Expression):\n key: Expression = attrs.field(validator=expression_has_wtype(wtypes.state_key))\n exists_assertion_message: str | None\n \"\"\"TEAL comment that will be emitted in a checked-read scenario\"\"\"\n account: Expression = attrs.field(\n validator=expression_has_wtype(wtypes.account_wtype, wtypes.uint64_wtype)\n )\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_app_account_state_expression(self)\n\n\n@attrs.frozen\nclass BoxValueExpression(Expression):\n key: Expression = attrs.field(validator=expression_has_wtype(wtypes.box_key))\n exists_assertion_message: str | None\n \"\"\"TEAL comment that will be emitted in a checked-read scenario\"\"\"\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_box_value_expression(self)\n\n\n@attrs.frozen\nclass SingleEvaluation(Expression):\n \"\"\"\n This node wraps an underlying expression and effectively caches the result of that lowering,\n such that regardless of how many times the SingleEvaluation object\n (or any object comparing equal to it) appears in the AWST,\n the underlying source expression will only be evaluated once.\n \"\"\"\n\n source: Expression\n _id: int = attrs.field()\n wtype: WType = attrs.field(init=False, eq=False)\n source_location: SourceLocation = attrs.field(eq=False)\n\n @_id.default\n def _default_id(self) -> int:\n return id(self)\n\n @wtype.default\n def _wtype(self) -> WType:\n return self.source.wtype\n\n @source_location.default\n def _default_source_location(self) -> SourceLocation:\n return self.source.source_location\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_single_evaluation(self)\n\n\n@attrs.frozen\nclass ReinterpretCast(Expression):\n \"\"\"Convert an expression to an AVM equivalent type.\n\n Note: the validation of this isn't done until IR construction\"\"\"\n\n expr: Expression\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_reinterpret_cast(self)\n\n\nStorageExpression = AppStateExpression | AppAccountStateExpression | BoxValueExpression\n# Expression types that are valid on the left hand side of assignment *statements*\n# Note that some of these can be recursive\/nested, eg:\n# obj.field[index].another_field = 123\nLvalue = VarExpression | FieldExpression | IndexExpression | TupleExpression | StorageExpression\n\n\n@attrs.frozen\nclass NewArray(Expression):\n wtype: wtypes.WArray | wtypes.ARC4Array\n values: Sequence[Expression] = attrs.field(default=(), converter=tuple[Expression, ...])\n\n @values.validator\n def _check_element_types(self, _attribute: object, value: tuple[Expression, ...]) -> None:\n if any(expr.wtype != self.wtype.element_type for expr in value):\n raise ValueError(\n f\"All array elements should have array type: {self.wtype.element_type}\"\n )\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_new_array(self)\n\n\n@attrs.frozen\nclass ConditionalExpression(Expression):\n \"\"\"A \"ternary\" operator with conditional evaluation - the true and false expressions must only\n be evaluated if they will be the result of expression.\n \"\"\"\n\n condition: Expression = attrs.field(validator=[wtype_is_bool])\n true_expr: Expression\n false_expr: Expression\n wtype: WType = attrs.field()\n\n @wtype.default\n def _wtype(self) -> WType:\n if self.true_expr.wtype != self.false_expr.wtype:\n raise CodeError(\n f\"true and false expressions of conditional have differing types:\"\n f\" {self.true_expr.wtype} and {self.false_expr.wtype}\",\n self.source_location,\n )\n return self.true_expr.wtype\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_conditional_expression(self)\n\n\n@attrs.frozen\nclass AssignmentStatement(Statement):\n \"\"\"\n A single assignment statement e.g. `a = 1`.\n\n Multi-assignment statements like `a = b = 1` should be split in the AST pass.\n\n Will validate that target and value are of the same type, and that said type is usable\n as an l-value.\n \"\"\"\n\n target: Lvalue\n value: Expression\n\n def __attrs_post_init__(self) -> None:\n if self.value.wtype != self.target.wtype:\n raise CodeError(\n \"assignment target type differs from expression value type\",\n self.source_location,\n )\n if self.value.wtype == wtypes.void_wtype:\n raise CodeError(\"void type cannot be assigned\", self.source_location)\n\n def accept(self, visitor: StatementVisitor[T]) -> T:\n return visitor.visit_assignment_statement(self)\n\n\n@attrs.frozen\nclass AssignmentExpression(Expression):\n \"\"\"\n This both assigns value to target and returns the value as the result of the expression.\n\n Will validate that target and value are of the same type, and that said type is usable\n as an l-value.\n \"\"\"\n\n target: Lvalue = attrs.field()\n value: Expression = attrs.field()\n wtype: wtypes.WType = attrs.field(init=False)\n\n @wtype.default\n def _wtype(self) -> wtypes.WType:\n return self.target.wtype\n\n @value.validator\n def _value_validator(self, _attribute: object, value: Expression) -> None:\n if value.wtype != self.target.wtype:\n raise CodeError(\n \"assignment target type differs from expression value type\",\n self.source_location,\n )\n if value.wtype == wtypes.void_wtype:\n raise CodeError(\"void type cannot be assigned\", self.source_location)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_assignment_expression(self)\n\n\nclass EqualityComparison(enum.StrEnum):\n eq = \"==\"\n ne = \"!=\"\n\n\nclass NumericComparison(enum.StrEnum):\n eq = \"==\" # \ud83d\ude29 why can't Python have enum inheritance\n ne = \"!=\"\n lt = \"<\"\n lte = \"<=\"\n gt = \">\"\n gte = \">=\"\n\n\nnumeric_comparable = expression_has_wtype(\n wtypes.uint64_wtype,\n wtypes.biguint_wtype,\n wtypes.bool_wtype,\n wtypes.asset_wtype,\n wtypes.application_wtype,\n)\n\n\n@attrs.frozen\nclass NumericComparisonExpression(Expression):\n \"\"\"Compare two numeric types.\n\n Any type promotion etc should be done at the source language level,\n this operation expects both arguments to already be in the same type.\n This is to insulate against language-specific differences in type promotion rules,\n or equality comparisons with bool, and so on.\n \"\"\"\n\n wtype: WType = attrs.field(default=wtypes.bool_wtype, init=False)\n\n # TODO: make these names consistent with other expressions\n lhs: Expression = attrs.field(validator=[numeric_comparable])\n operator: NumericComparison\n rhs: Expression = attrs.field(validator=[numeric_comparable])\n\n def __attrs_post_init__(self) -> None:\n if self.lhs.wtype != self.rhs.wtype:\n raise InternalError(\n \"numeric comparison between different wtypes:\"\n f\" {self.lhs.wtype} and {self.rhs.wtype}\",\n self.source_location,\n )\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_numeric_comparison_expression(self)\n\n\nbytes_comparable = expression_has_wtype(\n wtypes.bytes_wtype,\n wtypes.account_wtype,\n wtypes.string_wtype,\n wtypes.ARC4Type,\n)\n\n\n@attrs.frozen\nclass BytesComparisonExpression(Expression):\n wtype: WType = attrs.field(default=wtypes.bool_wtype, init=False)\n\n lhs: Expression = attrs.field(validator=[bytes_comparable])\n operator: EqualityComparison\n rhs: Expression = attrs.field(validator=[bytes_comparable])\n\n def __attrs_post_init__(self) -> None:\n if self.lhs.wtype != self.rhs.wtype:\n raise InternalError(\n \"bytes comparison between different wtypes:\"\n f\" {self.lhs.wtype} and {self.rhs.wtype}\",\n self.source_location,\n )\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_bytes_comparison_expression(self)\n\n\n@attrs.frozen\nclass SubroutineID:\n target: str\n\n\n@attrs.frozen(kw_only=True)\nclass InstanceMethodTarget:\n member_name: str\n\n\n@attrs.frozen(kw_only=True)\nclass InstanceSuperMethodTarget:\n member_name: str\n\n\n@attrs.frozen(kw_only=True)\nclass ContractMethodTarget:\n cref: ContractReference\n member_name: str\n\n\nSubroutineTarget = (\n SubroutineID | InstanceMethodTarget | InstanceSuperMethodTarget | ContractMethodTarget\n)\n\n\n@attrs.frozen\nclass CallArg:\n name: str | None # if None, then passed positionally\n value: Expression\n\n\n@attrs.frozen\nclass SubroutineCallExpression(Expression):\n target: SubroutineTarget\n args: Sequence[CallArg] = attrs.field(converter=tuple[CallArg, ...])\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_subroutine_call_expression(self)\n\n\n@attrs.frozen\nclass PuyaLibData:\n id: str\n params: Mapping[str, wtypes.WType]\n wtype: wtypes.WType\n\n\nclass PuyaLibFunction(enum.Enum):\n ensure_budget = PuyaLibData(\n id=\"_puya_lib.util.ensure_budget\",\n params={\"required_budget\": wtypes.uint64_wtype, \"fee_source\": wtypes.uint64_wtype},\n wtype=wtypes.void_wtype,\n )\n is_substring = PuyaLibData(\n id=\"_puya_lib.bytes_.is_substring\",\n params={\"item\": wtypes.bytes_wtype, \"sequence\": wtypes.bytes_wtype},\n wtype=wtypes.bool_wtype,\n )\n\n\n@attrs.define\nclass PuyaLibCall(Expression):\n func: PuyaLibFunction\n args: Sequence[CallArg] = attrs.field(default=(), converter=tuple[CallArg, ...])\n wtype: wtypes.WType = attrs.field(init=False)\n\n @wtype.default\n def _wtype(self) -> wtypes.WType:\n return self.func.value.wtype\n\n @args.validator\n def _args_validator(self, _: object, args: Sequence[CallArg]) -> None:\n if len(self.func.value.params) != len(args):\n raise CodeError(\n f\"provided args does not match arity for {self.func.name}\", self.source_location\n )\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_puya_lib_call(self)\n\n\n@enum.unique\nclass UInt64BinaryOperator(enum.StrEnum):\n add = \"+\"\n sub = \"-\"\n mult = \"*\"\n floor_div = \"\/\/\"\n mod = \"%\"\n pow = \"**\"\n lshift = \"<<\"\n rshift = \">>\"\n bit_or = \"|\"\n bit_xor = \"^\"\n bit_and = \"&\"\n # unsupported:\n # \/ aka ast.Div\n # @ aka ast.MatMult\n\n\n@enum.unique\nclass BigUIntBinaryOperator(enum.StrEnum):\n add = \"+\"\n sub = \"-\"\n mult = \"*\"\n floor_div = \"\/\/\"\n mod = \"%\"\n bit_or = \"|\"\n bit_xor = \"^\"\n bit_and = \"&\"\n # unsupported:\n # ** aka ast.Pow\n # \/ aka ast.Div\n # @ aka ast.MatMult\n # << aka ast.LShift\n # >> aka ast.RShift\n\n\n@enum.unique\nclass BytesBinaryOperator(enum.StrEnum):\n add = \"+\"\n bit_or = \"|\"\n bit_xor = \"^\"\n bit_and = \"&\"\n\n\n@enum.unique\nclass BytesUnaryOperator(enum.StrEnum):\n bit_invert = \"~\"\n\n\n@enum.unique\nclass UInt64UnaryOperator(enum.StrEnum):\n bit_invert = \"~\"\n\n\n@enum.unique\nclass UInt64PostfixUnaryOperator(enum.StrEnum):\n increment = \"++\"\n decrement = \"--\"\n\n\n@attrs.frozen\nclass UInt64UnaryOperation(Expression):\n op: UInt64UnaryOperator\n expr: Expression = attrs.field(validator=[wtype_is_uint64])\n wtype: WType = attrs.field(default=wtypes.uint64_wtype, init=False)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_uint64_unary_operation(self)\n\n\n@attrs.frozen\nclass UInt64PostfixUnaryOperation(Expression):\n op: UInt64PostfixUnaryOperator\n target: Lvalue = attrs.field(validator=[wtype_is_uint64])\n wtype: WType = attrs.field(default=wtypes.uint64_wtype, init=False)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_uint64_postfix_unary_operation(self)\n\n\n@enum.unique\nclass BigUIntPostfixUnaryOperator(enum.StrEnum):\n increment = \"++\"\n decrement = \"--\"\n\n\n@attrs.frozen\nclass BigUIntPostfixUnaryOperation(Expression):\n op: BigUIntPostfixUnaryOperator\n target: Expression = attrs.field(validator=[wtype_is_biguint])\n wtype: WType = attrs.field(default=wtypes.biguint_wtype, init=False)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_biguint_postfix_unary_operation(self)\n\n\n@attrs.frozen\nclass BytesUnaryOperation(Expression):\n op: BytesUnaryOperator\n expr: Expression = attrs.field(validator=[wtype_is_bytes])\n wtype: WType = attrs.field(default=wtypes.bytes_wtype, init=False)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_bytes_unary_operation(self)\n\n\n@attrs.frozen\nclass UInt64BinaryOperation(Expression):\n left: Expression = attrs.field(validator=[wtype_is_uint64])\n op: UInt64BinaryOperator\n right: Expression = attrs.field(validator=[wtype_is_uint64])\n wtype: WType = attrs.field(default=wtypes.uint64_wtype, init=False)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_uint64_binary_operation(self)\n\n\n@attrs.frozen\nclass BigUIntBinaryOperation(Expression):\n left: Expression = attrs.field(validator=[wtype_is_biguint])\n op: BigUIntBinaryOperator\n right: Expression = attrs.field(validator=[wtype_is_biguint])\n wtype: WType = attrs.field(default=wtypes.biguint_wtype, init=False)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_biguint_binary_operation(self)\n\n\n@attrs.frozen\nclass BytesBinaryOperation(Expression):\n left: Expression = attrs.field(\n validator=[expression_has_wtype(wtypes.bytes_wtype, wtypes.string_wtype)]\n )\n op: BytesBinaryOperator\n right: Expression = attrs.field(\n validator=[expression_has_wtype(wtypes.bytes_wtype, wtypes.string_wtype)]\n )\n wtype: WType = attrs.field(init=False)\n\n @right.validator\n def _check_right(self, _attribute: object, right: Expression) -> None:\n if right.wtype != self.left.wtype:\n raise CodeError(\n f\"Bytes operation on differing types,\"\n f\" lhs is {self.left.wtype}, rhs is {self.right.wtype}\",\n self.source_location,\n )\n\n @wtype.default\n def _wtype_factory(self) -> wtypes.WType:\n return self.left.wtype\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_bytes_binary_operation(self)\n\n\n@enum.unique\nclass BinaryBooleanOperator(enum.StrEnum):\n and_ = \"and\"\n or_ = \"or\"\n\n\n@attrs.frozen\nclass BooleanBinaryOperation(Expression):\n left: Expression = attrs.field(validator=[wtype_is_bool])\n op: BinaryBooleanOperator\n right: Expression = attrs.field(validator=[wtype_is_bool])\n wtype: WType = attrs.field(default=wtypes.bool_wtype, init=False)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_boolean_binary_operation(self)\n\n\n@attrs.frozen\nclass Not(Expression):\n expr: Expression = attrs.field(validator=[wtype_is_bool])\n wtype: WType = attrs.field(default=wtypes.bool_wtype, init=False)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_not_expression(self)\n\n\n@attrs.frozen\nclass UInt64AugmentedAssignment(Statement):\n target: Lvalue = attrs.field(validator=[wtype_is_uint64])\n op: UInt64BinaryOperator\n value: Expression = attrs.field(validator=[wtype_is_uint64])\n\n def accept(self, visitor: StatementVisitor[T]) -> T:\n return visitor.visit_uint64_augmented_assignment(self)\n\n\n@attrs.frozen\nclass BigUIntAugmentedAssignment(Statement):\n target: Lvalue = attrs.field(validator=[wtype_is_biguint])\n op: BigUIntBinaryOperator\n value: Expression = attrs.field(validator=[wtype_is_biguint])\n\n def accept(self, visitor: StatementVisitor[T]) -> T:\n return visitor.visit_biguint_augmented_assignment(self)\n\n\n@attrs.frozen\nclass BytesAugmentedAssignment(Statement):\n target: Lvalue = attrs.field(\n validator=[\n expression_has_wtype(wtypes.bytes_wtype, wtypes.string_wtype, wtypes.arc4_string_alias)\n ]\n )\n op: BytesBinaryOperator\n value: Expression = attrs.field(\n validator=[\n expression_has_wtype(wtypes.bytes_wtype, wtypes.string_wtype, wtypes.arc4_string_alias)\n ]\n )\n\n @value.validator\n def _check_value(self, _attribute: object, value: Expression) -> None:\n if value.wtype != self.target.wtype:\n raise CodeError(\n f\"Augmented assignment of differing types,\"\n f\" expected {self.target.wtype}, got {value.wtype}\",\n value.source_location,\n )\n\n def accept(self, visitor: StatementVisitor[T]) -> T:\n return visitor.visit_bytes_augmented_assignment(self)\n\n\n@attrs.frozen\nclass Emit(Expression):\n signature: str\n value: Expression = attrs.field(validator=expression_has_wtype(wtypes.ARC4Struct))\n wtype: WType = attrs.field(default=wtypes.void_wtype, init=False)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_emit(self)\n\n\n@attrs.frozen\nclass Range(Expression):\n wtype: WType = attrs.field(default=wtypes.uint64_range_wtype, init=False)\n start: Expression = attrs.field(validator=[wtype_is_uint64])\n stop: Expression = attrs.field(validator=[wtype_is_uint64])\n step: Expression = attrs.field(validator=[wtype_is_uint64])\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_range(self)\n\n\n@attrs.frozen\nclass Enumeration(Expression):\n expr: Expression\n wtype: wtypes.WEnumeration = attrs.field(init=False)\n\n @wtype.default\n def _wtype(self) -> wtypes.WEnumeration:\n return wtypes.WEnumeration(self.expr.wtype)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_enumeration(self)\n\n\n@attrs.frozen\nclass Reversed(Expression):\n expr: Expression\n wtype: WType = attrs.field(init=False)\n\n @wtype.default\n def _wtype(self) -> WType:\n return self.expr.wtype\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_reversed(self)\n\n\n@attrs.frozen\nclass ForInLoop(Statement):\n sequence: Expression\n items: Lvalue # item variable(s)\n loop_body: Block\n\n def accept(self, visitor: StatementVisitor[T]) -> T:\n return visitor.visit_for_in_loop(self)\n\n\n@attrs.frozen\nclass StateGet(Expression):\n \"\"\"\n Get value or default if unset - note that for get without a default,\n can just use the underlying StateExpression\n \"\"\"\n\n field: StorageExpression\n default: Expression = attrs.field()\n wtype: WType = attrs.field(init=False)\n\n @default.validator\n def _check_default(self, _attribute: object, default: Expression) -> None:\n if self.field.wtype != default.wtype:\n raise CodeError(\n \"Default state value should match storage type\", default.source_location\n )\n\n @wtype.default\n def _wtype_factory(self) -> WType:\n return self.field.wtype\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_state_get(self)\n\n\n@attrs.frozen\nclass StateGetEx(Expression):\n field: StorageExpression\n wtype: wtypes.WTuple = attrs.field(init=False)\n\n @wtype.default\n def _wtype_factory(self) -> wtypes.WTuple:\n return wtypes.WTuple(\n (self.field.wtype, wtypes.bool_wtype),\n self.source_location,\n )\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_state_get_ex(self)\n\n\n@attrs.frozen\nclass StateExists(Expression):\n field: StorageExpression\n wtype: WType = attrs.field(default=wtypes.bool_wtype, init=False)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_state_exists(self)\n\n\n@attrs.frozen\nclass StateDelete(Expression):\n field: StorageExpression\n wtype: WType = attrs.field(default=wtypes.void_wtype, init=False)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_state_delete(self)\n\n\n@attrs.frozen\nclass NewStruct(Expression):\n wtype: wtypes.WStructType | wtypes.ARC4Struct\n values: Mapping[str, Expression] = attrs.field(converter=immutabledict)\n\n @values.validator\n def _validate_values(self, _instance: object, values: Mapping[str, Expression]) -> None:\n if values.keys() != self.wtype.fields.keys():\n raise CodeError(\"Invalid argument(s)\", self.source_location)\n for field_name, field_value in self.values.items():\n expected_wtype = self.wtype.fields[field_name]\n if field_value.wtype != expected_wtype:\n raise CodeError(\"Invalid argument type(s)\", self.source_location)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_new_struct(self)\n\n\n@attrs.frozen\nclass RootNode(Node, ABC):\n @property\n @abstractmethod\n def id(self) -> str: ...\n\n @abstractmethod\n def accept(self, visitor: RootNodeVisitor[T]) -> T: ...\n\n\n@attrs.frozen(kw_only=True)\nclass SubroutineArgument:\n name: str\n source_location: SourceLocation\n wtype: WType = attrs.field()\n\n @wtype.validator\n def _wtype_validator(self, _attribute: object, wtype: WType) -> None:\n if wtype == wtypes.void_wtype:\n raise CodeError(\"void type arguments are not supported\", self.source_location)\n\n\n@attrs.frozen\nclass MethodDocumentation:\n description: str | None = None\n args: immutabledict[str, str] = attrs.field(default={}, converter=immutabledict)\n returns: str | None = None\n\n\n@attrs.frozen\nclass Function(Node, ABC):\n args: Sequence[SubroutineArgument] = attrs.field(converter=tuple[SubroutineArgument, ...])\n return_type: WType\n body: Block\n documentation: MethodDocumentation\n inline: bool | None = None\n\n @property\n @abstractmethod\n def short_name(self) -> str: ...\n\n @property\n @abstractmethod\n def full_name(self) -> str: ...\n\n\n@attrs.frozen(kw_only=True)\nclass Subroutine(Function, RootNode):\n id: str\n name: str\n\n @property\n def short_name(self) -> str:\n return self.name\n\n @property\n def full_name(self) -> str:\n return self.id\n\n def accept(self, visitor: RootNodeVisitor[T]) -> T:\n return visitor.visit_subroutine(self)\n\n\nAWST: typing.TypeAlias = Sequence[RootNode]\n\n\n@attrs.frozen\nclass ContractMemberNode(Node, ABC):\n @property\n @abc.abstractmethod\n def member_name(self) -> str: ...\n\n @abc.abstractmethod\n def accept(self, visitor: ContractMemberVisitor[T]) -> T: ...\n\n\n@attrs.frozen(kw_only=True)\nclass ContractMethod(Function, ContractMemberNode):\n cref: ContractReference\n member_name: str\n arc4_method_config: \"ARC4MethodConfig | None\"\n\n @property\n def short_name(self) -> str:\n return self.member_name\n\n @property\n def full_name(self) -> str:\n return f\"{self.cref}.{self.member_name}\"\n\n def accept(self, visitor: ContractMemberVisitor[T]) -> T:\n return visitor.visit_contract_method(self)\n\n\n@enum.unique\nclass AppStorageKind(enum.Enum):\n app_global = enum.auto()\n account_local = enum.auto()\n box = enum.auto()\n\n\n@attrs.frozen\nclass AppStorageDefinition(ContractMemberNode):\n member_name: str\n kind: AppStorageKind\n storage_wtype: WType\n key_wtype: WType | None\n \"\"\"if not None, then this is a map rather than singular\"\"\"\n key: BytesConstant\n \"\"\"for maps, this is the prefix\"\"\"\n description: str | None\n\n def accept(self, visitor: ContractMemberVisitor[T]) -> T:\n return visitor.visit_app_storage_definition(self)\n\n\ndef _validate_avm_version(node: Node, _: object, avm_version: int | None) -> None:\n if avm_version is not None and avm_version not in SUPPORTED_AVM_VERSIONS:\n raise CodeError(\n \"unsupported AVM version\",\n node.source_location,\n )\n\n\n@attrs.frozen(kw_only=True)\nclass LogicSignature(RootNode):\n id: LogicSigReference\n short_name: str\n program: Subroutine = attrs.field()\n docstring: str | None\n avm_version: int | None = attrs.field(validator=_validate_avm_version)\n\n @program.validator\n def _validate_program(self, _instance: object, program: Subroutine) -> None:\n if program.args:\n raise CodeError(\n \"logicsig should not take any args\",\n program.args[0].source_location,\n )\n if program.return_type not in (wtypes.uint64_wtype, wtypes.bool_wtype):\n raise CodeError(\n \"Invalid return type for logicsig method, should be either bool or UInt64.\",\n program.source_location,\n )\n\n def accept(self, visitor: RootNodeVisitor[T]) -> T:\n return visitor.visit_logic_signature(self)\n\n\n@attrs.frozen\nclass CompiledContract(Expression):\n contract: ContractReference\n allocation_overrides: Mapping[TxnField, Expression] = attrs.field(\n factory=immutabledict, converter=immutabledict\n )\n prefix: str | None = None\n \"\"\"\n Prefix will either be the value specified here or PuyaOptions.template_vars_prefix\n if prefix is None\n\n The prefix is then prefixed with the template_variables keys on this node to determine the\n final template variable name\n \"\"\"\n template_variables: Mapping[str, Expression] = attrs.field(\n factory=immutabledict, converter=immutabledict\n )\n \"\"\"\n template variables combined with their prefix defined on this node take precedence over\n template variables of the same key defined on PuyaOptions\n \"\"\"\n\n @allocation_overrides.validator\n def _allocation_overrides(\n self, _attribute: object, value: Mapping[TxnField, Expression]\n ) -> None:\n if value.keys() - {\n TxnField.ExtraProgramPages,\n TxnField.GlobalNumUint,\n TxnField.GlobalNumByteSlice,\n TxnField.LocalNumUint,\n TxnField.LocalNumByteSlice,\n }:\n raise InternalError(\"only allocation fields can be overridden\", self.source_location)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_compiled_contract(self)\n\n\n@attrs.frozen\nclass CompiledLogicSig(Expression):\n logic_sig: LogicSigReference\n prefix: str | None = None\n template_variables: Mapping[str, Expression] = attrs.field(\n converter=immutabledict, factory=immutabledict\n )\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_compiled_logicsig(self)\n\n\n@attrs.frozen(kw_only=True)\nclass StateTotals:\n global_uints: int | None = None\n local_uints: int | None = None\n global_bytes: int | None = None\n local_bytes: int | None = None\n\n\n@attrs.frozen\nclass ARC4Router(Expression):\n wtype: WType = attrs.field(default=wtypes.bool_wtype, init=False)\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_arc4_router(self)\n\n\n@attrs.frozen(kw_only=True)\nclass Contract(RootNode):\n id: ContractReference\n \"\"\"The fully qualified ID, must be unique within a compilation run.\"\"\"\n name: str\n \"\"\"The short \/ friendly name for the Contract, used in output file naming and in ARC-32\"\"\"\n description: str | None\n \"\"\"The (user supplied) contract description, currently only used in ARC-32 output\"\"\"\n method_resolution_order: Sequence[ContractReference]\n \"\"\"\n The lookup order to use when resolving calls to contract methods.\n Shouldn't include the current contract, but otherwise should be exhaustive,\n ie no recursive lookup is implemented for bases of bases.\n Front-ends for languages with multiple-inheritance must linearize their hierarchy in the\n correct order, which is why bases of bases are not resolved, since they may end up in a\n different order depending on the contract that is ultimately being compiled.\n \"\"\"\n approval_program: ContractMethod = attrs.field()\n \"\"\"\n The entry point to the approval program, can also appear in methods, but this is not required.\n \"\"\"\n clear_program: ContractMethod = attrs.field()\n \"\"\"\n The entry point to the clear-state program, can appear in methods, but not required.\n \"\"\"\n methods: Sequence[ContractMethod] = attrs.field(converter=tuple[ContractMethod, ...])\n \"\"\"\n All the methods in this contract and in it's entire hierarchy.\n A Sequence for serialization purposes, order doesn't matter.\n \"\"\"\n app_state: Sequence[AppStorageDefinition] = attrs.field(\n converter=tuple[AppStorageDefinition, ...]\n )\n \"\"\"\n All the app storage on this contract.\n A Sequence for serialization purposes, order doesn't matter.\n \"\"\"\n state_totals: StateTotals | None\n \"\"\"State totals which can override in part or in full those implied by `app_state`.\"\"\"\n reserved_scratch_space: Set[int]\n \"\"\"Scratch slots that the contract is explicitly setting aside for direct\/explicit usage.\"\"\"\n avm_version: int | None = attrs.field(validator=_validate_avm_version)\n \"\"\"AVM version to target, defaults to options.target_avm_version\"\"\"\n\n @approval_program.validator\n def check_approval(self, _attribute: object, approval: ContractMethod) -> None:\n if approval.args:\n raise CodeError(\n \"approval method should not take any args (other than self)\",\n approval.source_location,\n )\n if approval.return_type not in (wtypes.uint64_wtype, wtypes.bool_wtype):\n raise CodeError(\n \"Invalid return type for approval method, should be either bool or UInt64.\",\n approval.source_location,\n )\n if approval.arc4_method_config:\n raise CodeError(\n \"approval method should not be marked as an ABI method\",\n approval.source_location,\n )\n\n @clear_program.validator\n def check_clear(self, _attribute: object, clear: ContractMethod) -> None:\n if clear.args:\n raise CodeError(\n \"clear-state method should not take any args (other than self)\",\n clear.source_location,\n )\n if clear.return_type not in (wtypes.uint64_wtype, wtypes.bool_wtype):\n raise CodeError(\n \"Invalid return type for clear-state method, should be either bool or UInt64.\",\n clear.source_location,\n )\n if clear.arc4_method_config:\n raise CodeError(\n \"clear-state method should not be marked as an ABI method\",\n clear.source_location,\n )\n\n @cached_property\n def all_methods(self) -> Sequence[ContractMethod]:\n return unique((self.approval_program, self.clear_program, *self.methods))\n\n def accept(self, visitor: RootNodeVisitor[T]) -> T:\n return visitor.visit_contract(self)\n\n @typing.overload\n def resolve_contract_method(self, name: str) -> ContractMethod | None: ...\n\n @typing.overload\n def resolve_contract_method(\n self,\n name: str,\n source_location: SourceLocation,\n *,\n start: ContractReference,\n skip: bool = False,\n ) -> ContractMethod | None: ...\n\n def resolve_contract_method(\n self,\n name: str,\n source_location: SourceLocation | None = None,\n *,\n start: ContractReference | None = None,\n skip: bool = False,\n ) -> ContractMethod | None:\n mro = [self.id, *self.method_resolution_order]\n if start:\n try:\n curr_idx = mro.index(start)\n except ValueError:\n raise CodeError(\n \"call to base method outside current hierarchy\", source_location\n ) from None\n mro = mro[curr_idx:]\n if skip:\n mro = mro[1:]\n for cref in mro:\n for method in self.methods:\n if method.member_name == name and method.cref == cref:\n return method\n return None\n\n\nclass ARC4CreateOption(enum.Enum):\n allow = enum.auto()\n require = enum.auto()\n disallow = enum.auto()\n\n\n@attrs.frozen(kw_only=True)\nclass ARC4BareMethodConfig:\n source_location: SourceLocation\n allowed_completion_types: Sequence[OnCompletionAction] = attrs.field(\n default=(OnCompletionAction.NoOp,),\n converter=tuple[OnCompletionAction, ...],\n validator=attrs.validators.min_len(1),\n )\n create: ARC4CreateOption = ARC4CreateOption.disallow\n\n\n@attrs.frozen(kw_only=True)\nclass ABIMethodArgConstantDefault:\n value: Expression\n\n\n@attrs.frozen(kw_only=True)\nclass ABIMethodArgMemberDefault:\n name: str\n\n\nABIMethodArgDefault = ABIMethodArgMemberDefault | ABIMethodArgConstantDefault\n\n\n@attrs.frozen(kw_only=True)\nclass ARC4ABIMethodConfig:\n source_location: SourceLocation\n allowed_completion_types: Sequence[OnCompletionAction] = attrs.field(\n default=(OnCompletionAction.NoOp,),\n converter=tuple[OnCompletionAction],\n validator=attrs.validators.min_len(1),\n )\n create: ARC4CreateOption = ARC4CreateOption.disallow\n name: str\n readonly: bool = False\n default_args: immutabledict[str, ABIMethodArgDefault] = immutabledict()\n \"\"\"Mapping is from parameter -> source\"\"\"\n\n\nARC4MethodConfig = ARC4BareMethodConfig | ARC4ABIMethodConfig\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/awst\/nodes.py","language":"Python","license":"NOASSERTION","size":57974} {"code":"import decimal\nimport enum\nimport functools\nimport typing\nfrom collections.abc import Mapping\n\nimport cattrs\nfrom cattrs import ClassValidationError, IterableValidationError, transform_error\nfrom cattrs.preconf.json import make_converter\nfrom cattrs.strategies import configure_tagged_union, include_subclasses\nfrom immutabledict import immutabledict\n\nfrom puya import log\nfrom puya.awst import nodes, txn_fields, wtypes\nfrom puya.errors import PuyaError\n\nlogger = log.get_logger(__name__)\n\n\ndef _unstructure_optional_enum_literal(value: object) -> object:\n if value is None:\n return None\n if not isinstance(value, enum.Enum):\n raise TypeError(\"expected enum value\")\n return value.value\n\n\n@functools.cache\ndef _get_converter() -> cattrs.preconf.json.JsonConverter:\n converter = make_converter()\n\n # literals with optional enum\n converter.register_unstructure_hook_factory(\n cattrs.converters.is_literal_containing_enums, lambda _: _unstructure_optional_enum_literal\n )\n\n # TxnField and PuyaLibFunction as name\n for enum_type in (txn_fields.TxnField, nodes.PuyaLibFunction):\n converter.register_unstructure_hook(enum_type, lambda v: v.name)\n converter.register_structure_hook(enum_type, lambda v, t: t[v])\n\n # decimals as str\n converter.register_unstructure_hook(decimal.Decimal, str)\n converter.register_structure_hook(decimal.Decimal, lambda v, _: decimal.Decimal(v))\n\n # nodes.Switch has a mapping of Expression -> Block\n # which can't be serialized with that structure as a JSON object\n # need to convert into a list of pairs instead\n def is_switch_cases(typ: object) -> bool:\n if typing.get_origin(typ) is Mapping:\n args = typing.get_args(typ)\n return args == (nodes.Expression, nodes.Block)\n return False\n\n def unstructure_switch_cases(value: Mapping[nodes.Expression, nodes.Block]) -> object:\n return converter.unstructure(value.items(), list[tuple[nodes.Expression, nodes.Block]])\n\n def structure_switch_cases(value: object, _: type) -> object:\n items = converter.structure(value, list[tuple[nodes.Expression, nodes.Block]])\n return immutabledict(items)\n\n converter.register_unstructure_hook_func(is_switch_cases, unstructure_switch_cases)\n converter.register_structure_hook_func(is_switch_cases, structure_switch_cases)\n\n # register AWST types and unions, order is important to ensure correct configuration\n union_strategy = configure_tagged_union\n include_subclasses(wtypes.WType, converter, union_strategy=union_strategy)\n union_strategy(wtypes.WStructType | wtypes.ARC4Struct, converter)\n union_strategy(nodes.SubroutineTarget, converter)\n include_subclasses(nodes.Expression, converter, union_strategy=union_strategy)\n union_strategy(nodes.Lvalue, converter)\n union_strategy(nodes.StorageExpression, converter)\n union_strategy(nodes.CompileTimeConstantExpression, converter)\n include_subclasses(nodes.Statement, converter, union_strategy=union_strategy)\n include_subclasses(nodes.RootNode, converter, union_strategy=union_strategy)\n return converter\n\n\ndef awst_to_json(awst: nodes.AWST) -> str:\n return _get_converter().dumps(awst, indent=4)\n\n\ndef _find_and_log_puya_errors(err: ClassValidationError | IterableValidationError) -> None:\n for ex in err.exceptions:\n match ex:\n case PuyaError():\n logger.error(ex.msg, location=ex.location)\n case ClassValidationError() | IterableValidationError():\n _find_and_log_puya_errors(ex)\n\n\ndef awst_from_json(json: str) -> nodes.AWST:\n try:\n return _get_converter().loads(json, nodes.AWST) # type: ignore[type-abstract]\n except (ClassValidationError, IterableValidationError) as err:\n _find_and_log_puya_errors(err)\n logger.debug(\"Deserialization error: \\n\" + \"\\n\".join(transform_error(err)))\n raise ValueError(\n \"Error during deserialization of AWST json. See debug log for details\"\n ) from err\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/awst\/serialize.py","language":"Python","license":"NOASSERTION","size":4052} {"code":"import base64\nimport typing\nfrom collections.abc import Iterable, Iterator, Mapping\n\nfrom puya.awst import nodes, wtypes\nfrom puya.awst.visitors import (\n ContractMemberVisitor,\n ExpressionVisitor,\n RootNodeVisitor,\n StatementVisitor,\n)\nfrom puya.errors import InternalError\n\n\nclass ToCodeVisitor(\n RootNodeVisitor[list[str]],\n StatementVisitor[list[str]],\n ExpressionVisitor[str],\n ContractMemberVisitor[list[str]],\n):\n def __init__(self) -> None:\n self._seen_single_evals = dict[nodes.SingleEvaluation, int]()\n\n def _single_eval_index(self, tmp: nodes.SingleEvaluation) -> int:\n return self._seen_single_evals.setdefault(tmp, len(self._seen_single_evals))\n\n @typing.override\n def visit_array_concat(self, expr: nodes.ArrayConcat) -> str:\n left = expr.left.accept(self)\n right = expr.right.accept(self)\n return f\"{left} + {right}\"\n\n @typing.override\n def visit_array_extend(self, expr: nodes.ArrayExtend) -> str:\n base = expr.base.accept(self)\n value = expr.other.accept(self)\n return f\"{base}.extend({value})\"\n\n @typing.override\n def visit_array_pop(self, expr: nodes.ArrayPop) -> str:\n base = expr.base.accept(self)\n return f\"{base}.pop()\"\n\n @typing.override\n def visit_copy(self, expr: nodes.Copy) -> str:\n value = expr.value.accept(self)\n return f\"{value}.copy()\"\n\n @typing.override\n def visit_reversed(self, expr: nodes.Reversed) -> str:\n sequence = expr.expr.accept(self)\n return f\"reversed({sequence})\"\n\n def visit_module(self, module: nodes.AWST) -> str:\n result = list[str]()\n for stmt in module:\n lines = stmt.accept(self)\n result.extend(lines)\n return \"\\n\".join(result).strip()\n\n @typing.override\n def visit_arc4_decode(self, expr: nodes.ARC4Decode) -> str:\n return f\"arc4_decode({expr.value.accept(self)}, {expr.wtype})\"\n\n @typing.override\n def visit_arc4_encode(self, expr: nodes.ARC4Encode) -> str:\n return f\"arc4_encode({expr.value.accept(self)}, {expr.wtype})\"\n\n @typing.override\n def visit_reinterpret_cast(self, expr: nodes.ReinterpretCast) -> str:\n return f\"reinterpret_cast<{expr.wtype}>({expr.expr.accept(self)})\"\n\n @typing.override\n def visit_single_evaluation(self, expr: nodes.SingleEvaluation) -> str:\n # only render source the first time it is encountered\n source = \"\" if expr in self._seen_single_evals else f\", source={expr.source.accept(self)}\"\n eval_id = self._single_eval_index(expr)\n\n return \"\".join(\n (\n f\"SINGLE_EVAL(id={eval_id}\",\n source,\n \")\",\n )\n )\n\n @typing.override\n def visit_app_state_expression(self, expr: nodes.AppStateExpression) -> str:\n return f\"GlobalState[{expr.key.accept(self)}]\"\n\n @typing.override\n def visit_app_account_state_expression(self, expr: nodes.AppAccountStateExpression) -> str:\n return f\"LocalState[{expr.key.accept(self)}, {expr.account.accept(self)}]\"\n\n @typing.override\n def visit_box_value_expression(self, expr: nodes.BoxValueExpression) -> str:\n return f\"Box[{expr.key.accept(self)}]\"\n\n @typing.override\n def visit_new_array(self, expr: nodes.NewArray) -> str:\n args = \", \".join(a.accept(self) for a in expr.values)\n return f\"new {expr.wtype}({args})\"\n\n @typing.override\n def visit_new_struct(self, expr: nodes.NewStruct) -> str:\n args = \", \".join([f\"{name}=\" + value.accept(self) for name, value in expr.values.items()])\n return f\"new {expr.wtype}({args})\"\n\n @typing.override\n def visit_enumeration(self, expr: nodes.Enumeration) -> str:\n sequence = expr.expr.accept(self)\n return f\"enumerate({sequence})\"\n\n @typing.override\n def visit_bytes_comparison_expression(self, expr: nodes.BytesComparisonExpression) -> str:\n return f\"{expr.lhs.accept(self)} {expr.operator} {expr.rhs.accept(self)}\"\n\n @typing.override\n def visit_subroutine_call_expression(self, expr: nodes.SubroutineCallExpression) -> str:\n match expr.target:\n case nodes.InstanceMethodTarget(member_name=member_name):\n target = f\"this::{member_name}\"\n case nodes.InstanceSuperMethodTarget(member_name=member_name):\n target = f\"super::{member_name}\"\n case nodes.ContractMethodTarget(cref=cref, member_name=member_name):\n target = \"::\".join((cref, member_name))\n case nodes.SubroutineID(target):\n pass\n case unhandled:\n typing.assert_never(unhandled)\n args = \", \".join(\n [(f\"{a.name}=\" if a.name else \"\") + a.value.accept(self) for a in expr.args]\n )\n return f\"{target}({args})\"\n\n @typing.override\n def visit_bytes_binary_operation(self, expr: nodes.BytesBinaryOperation) -> str:\n return f\"{expr.left.accept(self)} {expr.op.value} {expr.right.accept(self)}\"\n\n @typing.override\n def visit_boolean_binary_operation(self, expr: nodes.BooleanBinaryOperation) -> str:\n return f\"{expr.left.accept(self)} {expr.op.value} {expr.right.accept(self)}\"\n\n @typing.override\n def visit_not_expression(self, expr: nodes.Not) -> str:\n return f\"!({expr.expr.accept(self)})\"\n\n @typing.override\n def visit_bytes_augmented_assignment(\n self, statement: nodes.BytesAugmentedAssignment\n ) -> list[str]:\n return [\n f\"{statement.target.accept(self)} {statement.op.value}= {statement.value.accept(self)}\"\n ]\n\n @typing.override\n def visit_range(self, range_node: nodes.Range) -> str:\n range_args = \", \".join(\n [r.accept(self) for r in [range_node.start, range_node.stop, range_node.step]]\n )\n return f\"range({range_args})\"\n\n @typing.override\n def visit_for_in_loop(self, statement: nodes.ForInLoop) -> list[str]:\n sequence = statement.sequence.accept(self)\n loop_body = statement.loop_body.accept(self)\n item_vars = statement.items.accept(self)\n return [\n f\"for {item_vars} in {sequence} {{\",\n *_indent(loop_body),\n \"}\",\n ]\n\n @typing.override\n def visit_subroutine(self, statement: nodes.Subroutine) -> list[str]:\n args = \", \".join([f\"{a.name}: {a.wtype}\" for a in statement.args])\n body = statement.body.accept(self)\n return [\n \"\",\n f\"subroutine {statement.name}({args}): {statement.return_type}\",\n \"{\",\n *_indent(body),\n \"}\",\n ]\n\n @typing.override\n def visit_app_storage_definition(self, defn: nodes.AppStorageDefinition) -> list[str]:\n raise InternalError(\"app storage is converted as part of class\")\n\n @typing.override\n def visit_contract(self, c: nodes.Contract) -> list[str]:\n body = [\n \"method_resolution_order: (\",\n *_indent(f\"{cref},\" for cref in c.method_resolution_order),\n \")\",\n ]\n if c.app_state:\n state_by_kind = dict[nodes.AppStorageKind, list[nodes.AppStorageDefinition]]()\n for state in c.app_state:\n state_by_kind.setdefault(state.kind, []).append(state)\n for kind_name, kind in (\n (\"globals\", nodes.AppStorageKind.app_global),\n (\"locals\", nodes.AppStorageKind.account_local),\n (\"boxes\", nodes.AppStorageKind.box),\n ):\n state_of_kind = state_by_kind.pop(kind, [])\n if state_of_kind:\n body.extend(\n [\n f\"{kind_name} {{\",\n *_indent(\n (\n f\"[{s.key.accept(self)}]: {s.key_wtype} => {s.storage_wtype}\"\n if s.key_wtype is not None\n else f\"[{s.key.accept(self)}]: {s.storage_wtype}\"\n )\n for s in state_of_kind\n ),\n \"}\",\n ]\n )\n if state_by_kind:\n raise InternalError(\n f\"Unhandled app state kinds: {', '.join(map(str, state_by_kind.keys()))}\",\n c.source_location,\n )\n if c.reserved_scratch_space:\n body.extend(\n [\n \"reserved_scratch_space {\",\n *_indent([\", \".join(_collapse_sequential_ranges(c.reserved_scratch_space))]),\n \"}\",\n ]\n )\n for sub in c.all_methods:\n lines = sub.accept(self)\n body.extend(lines)\n\n if body and not body[0].strip():\n body = body[1:]\n\n header = [\"contract\", c.name]\n\n return [\n \"\",\n \" \".join(header),\n \"{\",\n *_indent(body),\n \"}\",\n ]\n\n @typing.override\n def visit_logic_signature(self, statement: nodes.LogicSignature) -> list[str]:\n body = statement.program.body.accept(self)\n return [\n \"\",\n f\"logicsig {statement.id}\",\n \"{\",\n *_indent(body),\n \"}\",\n ]\n\n @typing.override\n def visit_contract_method(self, statement: nodes.ContractMethod) -> list[str]:\n body = statement.body.accept(self)\n args = \", \".join([f\"{a.name}: {a.wtype}\" for a in statement.args])\n match statement.arc4_method_config:\n case None:\n deco = \"subroutine\"\n case nodes.ARC4BareMethodConfig():\n deco = \"baremethod\"\n case nodes.ARC4ABIMethodConfig(name=config_name):\n if statement.member_name != config_name:\n deco = f\"abimethod[name_override={config_name}]\"\n else:\n deco = \"abimethod\"\n case other:\n typing.assert_never(other)\n\n return [\n \"\",\n f\"{deco} {statement.full_name}({args}): {statement.return_type}\",\n \"{\",\n *_indent(body),\n \"}\",\n ]\n\n @typing.override\n def visit_assignment_expression(self, expr: nodes.AssignmentExpression) -> str:\n return f\"{expr.target.accept(self)}: {expr.target.wtype} := {expr.value.accept(self)}\"\n\n @typing.override\n def visit_assignment_statement(self, stmt: nodes.AssignmentStatement) -> list[str]:\n return [f\"{stmt.target.accept(self)}: {stmt.target.wtype} = {stmt.value.accept(self)}\"]\n\n @typing.override\n def visit_uint64_binary_operation(self, expr: nodes.UInt64BinaryOperation) -> str:\n return f\"{expr.left.accept(self)} {expr.op.value} {expr.right.accept(self)}\"\n\n @typing.override\n def visit_biguint_binary_operation(self, expr: nodes.BigUIntBinaryOperation) -> str:\n return f\"{expr.left.accept(self)} b{expr.op.value} {expr.right.accept(self)}\"\n\n @typing.override\n def visit_uint64_unary_operation(self, expr: nodes.UInt64UnaryOperation) -> str:\n return f\"{expr.op.value}({expr.expr.accept(self)})\"\n\n @typing.override\n def visit_bytes_unary_operation(self, expr: nodes.BytesUnaryOperation) -> str:\n return f\"b{expr.op.value}({expr.expr.accept(self)})\"\n\n @typing.override\n def visit_integer_constant(self, expr: nodes.IntegerConstant) -> str:\n if expr.teal_alias:\n return expr.teal_alias\n match expr.wtype:\n case wtypes.uint64_wtype:\n suffix = \"u\"\n case wtypes.biguint_wtype:\n suffix = \"n\"\n case wtypes.ARC4UIntN(n=n):\n suffix = f\"_arc4u{n}\"\n case _:\n raise InternalError(\n f\"Numeric type not implemented: {expr.wtype}\", expr.source_location\n )\n return f\"{expr.value}{suffix}\"\n\n @typing.override\n def visit_decimal_constant(self, expr: nodes.DecimalConstant) -> str:\n d = str(expr.value)\n if expr.wtype.n <= 64:\n suffix = f\"arc4u{expr.wtype.n}x{expr.wtype.m}\"\n else:\n suffix = f\"arc4n{expr.wtype.n}x{expr.wtype.m}\"\n return f\"{d}{suffix}\"\n\n @typing.override\n def visit_bool_constant(self, expr: nodes.BoolConstant) -> str:\n return \"true\" if expr.value else \"false\"\n\n @typing.override\n def visit_bytes_constant(self, expr: nodes.BytesConstant) -> str:\n match expr.encoding:\n case nodes.BytesEncoding.utf8:\n return _bytes_str(expr.value)\n case nodes.BytesEncoding.base32:\n return f'b32<\"{base64.b32encode(expr.value).decode(\"ascii\")}\">'\n case nodes.BytesEncoding.base64:\n return f'b64<\"{base64.b64encode(expr.value).decode(\"ascii\")}\">'\n case nodes.BytesEncoding.base16 | nodes.BytesEncoding.unknown:\n return f'hex<\"{expr.value.hex().upper()}\">'\n\n @typing.override\n def visit_string_constant(self, expr: nodes.StringConstant) -> str:\n return repr(expr.value)\n\n @typing.override\n def visit_void_constant(self, expr: nodes.VoidConstant) -> str:\n return \"void\"\n\n @typing.override\n def visit_method_constant(self, expr: nodes.MethodConstant) -> str:\n return f'Method(\"{expr.value}\")'\n\n @typing.override\n def visit_address_constant(self, expr: nodes.AddressConstant) -> str:\n return f'Address(\"{expr.value}\")'\n\n @typing.override\n def visit_compiled_contract(self, expr: nodes.CompiledContract) -> str:\n template_vars_fragment = self._template_vars_fragment(expr.prefix, expr.template_variables)\n overrides = \", \".join(\n f\"{k.name}={v.accept(self)}\" for k, v in expr.allocation_overrides.items()\n )\n return f\"compiled_contract({expr.contract},{overrides},{template_vars_fragment})\"\n\n @typing.override\n def visit_compiled_logicsig(self, expr: nodes.CompiledLogicSig) -> str:\n template_vars_fragment = self._template_vars_fragment(expr.prefix, expr.template_variables)\n return f\"compiled_logicsig({expr.logic_sig!r}{template_vars_fragment})\"\n\n def _template_vars_fragment(\n self, prefix: str | None, variables: Mapping[str, nodes.Expression]\n ) -> str:\n variables_str = \", \".join(f\"{k!r}: {v.accept(self)}\" for k, v in variables.items())\n return f\", {prefix=!r}, variables={{{variables_str}}}\"\n\n @typing.override\n def visit_conditional_expression(self, expr: nodes.ConditionalExpression) -> str:\n condition = expr.condition.accept(self)\n true = expr.true_expr.accept(self)\n false = expr.false_expr.accept(self)\n return f\"({condition}) ? ({true}) : ({false})\"\n\n @typing.override\n def visit_numeric_comparison_expression(self, expr: nodes.NumericComparisonExpression) -> str:\n return f\"{expr.lhs.accept(self)} {expr.operator.value} {expr.rhs.accept(self)}\"\n\n @typing.override\n def visit_var_expression(self, expr: nodes.VarExpression) -> str:\n return expr.name\n\n @typing.override\n def visit_checked_maybe(self, expr: nodes.CheckedMaybe) -> str:\n return f\"checked_maybe({expr.expr.accept(self)})\"\n\n @typing.override\n def visit_intrinsic_call(self, expr: nodes.IntrinsicCall) -> str:\n result = expr.op_code\n if expr.immediates:\n result += \"<\" + \", \".join([str(immediate) for immediate in expr.immediates]) + \">\"\n result += \"(\"\n if expr.stack_args:\n result += \", \".join([stack_arg.accept(self) for stack_arg in expr.stack_args])\n result += \")\"\n return result\n\n @typing.override\n def visit_puya_lib_call(self, expr: nodes.PuyaLibCall) -> str:\n result = expr.func.value.id\n result += \"(\"\n if expr.args:\n result += \", \".join(\n [(f\"{a.name}=\" if a.name else \"\") + a.value.accept(self) for a in expr.args]\n )\n result += \")\"\n return result\n\n @typing.override\n def visit_group_transaction_reference(self, ref: nodes.GroupTransactionReference) -> str:\n if ref.wtype.transaction_type is None:\n type_ = \"any\"\n else:\n type_ = ref.wtype.transaction_type.name\n return f\"group_transaction(index={ref.index.accept(self)}, type={type_})\"\n\n @typing.override\n def visit_create_inner_transaction(self, expr: nodes.CreateInnerTransaction) -> str:\n fields = []\n for field, value in expr.fields.items():\n fields.append(f\"{field.immediate}={value.accept(self)}\")\n return f\"create_inner_transaction({', '.join(fields)})\"\n\n @typing.override\n def visit_update_inner_transaction(self, expr: nodes.UpdateInnerTransaction) -> str:\n fields = []\n for field, value in expr.fields.items():\n fields.append(f\"{field.immediate}={value.accept(self)}\")\n return f\"update_inner_transaction({expr.itxn.accept(self)},{', '.join(fields)})\"\n\n @typing.override\n def visit_submit_inner_transaction(self, call: nodes.SubmitInnerTransaction) -> str:\n itxns = f'{\", \".join(itxn.accept(self) for itxn in call.itxns)}'\n return f\"submit_txn({itxns})\"\n\n @typing.override\n def visit_inner_transaction_field(self, itxn_field: nodes.InnerTransactionField) -> str:\n txn = itxn_field.itxn.accept(self)\n result = f\"{txn}.{itxn_field.field.immediate}\"\n if itxn_field.array_index is not None:\n index = itxn_field.array_index.accept(self)\n result = f\"{result}[{index}]\"\n return result\n\n @typing.override\n def visit_tuple_expression(self, expr: nodes.TupleExpression) -> str:\n items = \", \".join([item.accept(self) for item in expr.items])\n return f\"({items})\"\n\n @typing.override\n def visit_tuple_item_expression(self, expr: nodes.TupleItemExpression) -> str:\n base = expr.base.accept(self)\n return f\"{base}[{expr.index}]\"\n\n @typing.override\n def visit_field_expression(self, expr: nodes.FieldExpression) -> str:\n base = expr.base.accept(self)\n return f\"{base}.{expr.name}\"\n\n @typing.override\n def visit_index_expression(self, expr: nodes.IndexExpression) -> str:\n return f\"{expr.base.accept(self)}[{expr.index.accept(self)}]\"\n\n @typing.override\n def visit_slice_expression(self, expr: nodes.SliceExpression) -> str:\n start = expr.begin_index.accept(self) if expr.begin_index else \"\"\n stop = expr.end_index.accept(self) if expr.end_index else \"\"\n\n return f\"{expr.base.accept(self)}[{start}:{stop}]\"\n\n @typing.override\n def visit_intersection_slice_expression(self, expr: nodes.IntersectionSliceExpression) -> str:\n start = (\n expr.begin_index.accept(self)\n if isinstance(expr.begin_index, nodes.Expression)\n else (expr.begin_index if expr.begin_index is not None else \"\")\n )\n stop = (\n expr.end_index.accept(self)\n if isinstance(expr.end_index, nodes.Expression)\n else (expr.end_index if expr.end_index is not None else \"\")\n )\n\n return f\"{expr.base.accept(self)}[{start}:{stop}]\"\n\n @typing.override\n def visit_block(self, statement: nodes.Block) -> list[str]:\n statements = [line for statement in statement.body for line in statement.accept(self)]\n if statement.label:\n return [f\"{statement.label}:\", *statements]\n return statements\n\n @typing.override\n def visit_goto(self, statement: nodes.Goto) -> list[str]:\n return [f\"goto {statement.target}\"]\n\n @typing.override\n def visit_if_else(self, statement: nodes.IfElse) -> list[str]:\n if_branch = statement.if_branch.accept(self)\n if_block = [\n f\"if ({statement.condition.accept(self)}) {{\",\n *_indent(if_branch),\n ]\n if statement.else_branch is not None:\n else_branch = statement.else_branch.accept(self)\n else_block = [\"} else {\", *_indent(else_branch)]\n else:\n else_block = []\n return [*if_block, *else_block, \"}\"]\n\n @typing.override\n def visit_switch(self, statement: nodes.Switch) -> list[str]:\n match_block = [f\"switch ({statement.value.accept(self)}) {{\"]\n for case_value, case_block in statement.cases.items():\n value = case_value.accept(self)\n block = case_block.accept(self)\n match_block.extend(\n _indent(\n [\n f\"case {value}: {{\",\n *_indent(block),\n \"}\",\n ]\n )\n )\n if statement.default_case:\n default_block = statement.default_case.accept(self)\n match_block.extend(\n _indent(\n [\n \"case _: {\",\n *_indent(default_block),\n \"}\",\n ]\n )\n )\n match_block.append(\"}\")\n return match_block\n\n @typing.override\n def visit_while_loop(self, statement: nodes.WhileLoop) -> list[str]:\n loop_body = statement.loop_body.accept(self)\n return [\n f\"while ({statement.condition.accept(self)}) {{\",\n *_indent(loop_body),\n \"}\",\n ]\n\n @typing.override\n def visit_loop_exit(self, _statement: nodes.LoopExit) -> list[str]:\n return [\"break\"]\n\n @typing.override\n def visit_return_statement(self, statement: nodes.ReturnStatement) -> list[str]:\n if not statement.value:\n return [\"return\"]\n return [f\"return {statement.value.accept(self)}\"]\n\n @typing.override\n def visit_assert_expression(self, statement: nodes.AssertExpression) -> str:\n error_message = \"\" if statement.error_message is None else f'\"{statement.error_message}\"'\n if not statement.condition:\n result = \"err(\"\n if error_message:\n result += error_message\n result += \")\"\n else:\n result = f\"assert({statement.condition.accept(self)}\"\n if error_message:\n result += f\", comment={error_message}\"\n result += \")\"\n return result\n\n @typing.override\n def visit_loop_continue(self, _statement: nodes.LoopContinue) -> list[str]:\n return [\"continue\"]\n\n @typing.override\n def visit_expression_statement(self, statement: nodes.ExpressionStatement) -> list[str]:\n return [\n statement.expr.accept(self),\n ]\n\n @typing.override\n def visit_uint64_augmented_assignment(\n self, statement: nodes.UInt64AugmentedAssignment\n ) -> list[str]:\n return [\n f\"{statement.target.accept(self)} {statement.op.value}= {statement.value.accept(self)}\"\n ]\n\n @typing.override\n def visit_biguint_augmented_assignment(\n self, statement: nodes.BigUIntAugmentedAssignment\n ) -> list[str]:\n return [\n f\"{statement.target.accept(self)} {statement.op.value}= {statement.value.accept(self)}\"\n ]\n\n @typing.override\n def visit_state_get_ex(self, expr: nodes.StateGetEx) -> str:\n return f\"STATE_GET_EX({expr.field.accept(self)})\"\n\n @typing.override\n def visit_state_delete(self, statement: nodes.StateDelete) -> str:\n return f\"STATE_DELETE({statement.field.accept(self)})\"\n\n @typing.override\n def visit_state_get(self, expr: nodes.StateGet) -> str:\n return f\"STATE_GET({expr.field.accept(self)}, default={expr.default.accept(self)})\"\n\n @typing.override\n def visit_state_exists(self, expr: nodes.StateExists) -> str:\n return f\"STATE_EXISTS({expr.field.accept(self)})\"\n\n @typing.override\n def visit_template_var(self, expr: nodes.TemplateVar) -> str:\n return f\"TemplateVar[{expr.wtype}]({expr.name})\"\n\n @typing.override\n def visit_biguint_postfix_unary_operation(\n self, expr: nodes.BigUIntPostfixUnaryOperation\n ) -> str:\n return f\"{expr.target.accept(self)}{expr.op}\"\n\n @typing.override\n def visit_uint64_postfix_unary_operation(self, expr: nodes.UInt64PostfixUnaryOperation) -> str:\n return f\"{expr.target.accept(self)}{expr.op}\"\n\n @typing.override\n def visit_arc4_router(self, expr: nodes.ARC4Router) -> str:\n return \"arc4_router()\"\n\n @typing.override\n def visit_emit(self, expr: nodes.Emit) -> str:\n return f\"emit({expr.signature!r}, {expr.value.accept(self)})\"\n\n\ndef _indent(lines: Iterable[str], indent_size: str = \" \") -> Iterator[str]:\n yield from (f\"{indent_size}{line}\" for line in lines)\n\n\ndef _bytes_str(b: bytes) -> str:\n return repr(b)[1:]\n\n\ndef _collapse_sequential_ranges(nums: Iterable[int]) -> Iterable[str]:\n ranges = list[tuple[int, int]]()\n for num in sorted(nums):\n if ranges and num == ranges[-1][1] + 1:\n ranges[-1] = (ranges[-1][0], num)\n else:\n ranges.append((num, num))\n for start, stop in ranges:\n if start == stop:\n yield str(start)\n else:\n yield f\"{start}..{stop}\"\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/awst\/to_code_visitor.py","language":"Python","license":"NOASSERTION","size":25304} {"code":"# ruff: noqa: PIE796\nimport enum\nimport typing\n\nimport attrs\n\nfrom puya.avm import AVMType\nfrom puya.awst import wtypes\n\n__all__ = [\n \"TxnField\",\n]\n\n\n@attrs.frozen(eq=False, hash=False)\nclass _TxnFieldData:\n wtype: wtypes.WType\n num_values: int = attrs.field(default=1, validator=attrs.validators.ge(1), kw_only=True)\n is_inner_param: bool = attrs.field(default=True, kw_only=True)\n\n\n@enum.unique\nclass TxnField(enum.Enum):\n def __init__(self, data: _TxnFieldData):\n # _name_ is set by the EnumType metaclass during construction,\n # and refers to the class member name\n self.immediate: typing.Final = self._name_\n assert data.wtype.scalar_type is not None\n self.avm_type: typing.Final = data.wtype.scalar_type\n typing.assert_type(self.avm_type, typing.Literal[AVMType.uint64, AVMType.bytes])\n self.wtype: typing.Final = data.wtype\n self.num_values: typing.Final = data.num_values\n self.is_inner_param: typing.Final = data.is_inner_param\n\n @property\n def is_array(self) -> bool:\n return self.num_values > 1\n\n def valid_argument_type(self, wtype: wtypes.WType) -> bool:\n if not self.is_array:\n return wtype.scalar_type == self.avm_type\n else:\n return isinstance(wtype, wtypes.WTuple) and all(\n item_wtype.scalar_type == self.avm_type for item_wtype in wtype.types\n )\n\n def __repr__(self) -> str:\n return (\n f\"{type(self).__name__}(\"\n f\"immediate={self.immediate!r},\"\n f\" wtype={self.wtype},\"\n f\" num_values={self.num_values!r},\"\n f\" is_inner_param={self.is_inner_param!r}\"\n \")\"\n )\n\n Sender = _TxnFieldData(wtypes.account_wtype)\n Fee = _TxnFieldData(wtypes.uint64_wtype)\n FirstValid = _TxnFieldData(wtypes.uint64_wtype, is_inner_param=False)\n FirstValidTime = _TxnFieldData(wtypes.uint64_wtype, is_inner_param=False)\n LastValid = _TxnFieldData(wtypes.uint64_wtype, is_inner_param=False)\n Note = _TxnFieldData(wtypes.bytes_wtype)\n Lease = _TxnFieldData(wtypes.bytes_wtype, is_inner_param=False)\n Receiver = _TxnFieldData(wtypes.account_wtype)\n Amount = _TxnFieldData(wtypes.uint64_wtype)\n CloseRemainderTo = _TxnFieldData(wtypes.account_wtype)\n VotePK = _TxnFieldData(wtypes.bytes_wtype)\n SelectionPK = _TxnFieldData(wtypes.bytes_wtype)\n VoteFirst = _TxnFieldData(wtypes.uint64_wtype)\n VoteLast = _TxnFieldData(wtypes.uint64_wtype)\n VoteKeyDilution = _TxnFieldData(wtypes.uint64_wtype)\n Type = _TxnFieldData(wtypes.bytes_wtype)\n TypeEnum = _TxnFieldData(wtypes.uint64_wtype)\n XferAsset = _TxnFieldData(wtypes.asset_wtype)\n AssetAmount = _TxnFieldData(wtypes.uint64_wtype)\n AssetSender = _TxnFieldData(wtypes.account_wtype)\n AssetReceiver = _TxnFieldData(wtypes.account_wtype)\n AssetCloseTo = _TxnFieldData(wtypes.account_wtype)\n GroupIndex = _TxnFieldData(wtypes.uint64_wtype, is_inner_param=False)\n TxID = _TxnFieldData(wtypes.bytes_wtype, is_inner_param=False)\n # v2\n ApplicationID = _TxnFieldData(wtypes.application_wtype)\n OnCompletion = _TxnFieldData(wtypes.uint64_wtype)\n NumAppArgs = _TxnFieldData(wtypes.uint64_wtype, is_inner_param=False)\n NumAccounts = _TxnFieldData(wtypes.uint64_wtype, is_inner_param=False)\n ApprovalProgram = _TxnFieldData(wtypes.bytes_wtype)\n ClearStateProgram = _TxnFieldData(wtypes.bytes_wtype)\n RekeyTo = _TxnFieldData(wtypes.account_wtype)\n ConfigAsset = _TxnFieldData(wtypes.asset_wtype)\n ConfigAssetTotal = _TxnFieldData(wtypes.uint64_wtype)\n ConfigAssetDecimals = _TxnFieldData(wtypes.uint64_wtype)\n ConfigAssetDefaultFrozen = _TxnFieldData(wtypes.bool_wtype)\n ConfigAssetUnitName = _TxnFieldData(wtypes.bytes_wtype)\n ConfigAssetName = _TxnFieldData(wtypes.bytes_wtype)\n ConfigAssetURL = _TxnFieldData(wtypes.bytes_wtype)\n ConfigAssetMetadataHash = _TxnFieldData(wtypes.bytes_wtype)\n ConfigAssetManager = _TxnFieldData(wtypes.account_wtype)\n ConfigAssetReserve = _TxnFieldData(wtypes.account_wtype)\n ConfigAssetFreeze = _TxnFieldData(wtypes.account_wtype)\n ConfigAssetClawback = _TxnFieldData(wtypes.account_wtype)\n FreezeAsset = _TxnFieldData(wtypes.asset_wtype)\n FreezeAssetAccount = _TxnFieldData(wtypes.account_wtype)\n FreezeAssetFrozen = _TxnFieldData(wtypes.bool_wtype)\n # v3\n NumAssets = _TxnFieldData(wtypes.uint64_wtype, is_inner_param=False)\n NumApplications = _TxnFieldData(wtypes.uint64_wtype, is_inner_param=False)\n GlobalNumUint = _TxnFieldData(wtypes.uint64_wtype)\n GlobalNumByteSlice = _TxnFieldData(wtypes.uint64_wtype)\n LocalNumUint = _TxnFieldData(wtypes.uint64_wtype)\n LocalNumByteSlice = _TxnFieldData(wtypes.uint64_wtype)\n # v4\n ExtraProgramPages = _TxnFieldData(wtypes.uint64_wtype)\n # v5\n Nonparticipation = _TxnFieldData(wtypes.bool_wtype)\n NumLogs = _TxnFieldData(wtypes.uint64_wtype, is_inner_param=False)\n CreatedAssetID = _TxnFieldData(wtypes.asset_wtype, is_inner_param=False)\n CreatedApplicationID = _TxnFieldData(wtypes.application_wtype, is_inner_param=False)\n # v6\n LastLog = _TxnFieldData(wtypes.bytes_wtype, is_inner_param=False)\n StateProofPK = _TxnFieldData(wtypes.bytes_wtype)\n # v7\n NumApprovalProgramPages = _TxnFieldData(wtypes.uint64_wtype, is_inner_param=False)\n NumClearStateProgramPages = _TxnFieldData(wtypes.uint64_wtype, is_inner_param=False)\n # array fields\n # TODO: allow configuring as these are consensus values\n # v2\n ApplicationArgs = _TxnFieldData(wtypes.bytes_wtype, num_values=16)\n Accounts = _TxnFieldData(wtypes.account_wtype, num_values=4)\n # v3\n Assets = _TxnFieldData(wtypes.asset_wtype, num_values=8)\n Applications = _TxnFieldData(wtypes.application_wtype, num_values=8)\n # v5\n Logs = _TxnFieldData(wtypes.bytes_wtype, num_values=32, is_inner_param=False)\n # v7\n ApprovalProgramPages = _TxnFieldData(wtypes.bytes_wtype, num_values=4)\n ClearStateProgramPages = _TxnFieldData(wtypes.bytes_wtype, num_values=4)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/awst\/txn_fields.py","language":"Python","license":"NOASSERTION","size":6085} {"code":"","repo_name":"algorandfoundation\/puya","path":"src\/puya\/awst\/validation\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"from collections.abc import Iterator\n\nimport attrs\n\nfrom puya import log\nfrom puya.awst import (\n nodes as awst_nodes,\n wtypes,\n)\nfrom puya.awst.awst_traverser import AWSTTraverser\n\nlogger = log.get_logger(__name__)\n\n\nclass ARC4CopyValidator(AWSTTraverser):\n @classmethod\n def validate(cls, module: awst_nodes.AWST) -> None:\n validator = cls()\n for module_statement in module:\n module_statement.accept(validator)\n\n def __init__(self) -> None:\n super().__init__()\n self._for_items: awst_nodes.Lvalue | None = None\n\n # for nodes that can't modify the input don't need to check for copies unless an assignment\n # expression is being used\n def visit_submit_inner_transaction(self, call: awst_nodes.SubmitInnerTransaction) -> None:\n if _HasAssignmentVisitor.check(call):\n super().visit_submit_inner_transaction(call)\n\n def visit_intrinsic_call(self, call: awst_nodes.IntrinsicCall) -> None:\n if _HasAssignmentVisitor.check(call):\n super().visit_intrinsic_call(call)\n\n def visit_emit(self, emit: awst_nodes.Emit) -> None:\n if _HasAssignmentVisitor.check(emit):\n super().visit_emit(emit)\n\n def visit_assert_expression(self, expr: awst_nodes.AssertExpression) -> None:\n if expr.condition and _HasAssignmentVisitor.check(expr.condition):\n super().visit_assert_expression(expr)\n\n def visit_assignment_statement(self, statement: awst_nodes.AssignmentStatement) -> None:\n _check_assignment(statement.target, statement.value)\n statement.value.accept(self)\n\n def visit_tuple_expression(self, expr: awst_nodes.TupleExpression) -> None:\n super().visit_tuple_expression(expr)\n if expr is not self._for_items:\n for item in expr.items:\n _check_for_arc4_copy(item, \"being passed to a tuple expression\")\n\n def visit_for_in_loop(self, statement: awst_nodes.ForInLoop) -> None:\n # statement.items is immediately checked before entering the for body\n # so don't need to worry about preserving _for_items through multiple loops\n self._for_items = statement.items\n super().visit_for_in_loop(statement)\n self._for_items = None\n\n # looping is essentially assigning so check sequence\n sequence = statement.sequence\n while isinstance(sequence, awst_nodes.Enumeration | awst_nodes.Reversed):\n sequence = sequence.expr\n if ( # mutable tuples cannot be iterated in a semantically correct way\n isinstance(sequence.wtype, wtypes.WTuple)\n and _is_referable_expression(sequence)\n and _is_arc4_mutable(sequence.wtype)\n ):\n logger.error(\n \"tuple of mutable ARC4 values cannot be iterated\",\n location=sequence.source_location,\n )\n elif ( # arrays of mutable types, must be modified and iterated by index\n isinstance(sequence.wtype, wtypes.ARC4Array)\n and _is_referable_expression(sequence)\n and _is_arc4_mutable(sequence.wtype.element_type)\n ):\n logger.error(\n \"cannot directly iterate an ARC4 array of mutable objects,\"\n \" construct a for-loop over the indexes instead\",\n location=sequence.source_location,\n )\n\n def visit_assignment_expression(self, expr: awst_nodes.AssignmentExpression) -> None:\n _check_assignment(expr.target, expr.value)\n expr.value.accept(self)\n\n def visit_subroutine_call_expression(self, expr: awst_nodes.SubroutineCallExpression) -> None:\n for arg_ in expr.args:\n for arg in _expand_tuple_items(arg_.value):\n match arg:\n case awst_nodes.VarExpression():\n # Var expressions don't need copy as we implicitly return the latest value\n # and update the var\n continue\n case awst_nodes.AppStateExpression() | awst_nodes.AppAccountStateExpression():\n message = \"being passed to a subroutine from state\"\n case _:\n message = \"being passed to a subroutine\"\n _check_for_arc4_copy(arg, message)\n\n def visit_new_array(self, expr: awst_nodes.NewArray) -> None:\n super().visit_new_array(expr)\n if isinstance(expr.wtype, wtypes.ARC4Array):\n for v in expr.values:\n _check_for_arc4_copy(v, \"being passed to an array constructor\")\n\n def visit_new_struct(self, expr: awst_nodes.NewStruct) -> None:\n super().visit_new_struct(expr)\n if isinstance(expr.wtype, wtypes.ARC4Struct):\n for v in expr.values.values():\n _check_for_arc4_copy(v, \"being passed to a struct constructor\")\n\n def visit_arc4_encode(self, expr: awst_nodes.ARC4Encode) -> None:\n super().visit_arc4_encode(expr)\n\n for item in _expand_tuple_items(expr.value):\n _check_for_arc4_copy(item, \"being passed to a constructor\")\n\n\ndef _is_referable_expression(expr: awst_nodes.Expression) -> bool:\n \"\"\"\n Returns True if expr represents something that can be referenced multiple times.\n \"\"\"\n match expr:\n case (\n awst_nodes.VarExpression()\n | awst_nodes.AppStateExpression()\n | awst_nodes.AppAccountStateExpression()\n | awst_nodes.StateGet()\n | awst_nodes.StateGetEx()\n | awst_nodes.BoxValueExpression()\n ):\n return True\n case (\n awst_nodes.IndexExpression(base=base_expr)\n | awst_nodes.TupleItemExpression(base=base_expr)\n | awst_nodes.FieldExpression(base=base_expr)\n ):\n return _is_referable_expression(base_expr)\n return False\n\n\ndef _check_assignment(target: awst_nodes.Expression, value: awst_nodes.Expression) -> None:\n if not isinstance(target, awst_nodes.TupleExpression):\n _check_for_arc4_copy(value, \"being assigned to another variable\")\n elif _is_referable_expression(value) and any(_is_arc4_mutable(i) for i in target.wtype.types):\n logger.error(\n \"tuples containing a mutable reference to an ARC4-encoded value cannot be unpacked,\"\n \" use index access instead\",\n location=value.source_location,\n )\n\n\ndef _check_for_arc4_copy(expr: awst_nodes.Expression, context_desc: str) -> None:\n if _is_arc4_mutable(expr.wtype) and _is_referable_expression(expr):\n logger.error(\n \"mutable reference to ARC4-encoded value\"\n f\" must be copied using .copy() when {context_desc}\",\n location=expr.source_location,\n )\n\n\ndef _expand_tuple_items(expr: awst_nodes.Expression) -> Iterator[awst_nodes.Expression]:\n match expr:\n case awst_nodes.TupleExpression(items=items):\n for item in items:\n yield from _expand_tuple_items(item)\n case _:\n yield expr\n\n\ndef _is_arc4_mutable(wtype: wtypes.WType) -> bool:\n \"\"\"\n Returns True if expr represents an arc4 type that is mutable\n \"\"\"\n match wtype:\n case wtypes.ARC4Type(immutable=False):\n return True\n case wtypes.WTuple(types=types):\n return any(_is_arc4_mutable(t) for t in types)\n return False\n\n\n@attrs.define\nclass _HasAssignmentVisitor(AWSTTraverser):\n has_assignment: bool = False\n\n @classmethod\n def check(cls, expr: awst_nodes.Expression) -> bool:\n visitor = _HasAssignmentVisitor()\n expr.accept(visitor)\n return visitor.has_assignment\n\n def visit_assignment_expression(self, _: awst_nodes.AssignmentExpression) -> None:\n self.has_assignment = True\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/awst\/validation\/arc4_copy.py","language":"Python","license":"NOASSERTION","size":7770} {"code":"import contextlib\nimport typing\nfrom collections.abc import Iterator\n\nfrom puya import log\nfrom puya.awst import nodes as awst_nodes\nfrom puya.awst.awst_traverser import AWSTTraverser\nfrom puya.awst.nodes import (\n ContractMethodTarget,\n InstanceMethodTarget,\n InstanceSuperMethodTarget,\n SubroutineID,\n)\n\nlogger = log.get_logger(__name__)\n\n\nclass BaseInvokerValidator(AWSTTraverser):\n def __init__(self) -> None:\n self._contract: awst_nodes.Contract | None = None\n\n @property\n def contract(self) -> awst_nodes.Contract | None:\n return self._contract\n\n @contextlib.contextmanager\n def _enter_contract(self, contract: awst_nodes.Contract) -> Iterator[None]:\n assert self._contract is None\n self._contract = contract\n try:\n yield\n finally:\n self._contract = None\n\n @classmethod\n def validate(cls, module: awst_nodes.AWST) -> None:\n validator = cls()\n for module_statement in module:\n module_statement.accept(validator)\n\n @typing.override\n def visit_contract(self, statement: awst_nodes.Contract) -> None:\n with self._enter_contract(statement):\n super().visit_contract(statement)\n\n @typing.override\n def visit_subroutine_call_expression(self, expr: awst_nodes.SubroutineCallExpression) -> None:\n super().visit_subroutine_call_expression(expr)\n match expr.target:\n case SubroutineID():\n # always okay\n pass\n case InstanceMethodTarget() | InstanceSuperMethodTarget():\n if self.contract is None:\n logger.error(\n \"invocation of instance method outside of a contract method\",\n location=expr.source_location,\n )\n case ContractMethodTarget(cref=target_class):\n caller_class = self.contract\n if caller_class is None:\n logger.error(\n \"invocation of contract method outside of a contract method\",\n location=expr.source_location,\n )\n else:\n caller_ref = caller_class.id\n if (\n target_class != caller_ref\n and target_class not in caller_class.method_resolution_order\n ):\n logger.error(\n \"invocation of a contract method outside of current hierarchy\",\n location=expr.source_location,\n )\n case invalid:\n typing.assert_never(invalid)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/awst\/validation\/base_invoker.py","language":"Python","license":"NOASSERTION","size":2702} {"code":"from puya import log\nfrom puya.awst import nodes as awst_nodes\nfrom puya.awst.awst_traverser import AWSTTraverser\n\nlogger = log.get_logger(__name__)\n\n\nclass ImmutableValidator(AWSTTraverser):\n @classmethod\n def validate(cls, module: awst_nodes.AWST) -> None:\n validator = cls()\n for module_statement in module:\n module_statement.accept(validator)\n\n def visit_assignment_expression(self, expr: awst_nodes.AssignmentExpression) -> None:\n super().visit_assignment_expression(expr)\n _validate_lvalue(expr.target)\n\n def visit_assignment_statement(self, statement: awst_nodes.AssignmentStatement) -> None:\n super().visit_assignment_statement(statement)\n _validate_lvalue(statement.target)\n\n def visit_array_pop(self, expr: awst_nodes.ArrayPop) -> None:\n super().visit_array_pop(expr)\n if expr.base.wtype.immutable:\n logger.error(\n \"cannot modify - object is immutable\",\n location=expr.source_location,\n )\n\n def visit_array_extend(self, expr: awst_nodes.ArrayExtend) -> None:\n super().visit_array_extend(expr)\n if expr.base.wtype.immutable:\n logger.error(\n \"cannot modify - object is immutable\",\n location=expr.source_location,\n )\n\n\ndef _validate_lvalue(lvalue: awst_nodes.Expression) -> None:\n if isinstance(lvalue, awst_nodes.FieldExpression | awst_nodes.IndexExpression):\n if lvalue.base.wtype.immutable:\n logger.error(\n \"expression is not valid as an assignment target - object is immutable\",\n location=lvalue.source_location,\n )\n elif isinstance(lvalue, awst_nodes.TupleExpression):\n for item in lvalue.items:\n _validate_lvalue(item)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/awst\/validation\/immutable.py","language":"Python","license":"NOASSERTION","size":1818} {"code":"import contextlib\nfrom collections.abc import Iterator\n\nfrom puya import log\nfrom puya.awst import (\n nodes as awst_nodes,\n wtypes,\n)\nfrom puya.awst.awst_traverser import AWSTTraverser\nfrom puya.awst.wtypes import WInnerTransaction, WInnerTransactionFields\nfrom puya.parse import SourceLocation\n\nlogger = log.get_logger(__name__)\n\nINNER_TRANSACTION_ASSIGNMENT_EXPRESSION_ERROR = (\n \"inner transactions cannot be used in assignment expressions\"\n)\nINNER_TRANSACTION_COPY_REQUIRED_ERROR = (\n \"inner transaction fields must be copied using .copy() when assigning to a new local\"\n)\nINNER_TRANSACTION_LOOP_MODIFICATION_ERROR = (\n \"inner transaction fields cannot be modified after submission while in a loop\"\n)\nINNER_TRANSACTION_MAYBE_STALE_ERROR = (\n \"inner transaction array field can not be reliably accessed due to other inner transaction \"\n \" submissions or subroutine calls, move array field access closer to {stale_var!r} definition\"\n)\nINNER_TRANSACTION_MAYBE_STALE_WARNING = (\n \"inner transaction {stale_var!r} potentially becomes stale here\"\n)\nINNER_TRANSACTION_SOURCE_ERROR = \"inner transactions can not be used like this\"\nINNER_TRANSACTION_SUBROUTINE_ERROR = (\n \"inner transactions cannot be used as a subroutine argument or return value\"\n)\n\n\nclass InnerTransactionsValidator(AWSTTraverser):\n \"\"\"\n Validates that expressions of type WInnerTransaction and WInnerTransactionFields are only\n used in the ways currently supported. Emits errors for:\n\n Reassigning expressions of type WInnerTransaction\n Reassigning expressions of type WInnerTransactionFields without a copy()\n Using WInnerTransaction or WInnerTransactionFields in a subroutine or assignment expression\n \"\"\"\n\n @classmethod\n def validate(cls, module: awst_nodes.AWST) -> None:\n for module_statement in module:\n validator = cls()\n module_statement.accept(validator)\n\n def visit_contract_method(self, statement: awst_nodes.ContractMethod) -> None:\n _check_method_types(statement)\n super().visit_contract_method(statement)\n\n def visit_subroutine(self, statement: awst_nodes.Subroutine) -> None:\n _check_method_types(statement)\n super().visit_subroutine(statement)\n\n def visit_assignment_statement(self, statement: awst_nodes.AssignmentStatement) -> None:\n self._check_inner_transaction_assignment(statement.value)\n self._check_inner_transaction_fields_assignment(statement.value)\n super().visit_assignment_statement(statement)\n\n def _check_inner_transaction_assignment(self, value: awst_nodes.Expression) -> None:\n if _is_itxn_wtype(value.wtype) and not _is_assignable_itxn_expr(value):\n logger.error(INNER_TRANSACTION_SOURCE_ERROR, location=value.source_location)\n\n def _check_inner_transaction_fields_assignment(self, value: awst_nodes.Expression) -> None:\n match value:\n case awst_nodes.CreateInnerTransaction() | awst_nodes.Copy():\n pass # ok\n case (\n awst_nodes.VarExpression(wtype=wtype)\n | awst_nodes.TupleItemExpression(wtype=wtype)\n ) if isinstance(wtype, WInnerTransactionFields):\n logger.error(\n INNER_TRANSACTION_COPY_REQUIRED_ERROR,\n location=value.source_location,\n )\n case awst_nodes.Expression(wtype=wtype) if (\n isinstance(wtype, WInnerTransactionFields)\n ):\n logger.error(\n INNER_TRANSACTION_SOURCE_ERROR,\n location=value.source_location,\n )\n\n def visit_assignment_expression(self, expr: awst_nodes.AssignmentExpression) -> None:\n super().visit_assignment_expression(expr)\n if _is_either_itxn_wtype(expr.wtype):\n logger.error(\n INNER_TRANSACTION_ASSIGNMENT_EXPRESSION_ERROR,\n location=expr.source_location,\n )\n\n def visit_subroutine_call_expression(self, expr: awst_nodes.SubroutineCallExpression) -> None:\n super().visit_subroutine_call_expression(expr)\n for arg in expr.args:\n if _is_either_itxn_wtype(arg.value.wtype):\n logger.error(\n INNER_TRANSACTION_SUBROUTINE_ERROR,\n location=expr.source_location,\n )\n\n\nclass InnerTransactionUsedInALoopValidator(AWSTTraverser):\n \"\"\"\n Validates that expressions of type WInnerTransactionFields are not modified after submission\n while in a loop\n Modifying after submission while in a loop\n \"\"\"\n\n def __init__(self) -> None:\n super().__init__()\n self._current_itxn_var_stack = list[list[str]]()\n\n @classmethod\n def validate(cls, module: awst_nodes.AWST) -> None:\n for module_statement in module:\n validator = cls()\n module_statement.accept(validator)\n\n @property\n def _current_loop_itxn_vars(self) -> list[str] | None:\n return self._current_itxn_var_stack[-1] if self._current_itxn_var_stack else None\n\n @contextlib.contextmanager\n def _enter_loop(self) -> Iterator[None]:\n self._current_itxn_var_stack.append(\n self._current_loop_itxn_vars.copy() if self._current_loop_itxn_vars else []\n )\n try:\n yield\n finally:\n self._current_itxn_var_stack.pop()\n\n def visit_for_in_loop(self, statement: awst_nodes.ForInLoop) -> None:\n with self._enter_loop():\n super().visit_for_in_loop(statement)\n\n def visit_while_loop(self, statement: awst_nodes.WhileLoop) -> None:\n with self._enter_loop():\n super().visit_while_loop(statement)\n\n def visit_assignment_statement(self, statement: awst_nodes.AssignmentStatement) -> None:\n value = statement.value\n match value:\n case awst_nodes.CreateInnerTransaction() | awst_nodes.Copy():\n self._check_itxn_params_not_submitted_in_loop(statement.target)\n super().visit_assignment_statement(statement)\n\n def visit_submit_inner_transaction(self, call: awst_nodes.SubmitInnerTransaction) -> None:\n if self._current_loop_itxn_vars is not None:\n for itxn_params in call.itxns:\n match itxn_params:\n case awst_nodes.TupleItemExpression(\n base=awst_nodes.VarExpression(name=var_name)\n ):\n self._current_loop_itxn_vars.append(var_name)\n case awst_nodes.VarExpression(name=var_name):\n self._current_loop_itxn_vars.append(var_name)\n super().visit_submit_inner_transaction(call)\n\n def visit_update_inner_transaction(self, call: awst_nodes.UpdateInnerTransaction) -> None:\n super().visit_update_inner_transaction(call)\n self._check_itxn_params_not_submitted_in_loop(call.itxn)\n\n def _check_itxn_params_not_submitted_in_loop(self, expr: awst_nodes.Expression) -> None:\n if (\n self._current_loop_itxn_vars\n and isinstance(expr, awst_nodes.VarExpression)\n and expr.name in self._current_loop_itxn_vars\n ):\n logger.error(\n INNER_TRANSACTION_LOOP_MODIFICATION_ERROR,\n location=expr.source_location,\n )\n\n\ndef _check_method_types(stmt: awst_nodes.Function) -> None:\n for arg in stmt.args:\n if _is_either_itxn_wtype(arg.wtype):\n logger.error(\n INNER_TRANSACTION_SUBROUTINE_ERROR,\n location=arg.source_location,\n )\n if _is_either_itxn_wtype(stmt.return_type):\n logger.error(\n INNER_TRANSACTION_SUBROUTINE_ERROR,\n location=stmt.source_location,\n )\n\n\ndef _is_assignable_itxn_expr(expr: awst_nodes.Expression) -> bool:\n if not _is_itxn_wtype(expr.wtype): # non itxn expressions are assignable\n return True\n match expr:\n case awst_nodes.VarExpression(): # local itxn expressions can be copied\n return True\n case awst_nodes.SubmitInnerTransaction(): # submit expressions are assignable\n return True\n case awst_nodes.TupleExpression(\n items=items\n ): # tuple expressions composed of assignable expressions are assignable\n return all(map(_is_assignable_itxn_expr, items))\n case awst_nodes.TupleItemExpression(\n base=base\n ): # tuple items are assignable if their base is assignable\n return _is_assignable_itxn_expr(base)\n case awst_nodes.SingleEvaluation(source=source):\n return _is_assignable_itxn_expr(source)\n case awst_nodes.SliceExpression(\n base=base, wtype=wtypes.WTuple()\n ): # tuple slices can be assigned if base can be\n return _is_assignable_itxn_expr(base)\n # anything else is not considered assignable\n return False\n\n\ndef _is_either_itxn_wtype(wtype: wtypes.WType) -> bool:\n return _is_itxn_wtype(wtype) or _is_itxn_fields_wtype(wtype)\n\n\ndef _is_itxn_wtype(wtype: wtypes.WType) -> bool:\n return isinstance(wtype, WInnerTransaction) or (\n isinstance(wtype, wtypes.WTuple) and any(map(_is_itxn_wtype, wtype.types))\n )\n\n\ndef _is_itxn_fields_wtype(wtype: wtypes.WType) -> bool:\n return isinstance(wtype, WInnerTransactionFields) or (\n isinstance(wtype, wtypes.WTuple) and any(map(_is_itxn_fields_wtype, wtype.types))\n )\n\n\nclass StaleInnerTransactionsValidator(AWSTTraverser):\n \"\"\"Validates that inner transaction array access are not stale\"\"\"\n\n @classmethod\n def validate(cls, module: awst_nodes.AWST) -> None:\n for module_statement in module:\n validator = cls()\n module_statement.accept(validator)\n\n def __init__(self) -> None:\n super().__init__()\n self._maybe_stale_itxn_vars = dict[str, SourceLocation]()\n self._active_itxn_vars = list[str]()\n\n def visit_assignment_statement(self, stmt: awst_nodes.AssignmentStatement) -> None:\n super().visit_assignment_statement(stmt)\n match stmt.value:\n case awst_nodes.SubmitInnerTransaction():\n new_itxn_var_names = self._get_var_names(stmt.target)\n self._update_active_var_names(new_itxn_var_names)\n case awst_nodes.TupleExpression(items=items) if any(\n isinstance(item.wtype, WInnerTransaction) for item in items\n ):\n var_names = self._get_var_names(stmt.target)\n self._update_active_var_names(var_names)\n\n def visit_intrinsic_call(self, call: awst_nodes.IntrinsicCall) -> None:\n super().visit_intrinsic_call(call)\n if call.op_code == \"itxn_submit\":\n self._update_maybe_stale_itxn_vars(call.source_location)\n\n def visit_submit_inner_transaction(self, call: awst_nodes.SubmitInnerTransaction) -> None:\n super().visit_submit_inner_transaction(call)\n self._update_maybe_stale_itxn_vars(call.source_location)\n\n def visit_inner_transaction_field(self, itxn_field: awst_nodes.InnerTransactionField) -> None:\n super().visit_inner_transaction_field(itxn_field)\n match itxn_field.itxn:\n case awst_nodes.VarExpression(name=stale_var):\n pass\n case awst_nodes.TupleItemExpression(base=awst_nodes.VarExpression(name=stale_var)):\n pass\n case _:\n return\n if itxn_field.field.is_array:\n try:\n stale_var_loc = self._maybe_stale_itxn_vars[stale_var]\n except KeyError:\n return\n logger.error(\n INNER_TRANSACTION_MAYBE_STALE_ERROR.format(stale_var=stale_var),\n location=itxn_field.itxn.source_location,\n )\n logger.warning(\n INNER_TRANSACTION_MAYBE_STALE_WARNING.format(stale_var=stale_var),\n location=stale_var_loc,\n )\n\n def visit_subroutine_call_expression(self, expr: awst_nodes.SubroutineCallExpression) -> None:\n super().visit_subroutine_call_expression(expr)\n self._update_maybe_stale_itxn_vars(expr.source_location)\n\n def _get_var_names(self, expr: awst_nodes.Expression) -> list[str]:\n match expr:\n case awst_nodes.VarExpression(name=name):\n return [name]\n case awst_nodes.TupleExpression(items=items):\n return [self._get_var_names(item)[0] for item in items]\n case _:\n return []\n\n def _update_active_var_names(self, var_names: list[str]) -> None:\n self._active_itxn_vars = var_names\n # if a var_name is reassigned then it is not considered stale\n for var_name in self._active_itxn_vars:\n with contextlib.suppress(KeyError):\n del self._maybe_stale_itxn_vars[var_name]\n\n def _update_maybe_stale_itxn_vars(self, staling_expr_loc: SourceLocation) -> None:\n for stale_var_name in self._active_itxn_vars:\n self._maybe_stale_itxn_vars[stale_var_name] = staling_expr_loc\n self._active_itxn_vars = []\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/awst\/validation\/inner_transactions.py","language":"Python","license":"NOASSERTION","size":13153} {"code":"from collections import defaultdict\n\nfrom puya import log\nfrom puya.awst import nodes as awst_nodes\nfrom puya.awst.function_traverser import FunctionTraverser\n\nlogger = log.get_logger(__name__)\n\n\nclass LabelsValidator(FunctionTraverser):\n @classmethod\n def validate(cls, module: awst_nodes.AWST) -> None:\n for module_statement in module:\n if isinstance(module_statement, awst_nodes.Subroutine):\n cls(module_statement)\n elif isinstance(module_statement, awst_nodes.Contract):\n for method in module_statement.all_methods:\n cls(method)\n\n def __init__(self, function: awst_nodes.Function) -> None:\n self._labelled_blocks = dict[awst_nodes.Label, awst_nodes.Block]()\n self._seen_targets = defaultdict[awst_nodes.Label, list[awst_nodes.Goto]](list)\n function.body.accept(self)\n for target, goto_list in self._seen_targets.items():\n if target not in self._labelled_blocks:\n for goto in goto_list:\n logger.error(\n f\"label target {target} does not exist\", location=goto.source_location\n )\n\n def visit_goto(self, goto: awst_nodes.Goto) -> None:\n self._seen_targets[goto.target].append(goto)\n\n def visit_block(self, block: awst_nodes.Block) -> None:\n if block.label is not None:\n first_seen = self._labelled_blocks.setdefault(block.label, block)\n if block is not first_seen:\n logger.error(\n f\"block has duplicate label {block.label}\", location=block.source_location\n )\n logger.info(\"label first seen here\", location=first_seen.source_location)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/awst\/validation\/labels.py","language":"Python","license":"NOASSERTION","size":1741} {"code":"from puya.awst import nodes as awst_nodes\nfrom puya.awst.validation.arc4_copy import ARC4CopyValidator\nfrom puya.awst.validation.base_invoker import BaseInvokerValidator\nfrom puya.awst.validation.immutable import ImmutableValidator\nfrom puya.awst.validation.inner_transactions import (\n InnerTransactionsValidator,\n InnerTransactionUsedInALoopValidator,\n StaleInnerTransactionsValidator,\n)\nfrom puya.awst.validation.labels import LabelsValidator\nfrom puya.awst.validation.scratch_slots import ScratchSlotReservationValidator\nfrom puya.awst.validation.storage import StorageTypesValidator\n\n\ndef validate_awst(module: awst_nodes.AWST) -> None:\n ARC4CopyValidator.validate(module)\n ScratchSlotReservationValidator.validate(module)\n InnerTransactionsValidator.validate(module)\n InnerTransactionUsedInALoopValidator.validate(module)\n StaleInnerTransactionsValidator.validate(module)\n BaseInvokerValidator.validate(module)\n StorageTypesValidator.validate(module)\n LabelsValidator.validate(module)\n ImmutableValidator.validate(module)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/awst\/validation\/main.py","language":"Python","license":"NOASSERTION","size":1064} {"code":"from collections.abc import Collection, Iterator\n\nfrom puya import log\nfrom puya.awst import nodes as awst_nodes\nfrom puya.awst.awst_traverser import AWSTTraverser\nfrom puya.parse import SourceLocation\n\nlogger = log.get_logger(__name__)\n\n\nclass ScratchSlotReservationValidator(AWSTTraverser):\n @classmethod\n def validate(cls, module: awst_nodes.AWST) -> None:\n for module_statement in module:\n validator = cls()\n module_statement.accept(validator)\n for slot, loc in validator.invalid_slot_usages:\n logger.error(\n f\"Scratch slot {slot} has not been reserved.\",\n location=loc,\n )\n\n def __init__(self) -> None:\n super().__init__()\n self._reserved_slots: Collection[int] = ()\n self._used_slots = list[tuple[int, SourceLocation]]()\n\n @property\n def invalid_slot_usages(self) -> Iterator[tuple[int, SourceLocation]]:\n for slot, loc in self._used_slots:\n if slot not in self._reserved_slots:\n yield slot, loc\n\n def visit_contract(self, statement: awst_nodes.Contract) -> None:\n super().visit_contract(statement)\n self._reserved_slots = statement.reserved_scratch_space\n\n def visit_intrinsic_call(self, call: awst_nodes.IntrinsicCall) -> None:\n super().visit_intrinsic_call(call)\n match call.op_code, call.stack_args:\n case \"loads\", [awst_nodes.IntegerConstant(value=slot, source_location=loc)]:\n self._used_slots.append((slot, loc))\n case \"stores\", [awst_nodes.IntegerConstant(value=slot, source_location=loc), *_]:\n self._used_slots.append((slot, loc))\n match call.op_code, call.immediates:\n case \"load\", [int(slot)]:\n self._used_slots.append((slot, call.source_location))\n case \"store\", [int(slot)]:\n self._used_slots.append((slot, call.source_location))\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/awst\/validation\/scratch_slots.py","language":"Python","license":"NOASSERTION","size":1972} {"code":"import typing\nfrom collections import defaultdict\n\nfrom puya import log\nfrom puya.awst import (\n nodes as awst_nodes,\n wtypes,\n)\nfrom puya.awst.awst_traverser import AWSTTraverser\nfrom puya.awst.nodes import AppStorageKind\nfrom puya.utils import set_add\n\nlogger = log.get_logger(__name__)\n\n\nclass StorageTypesValidator(AWSTTraverser):\n @classmethod\n def validate(cls, module: awst_nodes.AWST) -> None:\n for module_statement in module:\n # create a new instance for each top level construct,\n # either subroutine or contract class, so that we can de-dupe\n # messages (where possible) there\n validator = cls()\n module_statement.accept(validator)\n\n def __init__(self) -> None:\n super().__init__()\n self._seen_keys = defaultdict[AppStorageKind, set[bytes]](set)\n\n @typing.override\n def visit_app_storage_definition(self, defn: awst_nodes.AppStorageDefinition) -> None:\n super().visit_app_storage_definition(defn)\n wtypes.validate_persistable(defn.storage_wtype, defn.source_location)\n if defn.key_wtype is not None:\n wtypes.validate_persistable(defn.key_wtype, defn.source_location)\n\n @typing.override\n def visit_app_state_expression(self, expr: awst_nodes.AppStateExpression) -> None:\n super().visit_app_state_expression(expr)\n self._validate_usage(expr, AppStorageKind.app_global)\n\n @typing.override\n def visit_app_account_state_expression(\n self, expr: awst_nodes.AppAccountStateExpression\n ) -> None:\n super().visit_app_account_state_expression(expr)\n self._validate_usage(expr, AppStorageKind.account_local)\n\n @typing.override\n def visit_box_value_expression(self, expr: awst_nodes.BoxValueExpression) -> None:\n super().visit_box_value_expression(expr)\n self._validate_usage(expr, AppStorageKind.box)\n\n def _validate_usage(self, expr: awst_nodes.StorageExpression, kind: AppStorageKind) -> None:\n if isinstance(expr.key, awst_nodes.BytesConstant) and not set_add(\n self._seen_keys[kind], expr.key.value\n ):\n return\n wtypes.validate_persistable(expr.wtype, expr.source_location)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/awst\/validation\/storage.py","language":"Python","license":"NOASSERTION","size":2223} {"code":"from __future__ import annotations # needed to break import cycle\n\nimport typing as t\nfrom abc import ABC, abstractmethod\n\nif t.TYPE_CHECKING:\n import puya.awst.nodes\n\n\nclass StatementVisitor[T](ABC):\n @abstractmethod\n def visit_block(self, statement: puya.awst.nodes.Block) -> T: ...\n\n @abstractmethod\n def visit_if_else(self, statement: puya.awst.nodes.IfElse) -> T: ...\n\n @abstractmethod\n def visit_switch(self, statement: puya.awst.nodes.Switch) -> T: ...\n\n @abstractmethod\n def visit_while_loop(self, statement: puya.awst.nodes.WhileLoop) -> T: ...\n\n @abstractmethod\n def visit_loop_exit(self, statement: puya.awst.nodes.LoopExit) -> T: ...\n\n @abstractmethod\n def visit_return_statement(self, statement: puya.awst.nodes.ReturnStatement) -> T: ...\n\n @abstractmethod\n def visit_loop_continue(self, statement: puya.awst.nodes.LoopContinue) -> T: ...\n\n @abstractmethod\n def visit_expression_statement(self, statement: puya.awst.nodes.ExpressionStatement) -> T: ...\n\n @abstractmethod\n def visit_uint64_augmented_assignment(\n self, statement: puya.awst.nodes.UInt64AugmentedAssignment\n ) -> T: ...\n\n @abstractmethod\n def visit_biguint_augmented_assignment(\n self, statement: puya.awst.nodes.BigUIntAugmentedAssignment\n ) -> T: ...\n\n @abstractmethod\n def visit_bytes_augmented_assignment(\n self, statement: puya.awst.nodes.BytesAugmentedAssignment\n ) -> T: ...\n\n @abstractmethod\n def visit_for_in_loop(self, statement: puya.awst.nodes.ForInLoop) -> T: ...\n\n @abstractmethod\n def visit_assignment_statement(self, statement: puya.awst.nodes.AssignmentStatement) -> T: ...\n\n @abstractmethod\n def visit_goto(self, statement: puya.awst.nodes.Goto) -> T: ...\n\n\nclass RootNodeVisitor[T](ABC):\n @abstractmethod\n def visit_subroutine(self, statement: puya.awst.nodes.Subroutine) -> T: ...\n\n @abstractmethod\n def visit_contract(self, statement: puya.awst.nodes.Contract) -> T: ...\n\n @abstractmethod\n def visit_logic_signature(self, statement: puya.awst.nodes.LogicSignature) -> T: ...\n\n\nclass ContractMemberVisitor[T](ABC):\n @abstractmethod\n def visit_contract_method(self, statement: puya.awst.nodes.ContractMethod) -> T: ...\n\n @abstractmethod\n def visit_app_storage_definition(\n self, statement: puya.awst.nodes.AppStorageDefinition\n ) -> T: ...\n\n\nclass ExpressionVisitor[T](ABC):\n @abstractmethod\n def visit_state_delete(self, expr: puya.awst.nodes.StateDelete) -> T: ...\n\n @abstractmethod\n def visit_assignment_expression(self, expr: puya.awst.nodes.AssignmentExpression) -> T: ...\n\n @abstractmethod\n def visit_uint64_binary_operation(self, expr: puya.awst.nodes.UInt64BinaryOperation) -> T: ...\n\n @abstractmethod\n def visit_biguint_binary_operation(\n self, expr: puya.awst.nodes.BigUIntBinaryOperation\n ) -> T: ...\n\n @abstractmethod\n def visit_integer_constant(self, expr: puya.awst.nodes.IntegerConstant) -> T: ...\n\n @abstractmethod\n def visit_decimal_constant(self, expr: puya.awst.nodes.DecimalConstant) -> T: ...\n\n @abstractmethod\n def visit_bool_constant(self, expr: puya.awst.nodes.BoolConstant) -> T: ...\n\n @abstractmethod\n def visit_bytes_constant(self, expr: puya.awst.nodes.BytesConstant) -> T: ...\n\n @abstractmethod\n def visit_string_constant(self, expr: puya.awst.nodes.StringConstant) -> T: ...\n\n @abstractmethod\n def visit_void_constant(self, expr: puya.awst.nodes.VoidConstant) -> T: ...\n\n @abstractmethod\n def visit_address_constant(self, expr: puya.awst.nodes.AddressConstant) -> T: ...\n\n @abstractmethod\n def visit_compiled_contract(self, expr: puya.awst.nodes.CompiledContract) -> T: ...\n\n @abstractmethod\n def visit_compiled_logicsig(self, expr: puya.awst.nodes.CompiledLogicSig) -> T: ...\n\n @abstractmethod\n def visit_numeric_comparison_expression(\n self, expr: puya.awst.nodes.NumericComparisonExpression\n ) -> T: ...\n\n @abstractmethod\n def visit_var_expression(self, expr: puya.awst.nodes.VarExpression) -> T: ...\n\n @abstractmethod\n def visit_intrinsic_call(self, call: puya.awst.nodes.IntrinsicCall) -> T: ...\n\n @abstractmethod\n def visit_puya_lib_call(self, call: puya.awst.nodes.PuyaLibCall) -> T: ...\n\n @abstractmethod\n def visit_group_transaction_reference(\n self, ref: puya.awst.nodes.GroupTransactionReference\n ) -> T: ...\n\n @abstractmethod\n def visit_create_inner_transaction(\n self, create_itxn: puya.awst.nodes.CreateInnerTransaction\n ) -> T: ...\n\n @abstractmethod\n def visit_update_inner_transaction(\n self, update_itxn: puya.awst.nodes.UpdateInnerTransaction\n ) -> T: ...\n\n @abstractmethod\n def visit_submit_inner_transaction(\n self, submit: puya.awst.nodes.SubmitInnerTransaction\n ) -> T: ...\n\n @abstractmethod\n def visit_inner_transaction_field(\n self, itxn_field: puya.awst.nodes.InnerTransactionField\n ) -> T: ...\n @abstractmethod\n def visit_assert_expression(self, statement: puya.awst.nodes.AssertExpression) -> T: ...\n\n @abstractmethod\n def visit_checked_maybe(self, call: puya.awst.nodes.CheckedMaybe) -> T: ...\n\n @abstractmethod\n def visit_arc4_decode(self, expr: puya.awst.nodes.ARC4Decode) -> T: ...\n\n @abstractmethod\n def visit_arc4_encode(self, expr: puya.awst.nodes.ARC4Encode) -> T: ...\n\n @abstractmethod\n def visit_array_concat(self, expr: puya.awst.nodes.ArrayConcat) -> T: ...\n\n @abstractmethod\n def visit_array_extend(self, expr: puya.awst.nodes.ArrayExtend) -> T: ...\n\n @abstractmethod\n def visit_tuple_expression(self, expr: puya.awst.nodes.TupleExpression) -> T: ...\n\n @abstractmethod\n def visit_tuple_item_expression(self, expr: puya.awst.nodes.TupleItemExpression) -> T: ...\n\n @abstractmethod\n def visit_field_expression(self, expr: puya.awst.nodes.FieldExpression) -> T: ...\n\n @abstractmethod\n def visit_index_expression(self, expr: puya.awst.nodes.IndexExpression) -> T: ...\n\n @abstractmethod\n def visit_slice_expression(self, expr: puya.awst.nodes.SliceExpression) -> T: ...\n\n @abstractmethod\n def visit_conditional_expression(self, expr: puya.awst.nodes.ConditionalExpression) -> T: ...\n\n @abstractmethod\n def visit_single_evaluation(self, expr: puya.awst.nodes.SingleEvaluation) -> T: ...\n\n @abstractmethod\n def visit_app_state_expression(self, expr: puya.awst.nodes.AppStateExpression) -> T: ...\n\n @abstractmethod\n def visit_app_account_state_expression(\n self, expr: puya.awst.nodes.AppAccountStateExpression\n ) -> T: ...\n\n @abstractmethod\n def visit_new_array(self, expr: puya.awst.nodes.NewArray) -> T: ...\n\n @abstractmethod\n def visit_new_struct(self, expr: puya.awst.nodes.NewStruct) -> T: ...\n\n @abstractmethod\n def visit_bytes_comparison_expression(\n self, expr: puya.awst.nodes.BytesComparisonExpression\n ) -> T: ...\n\n @abstractmethod\n def visit_subroutine_call_expression(\n self, expr: puya.awst.nodes.SubroutineCallExpression\n ) -> T: ...\n\n @abstractmethod\n def visit_bytes_binary_operation(self, expr: puya.awst.nodes.BytesBinaryOperation) -> T: ...\n\n @abstractmethod\n def visit_boolean_binary_operation(\n self, expr: puya.awst.nodes.BooleanBinaryOperation\n ) -> T: ...\n\n @abstractmethod\n def visit_uint64_unary_operation(self, expr: puya.awst.nodes.UInt64UnaryOperation) -> T: ...\n\n @abstractmethod\n def visit_bytes_unary_operation(self, expr: puya.awst.nodes.BytesUnaryOperation) -> T: ...\n\n @abstractmethod\n def visit_not_expression(self, expr: puya.awst.nodes.Not) -> T: ...\n\n @abstractmethod\n def visit_reinterpret_cast(self, expr: puya.awst.nodes.ReinterpretCast) -> T: ...\n\n @abstractmethod\n def visit_enumeration(self, expr: puya.awst.nodes.Enumeration) -> T: ...\n\n @abstractmethod\n def visit_method_constant(self, expr: puya.awst.nodes.MethodConstant) -> T: ...\n\n @abstractmethod\n def visit_array_pop(self, expr: puya.awst.nodes.ArrayPop) -> T: ...\n\n @abstractmethod\n def visit_copy(self, expr: puya.awst.nodes.Copy) -> T: ...\n\n @abstractmethod\n def visit_reversed(self, expr: puya.awst.nodes.Reversed) -> T: ...\n\n @abstractmethod\n def visit_state_get(self, expr: puya.awst.nodes.StateGet) -> T: ...\n\n @abstractmethod\n def visit_state_get_ex(self, expr: puya.awst.nodes.StateGetEx) -> T: ...\n\n @abstractmethod\n def visit_state_exists(self, expr: puya.awst.nodes.StateExists) -> T: ...\n\n @abstractmethod\n def visit_template_var(self, expr: puya.awst.nodes.TemplateVar) -> T: ...\n\n @abstractmethod\n def visit_intersection_slice_expression(\n self, expr: puya.awst.nodes.IntersectionSliceExpression\n ) -> T: ...\n\n @abstractmethod\n def visit_box_value_expression(self, expr: puya.awst.nodes.BoxValueExpression) -> T: ...\n\n @abstractmethod\n def visit_uint64_postfix_unary_operation(\n self, expr: puya.awst.nodes.UInt64PostfixUnaryOperation\n ) -> T: ...\n\n @abstractmethod\n def visit_biguint_postfix_unary_operation(\n self, expr: puya.awst.nodes.BigUIntPostfixUnaryOperation\n ) -> T: ...\n\n @abstractmethod\n def visit_arc4_router(self, expr: puya.awst.nodes.ARC4Router) -> T: ...\n\n @abstractmethod\n def visit_range(self, node: puya.awst.nodes.Range) -> T: ...\n\n @abstractmethod\n def visit_emit(self, emit: puya.awst.nodes.Emit) -> T: ...\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/awst\/visitors.py","language":"Python","license":"NOASSERTION","size":9483} {"code":"import typing\nfrom collections.abc import Iterable, Mapping\nfrom functools import cached_property\n\nimport attrs\nfrom immutabledict import immutabledict\n\nfrom puya import log\nfrom puya.avm import AVMType, TransactionType\nfrom puya.errors import CodeError, InternalError\nfrom puya.parse import SourceLocation\nfrom puya.utils import unique\n\nlogger = log.get_logger(__name__)\n\n\n@attrs.frozen(kw_only=True)\nclass WType:\n name: str\n scalar_type: typing.Literal[AVMType.uint64, AVMType.bytes, None]\n \"the (unbound) AVM stack type, if any\"\n ephemeral: bool = False\n \"\"\"ephemeral types are not suitable for naive storage \/ persistence,\n even if their underlying type is a simple stack value\"\"\"\n immutable: bool\n\n def __str__(self) -> str:\n return self.name\n\n\nvoid_wtype: typing.Final = WType(\n name=\"void\",\n scalar_type=None,\n immutable=True,\n)\n\nbool_wtype: typing.Final = WType(\n name=\"bool\",\n scalar_type=AVMType.uint64,\n immutable=True,\n)\n\nuint64_wtype: typing.Final = WType(\n name=\"uint64\",\n scalar_type=AVMType.uint64,\n immutable=True,\n)\n\nbiguint_wtype: typing.Final = WType(\n name=\"biguint\",\n scalar_type=AVMType.bytes,\n immutable=True,\n)\n\nbytes_wtype: typing.Final = WType(\n name=\"bytes\",\n scalar_type=AVMType.bytes,\n immutable=True,\n)\nstring_wtype: typing.Final = WType(\n name=\"string\",\n scalar_type=AVMType.bytes,\n immutable=True,\n)\nasset_wtype: typing.Final = WType(\n name=\"asset\",\n scalar_type=AVMType.uint64,\n immutable=True,\n)\n\naccount_wtype: typing.Final = WType(\n name=\"account\",\n scalar_type=AVMType.bytes,\n immutable=True,\n)\n\napplication_wtype: typing.Final = WType(\n name=\"application\",\n scalar_type=AVMType.uint64,\n immutable=True,\n)\n\nstate_key: typing.Final = WType(\n name=\"state_key\",\n scalar_type=AVMType.bytes,\n immutable=True,\n)\nbox_key: typing.Final = WType(\n name=\"box_key\",\n scalar_type=AVMType.bytes,\n immutable=True,\n)\n\nuint64_range_wtype: typing.Final = WType(\n name=\"uint64_range\",\n scalar_type=None,\n immutable=True,\n)\n\n\n@attrs.frozen\nclass WEnumeration(WType):\n sequence_type: WType\n name: str = attrs.field(init=False)\n immutable: bool = attrs.field(default=True, init=False)\n scalar_type: None = attrs.field(default=None, init=False)\n ephemeral: bool = attrs.field(default=False, init=False)\n\n @name.default\n def _name_factory(self) -> str:\n return f\"enumerate_{self.sequence_type.name}\"\n\n\n@attrs.frozen\nclass _TransactionRelatedWType(WType):\n transaction_type: TransactionType | None\n ephemeral: bool = attrs.field(default=True, init=False)\n immutable: bool = attrs.field(default=True, init=False)\n\n\n@typing.final\n@attrs.frozen\nclass WGroupTransaction(_TransactionRelatedWType):\n scalar_type: typing.Literal[AVMType.uint64] = attrs.field(default=AVMType.uint64, init=False)\n\n @classmethod\n def from_type(cls, transaction_type: TransactionType | None) -> \"WGroupTransaction\":\n name = \"group_transaction\"\n if transaction_type:\n name = f\"{name}_{transaction_type.name}\"\n return cls(name=name, transaction_type=transaction_type)\n\n\n@typing.final\n@attrs.frozen\nclass WInnerTransactionFields(_TransactionRelatedWType):\n scalar_type: None = attrs.field(default=None, init=False)\n\n @classmethod\n def from_type(cls, transaction_type: TransactionType | None) -> \"WInnerTransactionFields\":\n name = \"inner_transaction_fields\"\n if transaction_type:\n name = f\"{name}_{transaction_type.name}\"\n return cls(name=name, transaction_type=transaction_type)\n\n\n@typing.final\n@attrs.frozen\nclass WInnerTransaction(_TransactionRelatedWType):\n scalar_type: None = attrs.field(default=None, init=False)\n\n @classmethod\n def from_type(cls, transaction_type: TransactionType | None) -> \"WInnerTransaction\":\n name = \"inner_transaction\"\n if transaction_type:\n name = f\"{name}_{transaction_type.name}\"\n return cls(name=name, transaction_type=transaction_type)\n\n\n@typing.final\n@attrs.frozen\nclass WStructType(WType):\n fields: immutabledict[str, WType] = attrs.field(converter=immutabledict)\n frozen: bool\n immutable: bool = attrs.field(init=False)\n scalar_type: None = attrs.field(default=None, init=False)\n source_location: SourceLocation | None = attrs.field(eq=False)\n desc: str | None = None\n\n @immutable.default\n def _immutable(self) -> bool:\n # TODO: determine correct behaviour when implementing native structs\n raise NotImplementedError\n\n @fields.validator\n def _fields_validator(self, _: object, fields: immutabledict[str, WType]) -> None:\n if not fields:\n raise CodeError(\"struct needs fields\", self.source_location)\n if void_wtype in fields.values():\n raise CodeError(\"struct should not contain void types\", self.source_location)\n\n\n@typing.final\n@attrs.frozen\nclass WArray(WType):\n element_type: WType = attrs.field()\n name: str = attrs.field(init=False)\n scalar_type: None = attrs.field(default=None, init=False)\n source_location: SourceLocation | None = attrs.field(eq=False)\n immutable: bool = attrs.field(default=False, init=False)\n\n @element_type.validator\n def _element_type_validator(self, _: object, element_type: WType) -> None:\n if element_type == void_wtype:\n raise CodeError(\"array element type cannot be void\", self.source_location)\n\n @name.default\n def _name(self) -> str:\n return f\"array<{self.element_type.name}>\"\n\n\n@typing.final\n@attrs.frozen(eq=False)\nclass WTuple(WType):\n types: tuple[WType, ...] = attrs.field(converter=tuple[WType, ...])\n source_location: SourceLocation | None = attrs.field(default=None)\n scalar_type: None = attrs.field(default=None, init=False)\n immutable: bool = attrs.field(default=True, init=False)\n name: str = attrs.field(kw_only=True)\n names: tuple[str, ...] | None = attrs.field(default=None)\n desc: str | None = None\n\n def __eq__(self, other: object) -> bool:\n # this custom equality check ensures that\n # tuple field names are only considered when both sides\n # have defined names\n if not isinstance(other, WTuple):\n return False\n return self.types == other.types and (\n self.names == other.names or None in (self.names, other.names)\n )\n\n def __hash__(self) -> int:\n return hash(self.types)\n\n @types.validator\n def _types_validator(self, _attribute: object, types: tuple[WType, ...]) -> None:\n if void_wtype in types:\n raise CodeError(\"tuple should not contain void types\", self.source_location)\n\n @name.default\n def _name(self) -> str:\n return f\"tuple<{','.join([t.name for t in self.types])}>\"\n\n @names.validator\n def _names_validator(self, _attribute: object, names: tuple[str, ...] | None) -> None:\n if names is None:\n return\n if len(names) != len(self.types):\n raise InternalError(\"mismatch between tuple item names length and types\")\n if len(names) != len(unique(names)):\n raise CodeError(\"tuple item names are not unique\", self.source_location)\n\n @cached_property\n def fields(self) -> Mapping[str, WType]:\n \"\"\"Mapping of item names to types if `names` is defined, otherwise empty.\"\"\"\n if self.names is None:\n return {}\n return dict(zip(self.names, self.types, strict=True))\n\n def name_to_index(self, name: str, source_location: SourceLocation) -> int:\n if self.names is None:\n raise CodeError(\n \"cannot access tuple item by name of an unnamed tuple\", source_location\n )\n try:\n return self.names.index(name)\n except ValueError:\n raise CodeError(f\"{name} is not a member of {self.name}\") from None\n\n\n@attrs.frozen(kw_only=True)\nclass ARC4Type(WType):\n scalar_type: typing.Literal[AVMType.bytes] = attrs.field(default=AVMType.bytes, init=False)\n arc4_name: str = attrs.field(eq=False) # exclude from equality in case of aliasing\n native_type: WType | None\n\n def can_encode_type(self, wtype: WType) -> bool:\n return wtype == self.native_type\n\n\narc4_bool_wtype: typing.Final = ARC4Type(\n name=\"arc4.bool\",\n arc4_name=\"bool\",\n immutable=True,\n native_type=bool_wtype,\n)\n\n\n@typing.final\n@attrs.frozen(kw_only=True)\nclass ARC4UIntN(ARC4Type):\n immutable: bool = attrs.field(default=True, init=False)\n native_type: WType = attrs.field(default=biguint_wtype, init=False)\n n: int = attrs.field()\n arc4_name: str = attrs.field(eq=False)\n name: str = attrs.field(init=False)\n source_location: SourceLocation | None = attrs.field(default=None, eq=False)\n\n @n.validator\n def _n_validator(self, _attribute: object, n: int) -> None:\n if not (n % 8 == 0):\n raise CodeError(\"Bit size must be multiple of 8\", self.source_location)\n if not (8 <= n <= 512):\n raise CodeError(\"Bit size must be between 8 and 512 inclusive\", self.source_location)\n\n @arc4_name.default\n def _arc4_name(self) -> str:\n return f\"uint{self.n}\"\n\n @name.default\n def _name(self) -> str:\n return f\"arc4.{self._arc4_name()}\"\n\n def can_encode_type(self, wtype: WType) -> bool:\n return wtype in (bool_wtype, uint64_wtype, biguint_wtype)\n\n\n@typing.final\n@attrs.frozen(kw_only=True)\nclass ARC4UFixedNxM(ARC4Type):\n n: int = attrs.field()\n m: int = attrs.field()\n immutable: bool = attrs.field(default=True, init=False)\n arc4_name: str = attrs.field(init=False, eq=False)\n name: str = attrs.field(init=False)\n source_location: SourceLocation | None = attrs.field(default=None, eq=False)\n native_type: None = attrs.field(default=None, init=False)\n\n @arc4_name.default\n def _arc4_name(self) -> str:\n return f\"ufixed{self.n}x{self.m}\"\n\n @name.default\n def _name(self) -> str:\n return f\"arc4.{self.arc4_name}\"\n\n @n.validator\n def _n_validator(self, _attribute: object, n: int) -> None:\n if not (n % 8 == 0):\n raise CodeError(\"Bit size must be multiple of 8\", self.source_location)\n if not (8 <= n <= 512):\n raise CodeError(\"Bit size must be between 8 and 512 inclusive\", self.source_location)\n\n @m.validator\n def _m_validator(self, _attribute: object, m: int) -> None:\n if not (1 <= m <= 160):\n raise CodeError(\"Precision must be between 1 and 160 inclusive\", self.source_location)\n\n\ndef _required_arc4_wtypes(wtypes: Iterable[WType]) -> tuple[ARC4Type, ...]:\n result = []\n for wtype in wtypes:\n if not isinstance(wtype, ARC4Type):\n raise CodeError(f\"expected ARC4 type: {wtype}\")\n result.append(wtype)\n return tuple(result)\n\n\n@typing.final\n@attrs.frozen(kw_only=True)\nclass ARC4Tuple(ARC4Type):\n source_location: SourceLocation | None = attrs.field(default=None, eq=False)\n types: tuple[ARC4Type, ...] = attrs.field(converter=_required_arc4_wtypes)\n name: str = attrs.field(init=False)\n arc4_name: str = attrs.field(init=False, eq=False)\n immutable: bool = attrs.field(init=False)\n native_type: WTuple = attrs.field(init=False)\n\n @name.default\n def _name(self) -> str:\n return f\"arc4.tuple<{','.join(t.name for t in self.types)}>\"\n\n @arc4_name.default\n def _arc4_name(self) -> str:\n return f\"({','.join(item.arc4_name for item in self.types)})\"\n\n @immutable.default\n def _immutable(self) -> bool:\n return all(typ.immutable for typ in self.types)\n\n @native_type.default\n def _native_type(self) -> WTuple:\n return WTuple(self.types, self.source_location)\n\n def can_encode_type(self, wtype: WType) -> bool:\n return super().can_encode_type(wtype) or _is_arc4_encodeable_tuple(wtype, self.types)\n\n\ndef _is_arc4_encodeable_tuple(\n wtype: WType, target_types: tuple[ARC4Type, ...]\n) -> typing.TypeGuard[WTuple]:\n return (\n isinstance(wtype, WTuple)\n and len(wtype.types) == len(target_types)\n and all(\n arc4_wtype == encode_wtype or arc4_wtype.can_encode_type(encode_wtype)\n for arc4_wtype, encode_wtype in zip(target_types, wtype.types, strict=True)\n )\n )\n\n\ndef _expect_arc4_type(wtype: WType) -> ARC4Type:\n if not isinstance(wtype, ARC4Type):\n raise CodeError(f\"expected ARC4 type: {wtype}\")\n return wtype\n\n\n@attrs.frozen(kw_only=True)\nclass ARC4Array(ARC4Type):\n element_type: ARC4Type = attrs.field(converter=_expect_arc4_type)\n native_type: WType | None = None\n immutable: bool = False\n\n\n@typing.final\n@attrs.frozen(kw_only=True)\nclass ARC4DynamicArray(ARC4Array):\n name: str = attrs.field(init=False)\n arc4_name: str = attrs.field(eq=False)\n source_location: SourceLocation | None = attrs.field(default=None, eq=False)\n\n @name.default\n def _name(self) -> str:\n return f\"arc4.dynamic_array<{self.element_type.name}>\"\n\n @arc4_name.default\n def _arc4_name(self) -> str:\n return f\"{self.element_type.arc4_name}[]\"\n\n\n@typing.final\n@attrs.frozen(kw_only=True)\nclass ARC4StaticArray(ARC4Array):\n array_size: int = attrs.field(validator=attrs.validators.ge(0))\n name: str = attrs.field(init=False)\n arc4_name: str = attrs.field(eq=False)\n source_location: SourceLocation | None = attrs.field(default=None, eq=False)\n\n @name.default\n def _name(self) -> str:\n return f\"arc4.static_array<{self.element_type.name}, {self.array_size}>\"\n\n @arc4_name.default\n def _arc4_name(self) -> str:\n return f\"{self.element_type.arc4_name}[{self.array_size}]\"\n\n\ndef _require_arc4_fields(fields: Mapping[str, WType]) -> immutabledict[str, ARC4Type]:\n if not fields:\n raise CodeError(\"arc4.Struct needs at least one element\")\n non_arc4_fields = [\n field_name\n for field_name, field_type in fields.items()\n if not isinstance(field_type, ARC4Type)\n ]\n if non_arc4_fields:\n raise CodeError(\n \"invalid ARC4 Struct declaration,\"\n f\" the following fields are not ARC4 encoded types: {', '.join(non_arc4_fields)}\",\n )\n return immutabledict(fields)\n\n\n@typing.final\n@attrs.frozen(kw_only=True)\nclass ARC4Struct(ARC4Type):\n fields: immutabledict[str, ARC4Type] = attrs.field(converter=_require_arc4_fields)\n frozen: bool\n immutable: bool = attrs.field(init=False)\n source_location: SourceLocation | None = attrs.field(default=None, eq=False)\n arc4_name: str = attrs.field(init=False, eq=False)\n native_type: None = attrs.field(default=None, init=False)\n desc: str | None = None\n\n @immutable.default\n def _immutable(self) -> bool:\n return self.frozen and all(typ.immutable for typ in self.fields.values())\n\n @arc4_name.default\n def _arc4_name(self) -> str:\n return f\"({','.join(item.arc4_name for item in self.types)})\"\n\n @cached_property\n def names(self) -> tuple[str, ...]:\n return tuple(self.fields.keys())\n\n @cached_property\n def types(self) -> tuple[ARC4Type, ...]:\n return tuple(self.fields.values())\n\n def can_encode_type(self, wtype: WType) -> bool:\n return super().can_encode_type(wtype) or (\n _is_arc4_encodeable_tuple(wtype, self.types)\n and (wtype.names is None or wtype.names == self.names)\n )\n\n\narc4_byte_alias: typing.Final = ARC4UIntN(\n n=8,\n arc4_name=\"byte\",\n source_location=None,\n)\n\narc4_string_alias: typing.Final = ARC4DynamicArray(\n arc4_name=\"string\",\n element_type=arc4_byte_alias,\n native_type=string_wtype,\n immutable=True,\n source_location=None,\n)\n\narc4_address_alias: typing.Final = ARC4StaticArray(\n arc4_name=\"address\",\n element_type=arc4_byte_alias,\n native_type=account_wtype,\n array_size=32,\n immutable=True,\n source_location=None,\n)\n\n\ndef persistable_stack_type(\n wtype: WType, location: SourceLocation\n) -> typing.Literal[AVMType.uint64, AVMType.bytes]:\n match _storage_type_or_error(wtype):\n case str(error):\n raise CodeError(error, location=location)\n case result:\n return result\n\n\ndef validate_persistable(wtype: WType, location: SourceLocation) -> bool:\n match _storage_type_or_error(wtype):\n case str(error):\n logger.error(error, location=location)\n return False\n case _:\n return True\n\n\ndef _storage_type_or_error(wtype: WType) -> str | typing.Literal[AVMType.uint64, AVMType.bytes]:\n if wtype.ephemeral:\n return \"ephemeral types (such as transaction related types) are not suitable for storage\"\n if wtype.scalar_type is None:\n return \"type is not suitable for storage\"\n return wtype.scalar_type\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/awst\/wtypes.py","language":"Python","license":"NOASSERTION","size":16805} {"code":"import abc\nimport typing\nfrom collections.abc import Mapping, Sequence\n\nimport attrs\n\nfrom puya.artifact_metadata import ContractMetaData, LogicSignatureMetaData\nfrom puya.parse import SourceLocation\nfrom puya.program_refs import ContractReference, LogicSigReference\n\nTemplateValue = tuple[int | bytes, SourceLocation | None]\n\n\nclass DebugEvent(typing.TypedDict, total=False):\n \"\"\"Describes various attributes for a particular PC location\"\"\"\n\n subroutine: str\n \"\"\"Subroutine name\"\"\"\n params: Mapping[str, str]\n \"\"\"Describes a subroutines parameters and their types\"\"\"\n block: str\n \"\"\"Name of a block\"\"\"\n stack_in: Sequence[str]\n \"\"\"Variable names on the stack BEFORE the next op executes\"\"\"\n op: str\n \"\"\"Op description\"\"\"\n callsub: str\n \"\"\"The subroutine that is about to be called\"\"\"\n retsub: bool\n \"\"\"Returns from current subroutine\"\"\"\n stack_out: Sequence[str]\n \"\"\"Variable names on the stack AFTER the next op executes\"\"\"\n defined_out: Sequence[str]\n \"\"\"Variable names that are defined AFTER the next op executes\"\"\"\n error: str\n \"\"\"Error message if failure occurs at this op\"\"\"\n\n\n@attrs.frozen\nclass DebugInfo:\n version: int\n sources: list[str]\n mappings: str\n op_pc_offset: int\n pc_events: Mapping[int, DebugEvent]\n\n\nclass CompiledProgram(abc.ABC):\n @property\n @abc.abstractmethod\n def teal_src(self) -> str: ...\n\n @property\n @abc.abstractmethod\n def bytecode(self) -> bytes | None:\n \"\"\"\n bytecode can only be produced if no template variables are used OR template values are\n provided, for this reason bytecode is only provided if output_bytecode is True\n \"\"\"\n\n @property\n @abc.abstractmethod\n def debug_info(self) -> DebugInfo | None: ...\n\n @property\n @abc.abstractmethod\n def template_variables(self) -> Mapping[str, int | bytes | None]: ...\n\n\nclass CompiledContract(abc.ABC):\n @property\n @abc.abstractmethod\n def source_location(self) -> SourceLocation | None: ...\n\n @property\n @abc.abstractmethod\n def approval_program(self) -> CompiledProgram: ...\n\n @property\n @abc.abstractmethod\n def clear_program(self) -> CompiledProgram: ...\n\n @property\n @abc.abstractmethod\n def metadata(self) -> ContractMetaData: ...\n\n @typing.final\n @property\n def id(self) -> ContractReference:\n return self.metadata.ref\n\n\nclass CompiledLogicSig(abc.ABC):\n @property\n @abc.abstractmethod\n def source_location(self) -> SourceLocation | None: ...\n @property\n @abc.abstractmethod\n def program(self) -> CompiledProgram: ...\n\n @property\n @abc.abstractmethod\n def metadata(self) -> LogicSignatureMetaData: ...\n\n @typing.final\n @property\n def id(self) -> LogicSigReference:\n return self.metadata.ref\n\n\nCompilationArtifact: typing.TypeAlias = CompiledContract | CompiledLogicSig\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/compilation_artifacts.py","language":"Python","license":"NOASSERTION","size":2895} {"code":"import itertools\nimport shutil\nimport typing\nfrom collections import defaultdict\nfrom collections.abc import Iterator, Mapping, Sequence, Set\nfrom pathlib import Path\n\nimport attrs\nfrom cattrs.preconf.json import make_converter\nfrom immutabledict import immutabledict\n\nfrom puya import log\nfrom puya.arc32 import create_arc32_json\nfrom puya.arc56 import create_arc56_json\nfrom puya.artifact_metadata import ContractMetaData, LogicSignatureMetaData, StateTotals\nfrom puya.artifact_sorter import Artifact, ArtifactCompilationSorter\nfrom puya.awst.nodes import AWST\nfrom puya.awst.validation.main import validate_awst\nfrom puya.compilation_artifacts import (\n CompilationArtifact,\n CompiledContract,\n CompiledLogicSig,\n CompiledProgram,\n DebugInfo,\n TemplateValue,\n)\nfrom puya.context import (\n ArtifactCompileContext,\n CompileContext,\n CompiledProgramProvider,\n OutputPathProvider,\n)\nfrom puya.errors import CodeError, InternalError\nfrom puya.ir import models as ir_models\nfrom puya.ir.destructure.main import destructure_ssa\nfrom puya.ir.main import awst_to_ir\nfrom puya.ir.optimize.main import optimize_program_ir\nfrom puya.ir.to_text_visitor import render_program\nfrom puya.ir.validation.main import validate_module_artifact\nfrom puya.log import LoggingContext\nfrom puya.mir.main import program_ir_to_mir\nfrom puya.options import PuyaOptions\nfrom puya.parse import SourceLocation\nfrom puya.program_refs import ContractReference, LogicSigReference, ProgramKind\nfrom puya.teal.main import mir_to_teal\nfrom puya.teal.models import TealProgram, TealSubroutine\nfrom puya.teal.output import emit_teal\nfrom puya.ussemble.main import assemble_program\nfrom puya.utils import attrs_extend, make_path_relative_to, make_path_relative_to_cwd\n\nlogger = log.get_logger(__name__)\n\n\ndef awst_to_teal(\n log_ctx: LoggingContext,\n options: PuyaOptions,\n compilation_set: Mapping[ContractReference | LogicSigReference, Path],\n sources_by_path: Mapping[Path, Sequence[str] | None],\n awst: AWST,\n *,\n write: bool = True,\n) -> list[CompilationArtifact]:\n validate_awst(awst)\n log_ctx.exit_if_errors()\n context = CompileContext(\n options=options,\n compilation_set=compilation_set,\n sources_by_path=sources_by_path,\n )\n log_ctx.exit_if_errors()\n ir = list(awst_to_ir(context, awst))\n log_ctx.exit_if_errors()\n teal = list(_ir_to_teal(log_ctx, context, ir))\n log_ctx.exit_if_errors()\n if write:\n _write_artifacts(context, teal)\n return teal\n\n\ndef _ir_to_teal(\n log_ctx: LoggingContext, context: CompileContext, all_ir: Sequence[ir_models.ModuleArtifact]\n) -> Iterator[CompilationArtifact]:\n compiled_program_provider = _CompiledProgramProviderImpl(\n compile_context=context,\n state_totals={\n ir.metadata.ref: ir.metadata.state_totals\n for ir in all_ir\n if isinstance(ir, ir_models.Contract)\n },\n )\n\n # used to check for conflicts that would occur on output\n artifacts_by_output_base = dict[Path, Artifact]()\n for artifact in ArtifactCompilationSorter.sort(all_ir):\n output_path_provider = None\n if out_dir_setting := context.compilation_set.get(artifact.id):\n name = artifact.ir.metadata.name\n maybe_out_dir = out_dir_setting \/ f\"{name}.ir\"\n first_seen = artifacts_by_output_base.setdefault(maybe_out_dir, artifact)\n if artifact is not first_seen:\n logger.error(f\"duplicate contract name {name}\", location=artifact.source_location)\n logger.info(\n f\"contract name {name} first seen here\", location=first_seen.source_location\n )\n else:\n out_dir = maybe_out_dir\n shutil.rmtree(out_dir, ignore_errors=True)\n output_path_provider = _SequentialOutputPathProvider(\n metadata=artifact.ir.metadata, out_dir=out_dir\n )\n\n artifact_context = attrs_extend(\n ArtifactCompileContext,\n context,\n output_path_provider=output_path_provider,\n compiled_program_provider=compiled_program_provider,\n )\n\n num_errors_before_optimization = log_ctx.num_errors\n artifact_ir = _optimize_and_destructure_ir(artifact_context, artifact.ir)\n # IR validation that occurs at the end of optimize_and_destructure_ir may have revealed\n # further errors, add dummy artifacts and continue so other artifacts can still be lowered\n # and report any errors they encounter\n errors_in_optimization = log_ctx.num_errors > num_errors_before_optimization\n if not errors_in_optimization:\n compiled: _CompiledContract | _CompiledLogicSig\n if isinstance(artifact_ir, ir_models.Contract):\n compiled = _contract_ir_to_teal(artifact_context, artifact_ir)\n else:\n compiled = _logic_sig_to_teal(artifact_context, artifact_ir)\n yield compiled\n compiled_program_provider.add_compiled_result(artifact, compiled)\n\n\n@attrs.define\nclass _CompiledProgramProviderImpl(CompiledProgramProvider):\n compile_context: CompileContext\n state_totals: Mapping[ContractReference, StateTotals]\n _compiled_artifacts: dict[\n ContractReference | LogicSigReference, \"_CompiledContract | _CompiledLogicSig\"\n ] = attrs.field(factory=dict, init=False)\n _bytecode_cache: dict[\n tuple[\n ContractReference | LogicSigReference, ProgramKind, immutabledict[str, TemplateValue]\n ],\n bytes,\n ] = attrs.field(factory=dict, init=False)\n\n def add_compiled_result(\n self, artifact: Artifact, result: \"_CompiledContract | _CompiledLogicSig\"\n ) -> None:\n self._compiled_artifacts[artifact.id] = result\n\n @typing.override\n def build_program_bytecode(\n self,\n ref: ContractReference | LogicSigReference,\n kind: ProgramKind,\n *,\n template_constants: immutabledict[str, TemplateValue],\n ) -> bytes:\n cache_key = (ref, kind, template_constants)\n try:\n return self._bytecode_cache[cache_key]\n except KeyError:\n pass\n\n try:\n comp_ref = self._compiled_artifacts[ref]\n except KeyError:\n raise CodeError(f\"invalid reference: {ref}\") from None\n match kind, comp_ref:\n case ProgramKind.logic_signature, _CompiledLogicSig(program=program):\n pass\n case ProgramKind.approval, _CompiledContract(approval_program=program):\n pass\n case ProgramKind.clear_state, _CompiledContract(clear_program=program):\n pass\n case _:\n raise InternalError(f\"invalid kind: {kind}, {type(comp_ref)}\")\n assembled = assemble_program(\n self.compile_context,\n ref,\n program.teal,\n template_constants=template_constants,\n is_reference=True,\n )\n result = assembled.bytecode\n self._bytecode_cache[cache_key] = result\n return result\n\n @typing.override\n def get_state_totals(self, ref: ContractReference) -> StateTotals:\n return self.state_totals[ref]\n\n\n@attrs.frozen\nclass _SequentialOutputPathProvider(OutputPathProvider):\n _metadata: ContractMetaData | LogicSignatureMetaData\n _out_dir: Path\n _output_seq: defaultdict[str, Iterator[int]] = attrs.field(\n factory=lambda: defaultdict(itertools.count), init=False\n )\n\n @typing.override\n def __call__(self, *, kind: str, qualifier: str, suffix: str) -> Path:\n out_dir = self._out_dir\n out_dir.mkdir(exist_ok=True)\n if qualifier:\n qualifier = f\".{qualifier}\"\n qualifier = f\"{next(self._output_seq[kind])}{qualifier}\"\n if kind is not ProgramKind.logic_signature:\n qualifier = f\"{kind}.{qualifier}\"\n return out_dir \/ f\"{self._metadata.name}.{qualifier}.{suffix}\"\n\n\ndef _optimize_and_destructure_ir(\n context: ArtifactCompileContext, artifact_ir: ir_models.ModuleArtifact\n) -> ir_models.ModuleArtifact:\n if isinstance(artifact_ir, ir_models.LogicSignature):\n routable_method_ids = None\n else:\n routable_method_ids = {a4m.id for a4m in artifact_ir.metadata.arc4_methods}\n for program in artifact_ir.all_programs():\n _optimize_and_destructure_program_ir(\n context, artifact_ir.metadata.ref, program, routable_method_ids=routable_method_ids\n )\n # validation is run as the last step, in case we've accidentally inserted something,\n # and in particular post subroutine removal, because some things that are \"linked\"\n # are not necessarily used from the current artifact\n validate_module_artifact(context, artifact_ir)\n return artifact_ir\n\n\ndef _optimize_and_destructure_program_ir(\n context: ArtifactCompileContext,\n ref: ContractReference | LogicSigReference,\n program: ir_models.Program,\n routable_method_ids: Set[str] | None = None,\n) -> None:\n if context.options.output_ssa_ir:\n render_program(context, program, qualifier=\"ssa\")\n logger.info(\n f\"optimizing {program.kind} program of {ref} at level {context.options.optimization_level}\"\n )\n optimize_program_ir(context, program, routable_method_ids=routable_method_ids)\n destructure_ssa(context, program)\n if context.options.output_destructured_ir:\n render_program(context, program, qualifier=\"destructured\")\n\n\n@attrs.frozen\nclass _CompiledProgram(CompiledProgram):\n teal: TealProgram\n teal_src: str\n template_variables: Mapping[str, int | bytes | None]\n debug_info: DebugInfo | None = None\n bytecode: bytes | None = None\n\n\n@attrs.frozen\nclass _CompiledContract(CompiledContract):\n source_location: SourceLocation | None\n approval_program: _CompiledProgram\n clear_program: _CompiledProgram\n metadata: ContractMetaData\n\n\n@attrs.frozen\nclass _CompiledLogicSig(CompiledLogicSig):\n source_location: SourceLocation | None\n program: _CompiledProgram\n metadata: LogicSignatureMetaData\n\n\ndef _dummy_program() -> _CompiledProgram:\n from puya.mir.models import Signature\n\n return _CompiledProgram(\n teal=TealProgram(\n avm_version=0,\n main=TealSubroutine(\n is_main=True,\n signature=Signature(\n name=\"\",\n parameters=(),\n returns=(),\n ),\n blocks=[],\n source_location=None,\n ),\n subroutines=[],\n ),\n teal_src=\"\",\n template_variables={},\n )\n\n\ndef _contract_ir_to_teal(\n context: ArtifactCompileContext, contract_ir: ir_models.Contract\n) -> _CompiledContract:\n approval_mir = program_ir_to_mir(context, contract_ir.approval_program)\n clear_state_mir = program_ir_to_mir(context, contract_ir.clear_program)\n approval_teal = mir_to_teal(context, approval_mir)\n clear_state_teal = mir_to_teal(context, clear_state_mir)\n ref = contract_ir.metadata.ref\n approval_program = _compile_program(context, ref, approval_teal)\n clear_program = _compile_program(context, ref, clear_state_teal)\n return _CompiledContract(\n approval_program=approval_program,\n clear_program=clear_program,\n metadata=contract_ir.metadata,\n source_location=contract_ir.source_location,\n )\n\n\ndef _logic_sig_to_teal(\n context: ArtifactCompileContext, logic_sig_ir: ir_models.LogicSignature\n) -> _CompiledLogicSig:\n program_mir = program_ir_to_mir(context, logic_sig_ir.program)\n teal_program = mir_to_teal(context, program_mir)\n program = _compile_program(context, logic_sig_ir.metadata.ref, teal_program)\n return _CompiledLogicSig(\n program=program,\n metadata=logic_sig_ir.metadata,\n source_location=logic_sig_ir.source_location,\n )\n\n\ndef _compile_program(\n context: ArtifactCompileContext,\n ref: ContractReference | LogicSigReference,\n program: TealProgram,\n) -> _CompiledProgram:\n assembled = assemble_program(context, ref, program)\n teal_src = emit_teal(context, program)\n return _CompiledProgram(\n teal=program,\n teal_src=teal_src,\n bytecode=assembled.bytecode,\n debug_info=assembled.debug_info,\n template_variables=assembled.template_variables,\n )\n\n\ndef _write_artifacts(\n context: CompileContext, compiled_artifacts: list[CompilationArtifact]\n) -> None:\n if not compiled_artifacts:\n logger.warning(\"No contracts or logic signatures discovered in any source files\")\n return\n for artifact in compiled_artifacts:\n out_dir = context.compilation_set.get(artifact.id)\n if out_dir is None:\n continue\n teal_file_stem = artifact.metadata.name\n artifact_base_path = out_dir \/ teal_file_stem\n match artifact:\n case CompiledLogicSig(program=program):\n programs = {\"\": program}\n case CompiledContract(approval_program=approval, clear_program=clear) as contract:\n programs = {\n \".approval\": approval,\n \".clear\": clear,\n }\n if contract.metadata.is_arc4:\n if context.options.output_arc32:\n app_spec_json = create_arc32_json(\n approval.teal_src,\n clear.teal_src,\n contract.metadata,\n )\n _write_output(\n artifact_base_path,\n {\".arc32.json\": app_spec_json.encode(\"utf8\")},\n )\n if context.options.output_arc56:\n app_spec_json = create_arc56_json(\n metadata=contract.metadata,\n approval_program=approval,\n clear_program=clear,\n template_prefix=context.options.template_vars_prefix,\n )\n _write_output(\n artifact_base_path,\n {\".arc56.json\": app_spec_json.encode(\"utf8\")},\n )\n case _:\n typing.assert_never(artifact)\n if context.options.output_teal:\n _write_output(\n artifact_base_path,\n {\n f\"{suffix}.teal\": program.teal_src.encode(\"utf8\")\n for suffix, program in programs.items()\n },\n )\n if context.options.output_bytecode:\n _write_output(\n artifact_base_path,\n {f\"{suffix}.bin\": program.bytecode for suffix, program in programs.items()},\n )\n if context.options.output_source_map:\n _write_output(\n artifact_base_path,\n {\n f\"{suffix}.puya.map\": (\n _debug_info_as_json(program.debug_info, out_dir)\n if program.debug_info\n else None\n )\n for suffix, program in programs.items()\n },\n )\n\n\n_debug_info_converter = make_converter(omit_if_default=True)\n\n\ndef _debug_info_as_json(info: DebugInfo, base_path: Path) -> bytes:\n # make sources relative to output\n info = attrs.evolve(\n info,\n sources=[\n make_path_relative_to(path=Path(s), to=base_path, walk_up=True) for s in info.sources\n ],\n )\n json = _debug_info_converter.dumps(info, DebugInfo, indent=2)\n return json.encode(\"utf-8\")\n\n\ndef _write_output(base_path: Path, programs: dict[str, bytes | None]) -> None:\n for suffix, program in programs.items():\n output_path = base_path.with_suffix(suffix)\n if program is None:\n logger.critical(f\"Unable to output {make_path_relative_to_cwd(output_path)}\")\n else:\n logger.info(f\"Writing {make_path_relative_to_cwd(output_path)}\")\n output_path.write_bytes(program)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/compile.py","language":"Python","license":"NOASSERTION","size":16225} {"code":"import typing\nfrom collections.abc import Mapping, Sequence\nfrom pathlib import Path\n\nimport attrs\nfrom immutabledict import immutabledict\n\nfrom puya import log\nfrom puya.artifact_metadata import StateTotals\nfrom puya.compilation_artifacts import TemplateValue\nfrom puya.options import PuyaOptions\nfrom puya.parse import SourceLocation\nfrom puya.program_refs import ContractReference, LogicSigReference, ProgramKind\n\nlogger = log.get_logger(__name__)\n\n\n@attrs.define(kw_only=True)\nclass CompileContext:\n options: PuyaOptions\n compilation_set: Mapping[ContractReference | LogicSigReference, Path]\n sources_by_path: Mapping[Path, Sequence[str] | None]\n\n def try_get_source(self, location: SourceLocation | None) -> Sequence[str] | None:\n return try_get_source(self.sources_by_path, location)\n\n\ndef try_get_source(\n sources_by_path: Mapping[Path, Sequence[str] | None], location: SourceLocation | None\n) -> Sequence[str] | None:\n if not location or not location.file:\n return None\n source_lines = sources_by_path.get(location.file)\n if source_lines is None:\n return None\n\n src_content = list(source_lines[location.line - 1 : location.end_line])\n if not src_content:\n logger.warning(f\"could not locate source: {location}\", location=None)\n else:\n end_column = location.end_column\n if end_column is not None:\n src_content[-1] = src_content[-1][:end_column]\n start_column = location.column\n if start_column is not None:\n src_content[0] = src_content[0][start_column:]\n return src_content\n\n\nclass CompiledProgramProvider(typing.Protocol):\n def build_program_bytecode(\n self,\n ref: ContractReference | LogicSigReference,\n kind: ProgramKind,\n *,\n template_constants: immutabledict[str, TemplateValue],\n ) -> bytes: ...\n\n def get_state_totals(self, ref: ContractReference) -> StateTotals: ...\n\n\nclass OutputPathProvider(typing.Protocol):\n def __call__(self, *, kind: str, qualifier: str, suffix: str) -> Path: ...\n\n\n@attrs.define(kw_only=True)\nclass ArtifactCompileContext(CompileContext):\n _compiled_program_provider: CompiledProgramProvider = attrs.field(\n on_setattr=attrs.setters.frozen\n )\n _output_path_provider: OutputPathProvider | None = attrs.field(on_setattr=attrs.setters.frozen)\n\n def build_output_path(self, kind: str, qualifier: str, suffix: str) -> Path | None:\n if self._output_path_provider is None:\n return None\n return self._output_path_provider(kind=kind, qualifier=qualifier, suffix=suffix)\n\n @typing.overload\n def build_program_bytecode(\n self,\n ref: ContractReference,\n kind: typing.Literal[ProgramKind.approval, ProgramKind.clear_state],\n *,\n template_constants: immutabledict[str, TemplateValue],\n ) -> bytes: ...\n\n @typing.overload\n def build_program_bytecode(\n self,\n ref: LogicSigReference,\n kind: typing.Literal[ProgramKind.logic_signature],\n *,\n template_constants: immutabledict[str, TemplateValue],\n ) -> bytes: ...\n\n def build_program_bytecode(\n self,\n ref: ContractReference | LogicSigReference,\n kind: ProgramKind,\n *,\n template_constants: immutabledict[str, TemplateValue],\n ) -> bytes:\n return self._compiled_program_provider.build_program_bytecode(\n ref, kind, template_constants=template_constants\n )\n\n def get_state_totals(self, ref: ContractReference) -> StateTotals:\n return self._compiled_program_provider.get_state_totals(ref)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/context.py","language":"Python","license":"NOASSERTION","size":3629} {"code":"import contextlib\nimport enum\nimport sys\nimport traceback\nfrom collections.abc import Iterator\n\nfrom puya import log\nfrom puya.parse import SourceLocation\n\nlogger = log.get_logger(__name__)\n\n\nclass ErrorExitCode(enum.IntEnum):\n code = 1\n internal = 2\n\n\nclass PuyaError(Exception):\n def __init__(self, msg: str, location: SourceLocation | None = None):\n super().__init__(msg)\n self.msg = msg\n self.location = location\n\n\nclass InternalError(PuyaError):\n \"\"\"Base class for all exceptions that indicate a fault in the compiler.\"\"\"\n\n\nclass CodeError(PuyaError):\n \"\"\"Base class for all exceptions that indicate a fault in the code being compiled.\"\"\"\n\n\n@contextlib.contextmanager\ndef log_exceptions(fallback_location: SourceLocation | None = None) -> Iterator[None]:\n try:\n yield\n except CodeError as ex:\n logger.error(ex.msg, location=ex.location or fallback_location) # noqa: TRY400\n except InternalError as ex:\n _log_traceback()\n logger.critical(ex.msg, location=ex.location or fallback_location)\n sys.exit(ErrorExitCode.internal)\n except Exception as ex:\n _log_traceback()\n logger.critical(f\"{type(ex).__name__}: {ex}\", location=fallback_location)\n sys.exit(ErrorExitCode.internal)\n\n\ndef _log_traceback() -> None:\n traceback_lines = traceback.format_exc()\n logger.debug(traceback_lines.rstrip(\"\\n\"))\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/errors.py","language":"Python","license":"NOASSERTION","size":1408} {"code":"IR_SSA = \"ssa\"\nIR_OPTIMIZATION = \"pass\"\nIR_FINAL = \"final\"\n\nIR_ALL = (IR_SSA, IR_OPTIMIZATION, IR_FINAL)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/__init__.py","language":"Python","license":"NOASSERTION","size":105} {"code":"import typing\nfrom collections.abc import Mapping\n\nimport attrs\n\nimport puya.ir.models as ir\nfrom puya import (\n artifact_metadata as models,\n log,\n)\nfrom puya.avm import AVMType, OnCompletionAction\nfrom puya.awst import (\n nodes as awst_nodes,\n wtypes,\n)\nfrom puya.awst.arc4_types import maybe_avm_to_arc4_equivalent_type, wtype_to_arc4\nfrom puya.context import CompiledProgramProvider\nfrom puya.errors import CodeError\nfrom puya.ir._utils import make_subroutine\nfrom puya.ir.builder.main import FunctionIRBuilder\nfrom puya.ir.context import IRBuildContext\nfrom puya.ir.optimize.context import IROptimizationContext\nfrom puya.ir.optimize.main import get_subroutine_optimizations\nfrom puya.options import PuyaOptions\nfrom puya.parse import SourceLocation\n\nlogger = log.get_logger(__name__)\n\n\ndef convert_default_args(\n ctx: IRBuildContext,\n contract: awst_nodes.Contract,\n m: awst_nodes.ContractMethod,\n config: awst_nodes.ARC4ABIMethodConfig,\n) -> Mapping[awst_nodes.SubroutineArgument, models.MethodArgDefault | None]:\n state_by_name = {s.member_name: s for s in contract.app_state}\n return {\n a: _convert_default_arg(\n ctx, contract, state_by_name, a, config.default_args.get(a.name), method_id=m.full_name\n )\n for a in m.args\n }\n\n\ndef _convert_default_arg(\n ctx: IRBuildContext,\n contract: awst_nodes.Contract,\n state_by_name: Mapping[str, awst_nodes.AppStorageDefinition],\n param: awst_nodes.SubroutineArgument,\n default: awst_nodes.ABIMethodArgDefault | None,\n *,\n method_id: str,\n) -> models.MethodArgDefault | None:\n match default:\n case None:\n return None\n case awst_nodes.ABIMethodArgMemberDefault(name=member_name):\n result_or_error = _convert_member_arg_default(\n contract, state_by_name, param, member_name\n )\n match result_or_error:\n case str(error_message):\n logger.error(error_message, location=param.source_location)\n return None\n case result:\n return result\n case awst_nodes.ABIMethodArgConstantDefault(value=expr):\n return _compile_arc4_default_constant(ctx, method_id, param, expr)\n\n\ndef _convert_member_arg_default(\n contract: awst_nodes.Contract,\n state_by_name: Mapping[str, awst_nodes.AppStorageDefinition],\n param: awst_nodes.SubroutineArgument,\n member_name: str,\n) -> models.MethodArgDefaultFromState | models.MethodArgDefaultFromMethod | str:\n param_arc4_type = wtype_to_arc4(param.wtype)\n\n # special handling for reference types\n match param_arc4_type:\n case \"asset\" | \"application\":\n param_arc4_type = \"uint64\"\n case \"account\":\n param_arc4_type = \"address\"\n\n if (state_source := state_by_name.get(member_name)) is not None:\n if state_source.key_wtype is not None:\n return \"state member is a map\"\n storage_type = wtypes.persistable_stack_type(\n state_source.storage_wtype, param.source_location\n )\n if (\n storage_type is AVMType.uint64\n # storage can provide an int to types <= uint64\n # TODO: check what ATC does with ufixed, see if it can be added\n and not (param_arc4_type == \"byte\" or param_arc4_type.startswith(\"uint\"))\n ) or (\n storage_type is AVMType.bytes\n # storage can provide fixed byte arrays\n and not (\n param_arc4_type == \"address\"\n or (param_arc4_type.startswith(\"byte[\") and param_arc4_type != \"byte[]\")\n )\n ):\n return f\"{member_name!r} cannot provide {param_arc4_type!r} type\"\n return models.MethodArgDefaultFromState(\n kind=state_source.kind,\n key=state_source.key.value,\n key_type=(\n \"AVMString\"\n if state_source.key.encoding == awst_nodes.BytesEncoding.utf8\n else \"AVMBytes\"\n ),\n )\n elif (method_source := contract.resolve_contract_method(member_name)) is not None:\n abi_method_config = method_source.arc4_method_config\n if not isinstance(abi_method_config, awst_nodes.ARC4ABIMethodConfig):\n return \"only ARC-4 ABI methods can be used as default values\"\n if OnCompletionAction.NoOp not in abi_method_config.allowed_completion_types:\n return f\"{member_name!r} does not allow no_op on completion calls\"\n if abi_method_config.create == awst_nodes.ARC4CreateOption.require:\n return f\"{member_name!r} can only be used for create calls\"\n if not abi_method_config.readonly:\n return f\"{member_name!r} is not readonly\"\n if method_source.args:\n return f\"{member_name!r} does not take zero arguments\"\n if method_source.return_type is wtypes.void_wtype:\n return f\"{member_name!r} does not provide a value\"\n return_type_arc4 = wtype_to_arc4(method_source.return_type)\n if return_type_arc4 != param_arc4_type:\n return f\"{member_name!r} does not provide {param_arc4_type!r} type\"\n return models.MethodArgDefaultFromMethod(\n name=abi_method_config.name,\n return_type=return_type_arc4,\n readonly=abi_method_config.readonly,\n )\n else:\n return f\"{member_name!r} is not a known state or method attribute\"\n\n\ndef _compile_arc4_default_constant(\n ctx: IRBuildContext,\n method_id: str,\n param: awst_nodes.SubroutineArgument,\n expr: awst_nodes.Expression,\n) -> models.MethodArgDefaultConstant | None:\n location = expr.source_location\n logger.debug(\"Building IR for ARC4 method argument default constant\", location=location)\n\n if param.wtype != expr.wtype:\n logger.error(\"mismatch between parameter type and default value type\", location=location)\n return None\n\n if isinstance(expr.wtype, wtypes.ARC4Type):\n arc4_type_name = expr.wtype.arc4_name\n else:\n arc4_type = maybe_avm_to_arc4_equivalent_type(expr.wtype)\n if arc4_type is None:\n logger.error(\"unsupported type for argument default\", location=location)\n return None\n expr = awst_nodes.ARC4Encode(value=expr, wtype=arc4_type, source_location=location)\n arc4_type_name = arc4_type.arc4_name\n\n fake_name = f\"#default:{param.name}\"\n awst_subroutine = awst_nodes.Subroutine(\n id=method_id + fake_name,\n name=fake_name,\n source_location=expr.source_location,\n args=[],\n return_type=expr.wtype,\n body=awst_nodes.Block(\n body=[awst_nodes.ReturnStatement(value=expr, source_location=expr.source_location)],\n source_location=expr.source_location,\n ),\n documentation=awst_nodes.MethodDocumentation(),\n inline=False,\n )\n ir_subroutine = make_subroutine(awst_subroutine, allow_implicits=False)\n FunctionIRBuilder.build_body(ctx, awst_subroutine, ir_subroutine)\n\n bytes_result = _try_extract_byte_constant(ir_subroutine)\n if bytes_result is None:\n _optimize_subroutine(ctx, ir_subroutine, location)\n bytes_result = _try_extract_byte_constant(ir_subroutine)\n if bytes_result is None:\n logger.error(\"could not determine constant value\", location=location)\n return None\n return models.MethodArgDefaultConstant(data=bytes_result, type_=arc4_type_name)\n\n\ndef _optimize_subroutine(\n ctx: IRBuildContext, subroutine: ir.Subroutine, location: SourceLocation\n) -> None:\n optimization_level = max(2, ctx.options.optimization_level)\n logger.debug(\n f\"Running optimizer at level {optimization_level}\"\n f\" to encode compile time constant to bytes\",\n location=location,\n )\n options = PuyaOptions(\n optimization_level=optimization_level,\n target_avm_version=ctx.options.target_avm_version,\n )\n dummy_program_provider = _NoCompiledProgramProvider(location)\n pass_context = IROptimizationContext(\n compilation_set=ctx.compilation_set,\n sources_by_path=ctx.sources_by_path,\n options=options,\n compiled_program_provider=dummy_program_provider,\n output_path_provider=None,\n expand_all_bytes=True,\n )\n pipeline = get_subroutine_optimizations(optimization_level=optimization_level)\n while True:\n modified = False\n for optimizer in pipeline:\n if optimizer.optimize(pass_context, subroutine):\n modified = True\n if not modified:\n return\n\n\ndef _try_extract_byte_constant(subroutine: ir.Subroutine) -> bytes | None:\n match subroutine.body:\n case [\n ir.BasicBlock(\n phis=[],\n ops=[],\n terminator=ir.SubroutineReturn(result=[ir.BytesConstant(value=result)]),\n )\n ]:\n return result\n return None\n\n\n@attrs.frozen\nclass _NoCompiledProgramProvider(CompiledProgramProvider):\n source_location: SourceLocation\n\n @typing.override\n def build_program_bytecode(self, *args: object, **kwargs: object) -> typing.Never:\n raise CodeError(\n \"compilation references are not supported as method default constants\",\n self.source_location,\n )\n\n @typing.override\n def get_state_totals(self, *args: object, **kwargs: object) -> typing.Never:\n raise CodeError(\n \"compilation references are not supported as method default constants\",\n self.source_location,\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/_arc4_default_args.py","language":"Python","license":"NOASSERTION","size":9586} {"code":"import contextlib\nimport typing\nfrom collections import Counter\nfrom collections.abc import Iterable, Iterator, Mapping, Sequence\nfrom operator import itemgetter\n\nimport attrs\nfrom immutabledict import immutabledict\n\nimport puya.artifact_metadata as models\nfrom puya import algo_constants, log\nfrom puya.avm import AVMType\nfrom puya.awst import (\n nodes as awst_nodes,\n wtypes,\n)\nfrom puya.awst.arc4_types import maybe_avm_to_arc4_equivalent_type, wtype_to_arc4\nfrom puya.awst.function_traverser import FunctionTraverser\nfrom puya.errors import InternalError\nfrom puya.ir._arc4_default_args import convert_default_args\nfrom puya.ir.context import IRBuildContext\nfrom puya.parse import SourceLocation\nfrom puya.utils import StableSet, set_add, unique\n\n__all__ = [\n \"build_contract_metadata\",\n]\n\nlogger = log.get_logger(__name__)\n\n\ndef build_contract_metadata(\n ctx: IRBuildContext, contract: awst_nodes.Contract\n) -> tuple[\n models.ContractMetaData,\n dict[awst_nodes.ContractMethod, models.ARC4Method],\n]:\n global_state = dict[str, models.ContractState]()\n local_state = dict[str, models.ContractState]()\n boxes = dict[str, models.ContractState]()\n for state in contract.app_state:\n translated = _translate_state(state)\n match state.kind:\n case awst_nodes.AppStorageKind.app_global:\n global_state[state.member_name] = translated\n case awst_nodes.AppStorageKind.account_local:\n local_state[state.member_name] = translated\n case awst_nodes.AppStorageKind.box:\n boxes[state.member_name] = translated\n case unexpected:\n typing.assert_never(unexpected)\n state_totals = _build_state_totals(\n contract.state_totals,\n global_state=global_state,\n local_state=local_state,\n location=contract.source_location,\n )\n arc4_method_data, type_refs = _extract_arc4_methods_and_type_refs(ctx, contract)\n structs = _extract_structs(type_refs)\n template_var_types = _TemplateVariableTypeCollector.collect(ctx, contract, arc4_method_data)\n metadata = models.ContractMetaData(\n description=contract.description,\n name=contract.name,\n ref=contract.id,\n arc4_methods=list(arc4_method_data.values()),\n global_state=immutabledict(global_state),\n local_state=immutabledict(local_state),\n boxes=immutabledict(boxes),\n state_totals=state_totals,\n structs=immutabledict(structs),\n template_variable_types=immutabledict(template_var_types),\n )\n return metadata, arc4_method_data\n\n\ndef _translate_state(\n state: awst_nodes.AppStorageDefinition,\n) -> models.ContractState:\n storage_type = wtypes.persistable_stack_type(state.storage_wtype, state.source_location)\n if state.key_wtype is not None:\n if state.kind is not awst_nodes.AppStorageKind.box:\n raise InternalError(\n f\"maps of {state.kind} are not supported by IR backend yet\", state.source_location\n )\n arc56_key_type = _get_arc56_type(state.key_wtype, state.source_location)\n is_map = True\n else:\n arc56_key_type = (\n \"AVMString\" if state.key.encoding == awst_nodes.BytesEncoding.utf8 else \"AVMBytes\"\n )\n is_map = False\n arc56_value_type = _get_arc56_type(state.storage_wtype, state.source_location)\n return models.ContractState(\n name=state.member_name,\n source_location=state.source_location,\n key_or_prefix=state.key.value,\n arc56_key_type=arc56_key_type,\n arc56_value_type=arc56_value_type,\n storage_type=storage_type,\n description=state.description,\n is_map=is_map,\n )\n\n\ndef _build_state_totals(\n declared_totals: awst_nodes.StateTotals | None,\n *,\n global_state: Mapping[str, models.ContractState],\n local_state: Mapping[str, models.ContractState],\n location: SourceLocation,\n) -> models.StateTotals:\n global_by_type = Counter(s.storage_type for s in global_state.values())\n local_by_type = Counter(s.storage_type for s in local_state.values())\n merged = models.StateTotals(\n global_uints=global_by_type[AVMType.uint64],\n global_bytes=global_by_type[AVMType.bytes],\n local_uints=local_by_type[AVMType.uint64],\n local_bytes=local_by_type[AVMType.bytes],\n )\n if declared_totals is not None:\n insufficient_fields = []\n declared_dict = attrs.asdict(declared_totals, filter=attrs.filters.include(int))\n for field, declared in declared_dict.items():\n calculated = getattr(merged, field)\n if declared < calculated:\n insufficient_fields.append(f\"{field}: {declared=}, {calculated=}\")\n merged = attrs.evolve(merged, **{field: declared})\n if insufficient_fields:\n logger.warning(\n f\"State totals declared on the class are less than totals calculated from\"\n f\" explicitly declared properties: {', '.join(sorted(insufficient_fields))}.\",\n location=location,\n )\n global_total = merged.global_uints + merged.global_bytes\n local_total = merged.local_uints + merged.local_bytes\n if global_total > algo_constants.MAX_GLOBAL_STATE_KEYS:\n logger.warning(\n f\"Total global state key count of {global_total}\"\n f\" exceeds consensus parameter value {algo_constants.MAX_GLOBAL_STATE_KEYS}\",\n location=location,\n )\n if local_total > algo_constants.MAX_LOCAL_STATE_KEYS:\n logger.warning(\n f\"Total local state key count of {local_total}\"\n f\" exceeds consensus parameter value {algo_constants.MAX_LOCAL_STATE_KEYS}\",\n location=location,\n )\n return merged\n\n\nclass _TemplateVariableTypeCollector(FunctionTraverser):\n def __init__(self, context: IRBuildContext) -> None:\n self.context = context\n self.vars = dict[str, awst_nodes.TemplateVar]()\n self._seen_functions = set[awst_nodes.Function]()\n self._func_stack = list[awst_nodes.Function]()\n\n def process_func(self, func: awst_nodes.Function) -> None:\n if set_add(self._seen_functions, func):\n with self._enter_func(func):\n func.body.accept(self)\n\n @classmethod\n def collect(\n cls,\n context: IRBuildContext,\n contract: awst_nodes.Contract,\n routable_methods: Iterable[awst_nodes.ContractMethod],\n ) -> dict[str, str]:\n collector = cls(context)\n for function in (contract.approval_program, contract.clear_program, *routable_methods):\n collector.process_func(function)\n return {\n name: _get_arc56_type(var.wtype, var.source_location)\n for name, var in collector.vars.items()\n }\n\n def visit_template_var(self, var: awst_nodes.TemplateVar) -> None:\n try:\n existing = self.vars[var.name]\n except KeyError:\n self.vars[var.name] = var\n else:\n if existing.wtype != var.wtype:\n logger.error(\n \"inconsistent types specified for template var\",\n location=var.source_location,\n )\n logger.info(\"other template var\", location=existing.source_location)\n\n @contextlib.contextmanager\n def _enter_func(self, func: awst_nodes.Function) -> Iterator[None]:\n self._func_stack.append(func)\n try:\n yield\n finally:\n self._func_stack.pop()\n\n @property\n def current_func(self) -> awst_nodes.Function:\n return self._func_stack[-1]\n\n def visit_subroutine_call_expression(self, expr: awst_nodes.SubroutineCallExpression) -> None:\n target = self.context.resolve_function_reference(\n expr.target,\n expr.source_location,\n caller=self.current_func,\n )\n self.process_func(target)\n\n\ndef _extract_arc4_methods_and_type_refs(\n ctx: IRBuildContext, contract: awst_nodes.Contract\n) -> tuple[dict[awst_nodes.ContractMethod, models.ARC4Method], list[wtypes.WType]]:\n event_collector = _EventCollector(ctx)\n type_refs = [\n typ\n for state in contract.app_state\n for typ in (state.key_wtype, state.storage_wtype)\n if typ is not None\n ]\n methods = dict[awst_nodes.ContractMethod, models.ARC4Method]()\n for method_name in unique(m.member_name for m in contract.methods):\n m = contract.resolve_contract_method(method_name)\n assert m is not None # shouldn't logically be possible\n match m.arc4_method_config:\n case None:\n pass\n case awst_nodes.ARC4BareMethodConfig() as bare_method_config:\n methods[m] = models.ARC4BareMethod(\n id=m.full_name, desc=m.documentation.description, config=bare_method_config\n )\n case abi_method_config:\n event_wtypes = event_collector.process_func(m)\n events = list(map(_wtype_to_struct, event_wtypes))\n methods[m] = _abi_method_metadata(ctx, contract, m, abi_method_config, events)\n if m.return_type is not None:\n type_refs.append(m.return_type)\n type_refs.extend(arg.wtype for arg in m.args)\n for event_struct in event_wtypes:\n type_refs.extend(event_struct.types)\n return methods, type_refs\n\n\ndef _extract_structs(\n typ_refs: Sequence[wtypes.WType],\n) -> dict[str, models.ARC4Struct]:\n # Produce a unique mapping of struct names to ARC4Struct definitions.\n # Will recursively include any structs referenced in fields\n struct_wtypes = list(filter(_is_arc4_struct, typ_refs))\n struct_results = dict[str, models.ARC4Struct]()\n while struct_wtypes:\n struct = struct_wtypes.pop()\n if struct.name in struct_results:\n continue\n struct_wtypes.extend(\n wtype\n for wtype in struct.fields.values()\n if _is_arc4_struct(wtype) and wtype.name not in struct_results\n )\n struct_results[struct.name] = _wtype_to_struct(struct)\n return dict(sorted(struct_results.items(), key=itemgetter(0)))\n\n\ndef _abi_method_metadata(\n ctx: IRBuildContext,\n contract: awst_nodes.Contract,\n m: awst_nodes.ContractMethod,\n config: awst_nodes.ARC4ABIMethodConfig,\n events: Sequence[models.ARC4Struct],\n) -> models.ARC4ABIMethod:\n assert config is m.arc4_method_config\n default_args = convert_default_args(ctx, contract, m, config)\n args = [\n models.ARC4MethodArg(\n name=a.name,\n type_=wtype_to_arc4(a.wtype),\n struct=_get_arc4_struct_name(a.wtype),\n desc=m.documentation.args.get(a.name),\n client_default=default_args[a],\n )\n for a in m.args\n ]\n returns = models.ARC4Returns(\n desc=m.documentation.returns,\n type_=wtype_to_arc4(m.return_type),\n struct=_get_arc4_struct_name(m.return_type),\n )\n return models.ARC4ABIMethod(\n id=m.full_name,\n desc=m.documentation.description,\n args=args,\n returns=returns,\n events=events,\n config=config,\n )\n\n\ndef _is_arc4_struct(\n wtype: wtypes.WType | None,\n) -> typing.TypeGuard[wtypes.ARC4Struct | wtypes.WTuple]:\n return isinstance(wtype, wtypes.ARC4Struct | wtypes.WTuple) and bool(wtype.fields)\n\n\ndef _get_arc4_struct_name(wtype: wtypes.WType) -> str | None:\n return wtype.name if _is_arc4_struct(wtype) else None\n\n\ndef _wtype_to_struct(s: wtypes.ARC4Struct | wtypes.WTuple) -> models.ARC4Struct:\n fields = []\n assert s.fields\n for field_name, field_wtype in s.fields.items():\n if not isinstance(field_wtype, wtypes.ARC4Type):\n maybe_arc4_field_wtype = maybe_avm_to_arc4_equivalent_type(field_wtype)\n if maybe_arc4_field_wtype is None:\n raise InternalError(\"expected ARC4 type\")\n field_wtype = maybe_arc4_field_wtype\n fields.append(\n models.ARC4StructField(\n name=field_name,\n type=field_wtype.arc4_name,\n struct=_get_arc4_struct_name(field_wtype),\n )\n )\n return models.ARC4Struct(fullname=s.name, desc=s.desc, fields=fields)\n\n\n@attrs.frozen\nclass _EventCollector(FunctionTraverser):\n context: IRBuildContext\n emits: dict[awst_nodes.Function, StableSet[wtypes.ARC4Struct]] = attrs.field(\n factory=dict, init=False\n )\n _func_stack: list[awst_nodes.Function] = attrs.field(factory=list)\n\n def process_func(self, func: awst_nodes.Function) -> StableSet[wtypes.ARC4Struct]:\n if func not in self.emits:\n self.emits[func] = StableSet[wtypes.ARC4Struct]()\n with self._enter_func(func):\n func.body.accept(self)\n return self.emits[func]\n\n @contextlib.contextmanager\n def _enter_func(self, func: awst_nodes.Function) -> Iterator[None]:\n self._func_stack.append(func)\n try:\n yield\n finally:\n self._func_stack.pop()\n\n @property\n def current_func(self) -> awst_nodes.Function:\n return self._func_stack[-1]\n\n def visit_emit(self, emit: awst_nodes.Emit) -> None:\n assert isinstance(emit.value.wtype, wtypes.ARC4Struct)\n self.emits[self.current_func].add(emit.value.wtype)\n\n def visit_subroutine_call_expression(self, expr: awst_nodes.SubroutineCallExpression) -> None:\n target = self.context.resolve_function_reference(\n expr.target,\n expr.source_location,\n caller=self.current_func,\n )\n self.emits[self.current_func] |= self.process_func(target)\n\n\ndef _get_arc56_type(wtype: wtypes.WType, loc: SourceLocation) -> str:\n if isinstance(wtype, wtypes.ARC4Struct):\n return wtype.name\n if isinstance(wtype, wtypes.ARC4Type):\n return wtype.arc4_name\n if wtype == wtypes.string_wtype:\n return \"AVMString\"\n storage_type = wtypes.persistable_stack_type(wtype, loc)\n match storage_type:\n case AVMType.uint64:\n return \"AVMUint64\"\n case AVMType.bytes:\n return \"AVMBytes\"\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/_contract_metadata.py","language":"Python","license":"NOASSERTION","size":14260} {"code":"from collections import deque\nfrom collections.abc import Iterator\n\nfrom puya.awst import (\n nodes as awst_nodes,\n wtypes,\n)\nfrom puya.ir import models\nfrom puya.ir.models import Parameter, Subroutine\nfrom puya.ir.types_ import wtype_to_ir_type, wtype_to_ir_types\nfrom puya.ir.utils import format_tuple_index\nfrom puya.parse import SourceLocation\nfrom puya.utils import set_add\n\n\ndef bfs_block_order(start: models.BasicBlock) -> Iterator[models.BasicBlock]:\n q = deque((start,))\n visited = {start}\n while q:\n block = q.popleft()\n yield block\n q.extend(succ for succ in block.successors if set_add(visited, succ))\n\n\ndef make_subroutine(func: awst_nodes.Function, *, allow_implicits: bool) -> Subroutine:\n \"\"\"Pre-construct subroutine with an empty body\"\"\"\n parameters = [\n param\n for arg in func.args\n for param in _expand_tuple_parameters(\n arg.name,\n arg.wtype,\n allow_implicits=allow_implicits,\n source_location=arg.source_location,\n )\n ]\n returns = wtype_to_ir_types(func.return_type)\n return Subroutine(\n id=func.full_name,\n short_name=func.short_name,\n parameters=parameters,\n returns=returns,\n body=[],\n inline=func.inline,\n source_location=func.source_location,\n )\n\n\ndef _expand_tuple_parameters(\n name: str, typ: wtypes.WType, *, allow_implicits: bool, source_location: SourceLocation | None\n) -> Iterator[Parameter]:\n if isinstance(typ, wtypes.WTuple):\n for item_idx, item_type in enumerate(typ.types):\n item_name = format_tuple_index(typ, name, item_idx)\n yield from _expand_tuple_parameters(\n item_name,\n item_type,\n allow_implicits=allow_implicits,\n source_location=source_location,\n )\n else:\n yield Parameter(\n name=name,\n ir_type=wtype_to_ir_type(typ),\n version=0,\n implicit_return=allow_implicits and not typ.immutable,\n source_location=source_location,\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/_utils.py","language":"Python","license":"NOASSERTION","size":2124} {"code":"import typing\nfrom collections.abc import Iterable, Mapping, Sequence\n\nimport attrs\n\nfrom puya import (\n artifact_metadata as md,\n log,\n)\nfrom puya.avm import OnCompletionAction\nfrom puya.awst import (\n nodes as awst_nodes,\n wtypes,\n)\nfrom puya.awst.arc4_types import maybe_avm_to_arc4_equivalent_type\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puya.utils import set_add\n\n__all__ = [\n \"create_abi_router\",\n \"AWSTContractMethodSignature\",\n]\n\nlogger = log.get_logger(__name__)\n\nALL_VALID_APPROVAL_ON_COMPLETION_ACTIONS = {\n OnCompletionAction.NoOp,\n OnCompletionAction.OptIn,\n OnCompletionAction.CloseOut,\n OnCompletionAction.UpdateApplication,\n OnCompletionAction.DeleteApplication,\n}\n\n\n@attrs.frozen(kw_only=True)\nclass AWSTContractMethodSignature:\n target: awst_nodes.ContractMethodTarget\n parameter_types: Sequence[wtypes.WType]\n return_type: wtypes.WType\n\n\ndef _btoi(\n bytes_arg: awst_nodes.Expression, location: SourceLocation | None = None\n) -> awst_nodes.IntrinsicCall:\n return awst_nodes.IntrinsicCall(\n op_code=\"btoi\",\n stack_args=[bytes_arg],\n wtype=wtypes.uint64_wtype,\n source_location=location or bytes_arg.source_location,\n )\n\n\ndef _txn(\n immediate: str, wtype: wtypes.WType, location: SourceLocation\n) -> awst_nodes.IntrinsicCall:\n return awst_nodes.IntrinsicCall(\n op_code=\"txn\",\n immediates=[immediate],\n wtype=wtype,\n source_location=location,\n )\n\n\ndef _txn_app_args(index: int, loc: SourceLocation) -> awst_nodes.IntrinsicCall:\n return awst_nodes.IntrinsicCall(\n op_code=\"txna\",\n immediates=[\"ApplicationArgs\", index],\n source_location=loc,\n wtype=wtypes.bytes_wtype,\n )\n\n\ndef create_block(\n location: SourceLocation, comment: str | None, *stmts: awst_nodes.Statement\n) -> awst_nodes.Block:\n return awst_nodes.Block(source_location=location, body=stmts, comment=comment)\n\n\ndef call(\n location: SourceLocation, sig: AWSTContractMethodSignature, *args: awst_nodes.Expression\n) -> awst_nodes.SubroutineCallExpression:\n return awst_nodes.SubroutineCallExpression(\n target=sig.target,\n args=[awst_nodes.CallArg(name=None, value=arg) for arg in args],\n wtype=sig.return_type,\n source_location=location,\n )\n\n\ndef app_arg(\n index: int,\n wtype: wtypes.WType,\n location: SourceLocation,\n) -> awst_nodes.Expression:\n value = _txn_app_args(index, location)\n if wtype == wtypes.bytes_wtype:\n return value\n return awst_nodes.ReinterpretCast(\n source_location=location,\n expr=value,\n wtype=wtype,\n )\n\n\ndef _non_zero(value: awst_nodes.Expression) -> awst_nodes.Expression:\n location = value.source_location\n return awst_nodes.NumericComparisonExpression(\n lhs=value,\n rhs=constant(0, location),\n operator=awst_nodes.NumericComparison.ne,\n source_location=location,\n )\n\n\ndef _is_zero(value: awst_nodes.Expression) -> awst_nodes.Expression:\n location = value.source_location\n return awst_nodes.NumericComparisonExpression(\n lhs=value,\n rhs=constant(0, location),\n operator=awst_nodes.NumericComparison.eq,\n source_location=location,\n )\n\n\ndef return_(value: bool, location: SourceLocation) -> awst_nodes.ReturnStatement: # noqa: FBT001\n return awst_nodes.ReturnStatement(\n value=awst_nodes.BoolConstant(value=value, source_location=location),\n source_location=location,\n )\n\n\ndef reject(location: SourceLocation) -> awst_nodes.ReturnStatement:\n return return_(False, location) # noqa: FBT003\n\n\ndef approve(location: SourceLocation) -> awst_nodes.ReturnStatement:\n return return_(True, location) # noqa: FBT003\n\n\ndef on_completion(location: SourceLocation) -> awst_nodes.Expression:\n return _txn(\"OnCompletion\", wtypes.uint64_wtype, location)\n\n\ndef route_bare_methods(\n location: SourceLocation,\n bare_methods: Mapping[md.ARC4BareMethod, AWSTContractMethodSignature],\n) -> awst_nodes.Block | None:\n bare_blocks = dict[OnCompletionAction, awst_nodes.Block]()\n for method, sig in bare_methods.items():\n bare_location = method.config_location\n bare_block = create_block(\n bare_location,\n sig.target.member_name,\n *assert_create_state(method),\n awst_nodes.ExpressionStatement(expr=call(bare_location, sig)),\n approve(bare_location),\n )\n for oca in method.allowed_completion_types:\n if bare_blocks.setdefault(oca, bare_block) is not bare_block:\n logger.error(\n f\"cannot have multiple bare methods handling the same \"\n f\"OnCompletionAction: {oca.name}\",\n location=bare_location,\n )\n return create_block(\n location,\n \"bare_routing\",\n *_maybe_switch(\n on_completion(location),\n {constant(oca.value, location): block for oca, block in bare_blocks.items()},\n ),\n )\n\n\ndef log_arc4_result(\n location: SourceLocation, result_expression: awst_nodes.Expression\n) -> awst_nodes.ExpressionStatement:\n abi_log_prefix = awst_nodes.BytesConstant(\n source_location=location,\n value=0x151F7C75.to_bytes(4),\n encoding=awst_nodes.BytesEncoding.base16,\n )\n abi_log = awst_nodes.BytesBinaryOperation(\n source_location=location,\n left=abi_log_prefix,\n op=awst_nodes.BytesBinaryOperator.add,\n right=awst_nodes.ReinterpretCast(\n expr=result_expression,\n wtype=wtypes.bytes_wtype,\n source_location=result_expression.source_location,\n ),\n )\n log_op = awst_nodes.IntrinsicCall(\n op_code=\"log\",\n stack_args=[abi_log],\n wtype=wtypes.void_wtype,\n source_location=location,\n )\n return awst_nodes.ExpressionStatement(log_op)\n\n\ndef assert_create_state(method: md.ARC4Method) -> Sequence[awst_nodes.Statement]:\n app_id = _txn(\"ApplicationID\", wtypes.uint64_wtype, method.config_location)\n match method.create:\n case awst_nodes.ARC4CreateOption.allow:\n # if create is allowed but not required, we don't need to check anything\n return ()\n case awst_nodes.ARC4CreateOption.disallow:\n condition = _non_zero(app_id)\n error_message = \"can only call when not creating\"\n case awst_nodes.ARC4CreateOption.require:\n condition = _is_zero(app_id)\n error_message = \"can only call when creating\"\n case invalid:\n typing.assert_never(invalid)\n return [\n awst_nodes.ExpressionStatement(\n awst_nodes.AssertExpression(\n condition=condition,\n error_message=error_message,\n source_location=method.config_location,\n )\n )\n ]\n\n\ndef constant(value: int, location: SourceLocation) -> awst_nodes.Expression:\n return awst_nodes.UInt64Constant(value=value, source_location=location)\n\n\ndef left_shift(value: awst_nodes.Expression, location: SourceLocation) -> awst_nodes.Expression:\n return awst_nodes.UInt64BinaryOperation(\n source_location=location,\n left=constant(1, location),\n op=awst_nodes.UInt64BinaryOperator.lshift,\n right=value,\n )\n\n\ndef bit_and(\n lhs: awst_nodes.Expression, rhs: awst_nodes.Expression, location: SourceLocation\n) -> awst_nodes.Expression:\n return awst_nodes.UInt64BinaryOperation(\n source_location=location,\n left=lhs,\n op=awst_nodes.UInt64BinaryOperator.bit_and,\n right=rhs,\n )\n\n\ndef uint64_sub(\n lhs: awst_nodes.Expression, rhs: awst_nodes.Expression, location: SourceLocation\n) -> awst_nodes.Expression:\n return awst_nodes.UInt64BinaryOperation(\n source_location=location,\n left=lhs,\n op=awst_nodes.UInt64BinaryOperator.sub,\n right=rhs,\n )\n\n\ndef bit_packed_oca(\n allowed_oca: Iterable[OnCompletionAction], location: SourceLocation\n) -> awst_nodes.Expression:\n \"\"\"Returns an integer constant, where each bit corresponding to an OnCompletionAction is\n set to 1 if that action is allowed. This allows comparing a transaction's on completion value\n against a set of allowed actions using a bitwise and op\"\"\"\n bit_packed_value = 0\n for value in allowed_oca:\n bit_packed_value |= 1 << value.value\n return constant(bit_packed_value, location)\n\n\ndef check_allowed_oca(\n allowed_ocas: Sequence[OnCompletionAction], location: SourceLocation\n) -> Sequence[awst_nodes.Statement]:\n not_allowed_ocas = sorted(\n a for a in ALL_VALID_APPROVAL_ON_COMPLETION_ACTIONS if a not in allowed_ocas\n )\n if not not_allowed_ocas:\n # all actions are allowed, don't need to check\n return ()\n match allowed_ocas, not_allowed_ocas:\n case [[single_allowed], _]:\n condition: awst_nodes.Expression = awst_nodes.NumericComparisonExpression(\n lhs=on_completion(location),\n rhs=awst_nodes.UInt64Constant(\n source_location=location,\n value=single_allowed.value,\n teal_alias=single_allowed.name,\n ),\n operator=awst_nodes.NumericComparison.eq,\n source_location=location,\n )\n case _, [single_disallowed]:\n condition = awst_nodes.NumericComparisonExpression(\n lhs=on_completion(location),\n rhs=awst_nodes.UInt64Constant(\n source_location=location,\n value=single_disallowed.value,\n teal_alias=single_disallowed.name,\n ),\n operator=awst_nodes.NumericComparison.ne,\n source_location=location,\n )\n case _:\n condition = bit_and(\n left_shift(on_completion(location), location),\n bit_packed_oca(allowed_ocas, location),\n location,\n )\n oca_desc = \", \".join(a.name for a in allowed_ocas)\n if len(allowed_ocas) > 1:\n oca_desc = f\"one of {oca_desc}\"\n return (\n awst_nodes.ExpressionStatement(\n awst_nodes.AssertExpression(\n condition=condition,\n error_message=f\"OnCompletion is not {oca_desc}\",\n source_location=location,\n )\n ),\n )\n\n\ndef _map_abi_args(\n arg_types: Sequence[wtypes.WType], location: SourceLocation\n) -> Iterable[awst_nodes.Expression]:\n transaction_arg_offset = 0\n incoming_types = []\n for a in arg_types:\n if isinstance(a, wtypes.WGroupTransaction):\n transaction_arg_offset += 1\n else:\n if isinstance(a, wtypes.ARC4Type):\n arc4_type = a\n else:\n converted = maybe_avm_to_arc4_equivalent_type(a)\n if converted is not None:\n arc4_type = converted\n elif _reference_type_array(a) is not None:\n arc4_type = wtypes.arc4_byte_alias\n else:\n raise CodeError(f\"not an ARC4 type or native equivalent: {a}\", location)\n incoming_types.append(arc4_type)\n\n if len(incoming_types) > 15:\n unpacked_types, packed_types = incoming_types[:14], incoming_types[14:]\n else:\n unpacked_types, packed_types = incoming_types, []\n abi_args = [\n app_arg(array_index, arg_wtype, location)\n for array_index, arg_wtype in enumerate(unpacked_types, start=1)\n ]\n if packed_types:\n abi_args.extend(\n awst_nodes.TupleItemExpression(\n base=app_arg(\n 15, wtypes.ARC4Tuple(types=packed_types, source_location=location), location\n ),\n index=tuple_index,\n source_location=location,\n )\n for tuple_index, _ in enumerate(packed_types)\n )\n abi_args.reverse() # reverse so we can pop off end\n\n for arg in arg_types:\n if isinstance(arg, wtypes.WGroupTransaction):\n transaction_index = uint64_sub(\n _txn(\"GroupIndex\", wtypes.uint64_wtype, location),\n constant(transaction_arg_offset, location),\n location,\n )\n yield awst_nodes.GroupTransactionReference(\n index=transaction_index, wtype=arg, source_location=location\n )\n transaction_arg_offset -= 1\n else:\n abi_arg = abi_args.pop()\n if (ref_array := _reference_type_array(arg)) is not None:\n uint64_index = _btoi(abi_arg, location)\n yield awst_nodes.IntrinsicCall(\n op_code=\"txnas\",\n immediates=[ref_array],\n stack_args=[uint64_index],\n wtype=arg,\n source_location=location,\n )\n else:\n if abi_arg.wtype != arg:\n abi_arg = awst_nodes.ARC4Decode(\n value=abi_arg, wtype=arg, source_location=location\n )\n yield abi_arg\n\n\ndef route_abi_methods(\n location: SourceLocation,\n methods: Mapping[md.ARC4ABIMethod, AWSTContractMethodSignature],\n) -> awst_nodes.Block:\n method_routing_cases = dict[awst_nodes.Expression, awst_nodes.Block]()\n seen_signatures = set[str]()\n for method, sig in methods.items():\n abi_loc = method.config_location\n abi_args = list(_map_abi_args(sig.parameter_types, location))\n method_result = call(abi_loc, sig, *abi_args)\n match sig.return_type:\n case wtypes.void_wtype:\n call_and_maybe_log = awst_nodes.ExpressionStatement(method_result)\n case wtypes.ARC4Type():\n call_and_maybe_log = log_arc4_result(abi_loc, method_result)\n case _:\n converted_return_type = maybe_avm_to_arc4_equivalent_type(sig.return_type)\n if converted_return_type is None:\n raise CodeError(f\"{sig.return_type} is not a valid ABI return type\", abi_loc)\n arc4_encoded = awst_nodes.ARC4Encode(\n value=method_result,\n wtype=converted_return_type,\n source_location=method_result.source_location,\n )\n call_and_maybe_log = log_arc4_result(abi_loc, arc4_encoded)\n\n arc4_signature = method.signature\n if not set_add(seen_signatures, arc4_signature):\n raise CodeError(\n f\"Cannot have duplicate ARC4 method signatures: {arc4_signature}\", abi_loc\n )\n method_routing_cases[\n awst_nodes.MethodConstant(source_location=location, value=arc4_signature)\n ] = create_block(\n abi_loc,\n f\"{method.name}_route\",\n *check_allowed_oca(method.allowed_completion_types, abi_loc),\n *assert_create_state(method),\n call_and_maybe_log,\n approve(abi_loc),\n )\n return create_block(\n location,\n \"abi_routing\",\n *_maybe_switch(_txn_app_args(0, location), method_routing_cases),\n )\n\n\ndef _maybe_switch(\n value: awst_nodes.Expression, cases: Mapping[awst_nodes.Expression, awst_nodes.Block]\n) -> Sequence[awst_nodes.Statement]:\n if not cases:\n return ()\n return [\n awst_nodes.Switch(\n value=value,\n cases=cases,\n default_case=None,\n source_location=value.source_location,\n )\n ]\n\n\ndef create_abi_router(\n contract: awst_nodes.Contract,\n arc4_methods_with_signatures: Mapping[md.ARC4Method, AWSTContractMethodSignature],\n) -> awst_nodes.ContractMethod:\n router_location = contract.source_location\n abi_methods = {}\n bare_methods = {}\n for method, sig in arc4_methods_with_signatures.items():\n if isinstance(method, md.ARC4BareMethod):\n bare_methods[method] = sig\n else:\n abi_methods[method] = sig\n\n abi_routing = route_abi_methods(router_location, abi_methods)\n bare_routing = route_bare_methods(router_location, bare_methods)\n num_app_args = _txn(\"NumAppArgs\", wtypes.uint64_wtype, router_location)\n router = [\n awst_nodes.IfElse(\n condition=_non_zero(num_app_args),\n if_branch=abi_routing,\n else_branch=bare_routing,\n source_location=router_location,\n ),\n reject(router_location),\n ]\n approval_program = awst_nodes.ContractMethod(\n cref=contract.id,\n member_name=\"__puya_arc4_router__\",\n source_location=router_location,\n args=[],\n return_type=wtypes.bool_wtype,\n body=create_block(router_location, None, *router),\n documentation=awst_nodes.MethodDocumentation(),\n arc4_method_config=None,\n inline=True,\n )\n return approval_program\n\n\ndef _reference_type_array(wtype: wtypes.WType) -> str | None:\n match wtype:\n case wtypes.asset_wtype:\n return \"Assets\"\n case wtypes.account_wtype:\n return \"Accounts\"\n case wtypes.application_wtype:\n return \"Applications\"\n return None\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/arc4_router.py","language":"Python","license":"NOASSERTION","size":17332} {"code":"# AUTO GENERATED BY scripts\/generate_avm_ops.py, DO NOT EDIT\nimport enum\nfrom collections.abc import Sequence\n\nfrom puya.errors import InternalError\nfrom puya.ir.avm_ops_models import (\n AVMOpData,\n DynamicVariants,\n ImmediateKind,\n OpSignature,\n RunMode,\n StackType,\n Variant,\n)\n\n\nclass AVMOp(enum.StrEnum):\n code: str\n immediate_types: Sequence[ImmediateKind]\n _variants: Variant | DynamicVariants\n cost: int | None\n min_avm_version: int\n\n def __new__(cls, data: AVMOpData | str) -> \"AVMOp\":\n # the weird union type on data && then assert,\n # is to shut mypy up when it wrongly infers the arg type of\n # e.g. AVMOp(\"+\") to be invalid\n assert isinstance(data, AVMOpData)\n op_code = data.op_code\n obj = str.__new__(cls, op_code)\n obj._value_ = op_code\n obj.code = op_code\n obj.immediate_types = tuple(data.immediate_types)\n obj._variants = data.variants # noqa: SLF001\n obj.cost = data.cost\n obj.min_avm_version = data.min_avm_version\n return obj\n\n def get_variant(self, immediates: Sequence[str | int]) -> Variant:\n if isinstance(self._variants, Variant):\n return self._variants\n im = immediates[self._variants.immediate_index]\n assert isinstance(im, str)\n try:\n return self._variants.variant_map[im]\n except KeyError as ex:\n raise InternalError(f\"Unknown immediate for {self.code}: {im}\") from ex\n\n acct_params_get = AVMOpData(\n op_code=\"acct_params_get\",\n variants=DynamicVariants(\n immediate_index=0,\n variant_map={\n \"AcctBalance\": Variant(\n signature=OpSignature(\n args=[StackType.address_or_index],\n returns=[StackType.uint64, StackType.bool],\n ),\n enum=\"AcctBalance\",\n supported_modes=RunMode.app,\n min_avm_version=6,\n ),\n \"AcctMinBalance\": Variant(\n signature=OpSignature(\n args=[StackType.address_or_index],\n returns=[StackType.uint64, StackType.bool],\n ),\n enum=\"AcctMinBalance\",\n supported_modes=RunMode.app,\n min_avm_version=6,\n ),\n \"AcctAuthAddr\": Variant(\n signature=OpSignature(\n args=[StackType.address_or_index],\n returns=[StackType.address, StackType.bool],\n ),\n enum=\"AcctAuthAddr\",\n supported_modes=RunMode.app,\n min_avm_version=6,\n ),\n \"AcctTotalNumUint\": Variant(\n signature=OpSignature(\n args=[StackType.address_or_index],\n returns=[StackType.uint64, StackType.bool],\n ),\n enum=\"AcctTotalNumUint\",\n supported_modes=RunMode.app,\n min_avm_version=8,\n ),\n \"AcctTotalNumByteSlice\": Variant(\n signature=OpSignature(\n args=[StackType.address_or_index],\n returns=[StackType.uint64, StackType.bool],\n ),\n enum=\"AcctTotalNumByteSlice\",\n supported_modes=RunMode.app,\n min_avm_version=8,\n ),\n \"AcctTotalExtraAppPages\": Variant(\n signature=OpSignature(\n args=[StackType.address_or_index],\n returns=[StackType.uint64, StackType.bool],\n ),\n enum=\"AcctTotalExtraAppPages\",\n supported_modes=RunMode.app,\n min_avm_version=8,\n ),\n \"AcctTotalAppsCreated\": Variant(\n signature=OpSignature(\n args=[StackType.address_or_index],\n returns=[StackType.uint64, StackType.bool],\n ),\n enum=\"AcctTotalAppsCreated\",\n supported_modes=RunMode.app,\n min_avm_version=8,\n ),\n \"AcctTotalAppsOptedIn\": Variant(\n signature=OpSignature(\n args=[StackType.address_or_index],\n returns=[StackType.uint64, StackType.bool],\n ),\n enum=\"AcctTotalAppsOptedIn\",\n supported_modes=RunMode.app,\n min_avm_version=8,\n ),\n \"AcctTotalAssetsCreated\": Variant(\n signature=OpSignature(\n args=[StackType.address_or_index],\n returns=[StackType.uint64, StackType.bool],\n ),\n enum=\"AcctTotalAssetsCreated\",\n supported_modes=RunMode.app,\n min_avm_version=8,\n ),\n \"AcctTotalAssets\": Variant(\n signature=OpSignature(\n args=[StackType.address_or_index],\n returns=[StackType.uint64, StackType.bool],\n ),\n enum=\"AcctTotalAssets\",\n supported_modes=RunMode.app,\n min_avm_version=8,\n ),\n \"AcctTotalBoxes\": Variant(\n signature=OpSignature(\n args=[StackType.address_or_index],\n returns=[StackType.uint64, StackType.bool],\n ),\n enum=\"AcctTotalBoxes\",\n supported_modes=RunMode.app,\n min_avm_version=8,\n ),\n \"AcctTotalBoxBytes\": Variant(\n signature=OpSignature(\n args=[StackType.address_or_index],\n returns=[StackType.uint64, StackType.bool],\n ),\n enum=\"AcctTotalBoxBytes\",\n supported_modes=RunMode.app,\n min_avm_version=8,\n ),\n \"AcctIncentiveEligible\": Variant(\n signature=OpSignature(\n args=[StackType.address_or_index], returns=[StackType.bool, StackType.bool]\n ),\n enum=\"AcctIncentiveEligible\",\n supported_modes=RunMode.app,\n min_avm_version=11,\n ),\n \"AcctLastProposed\": Variant(\n signature=OpSignature(\n args=[StackType.address_or_index],\n returns=[StackType.uint64, StackType.bool],\n ),\n enum=\"AcctLastProposed\",\n supported_modes=RunMode.app,\n min_avm_version=11,\n ),\n \"AcctLastHeartbeat\": Variant(\n signature=OpSignature(\n args=[StackType.address_or_index],\n returns=[StackType.uint64, StackType.bool],\n ),\n enum=\"AcctLastHeartbeat\",\n supported_modes=RunMode.app,\n min_avm_version=11,\n ),\n },\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=1,\n min_avm_version=6,\n supported_modes=RunMode.app,\n )\n \"\"\"\n X is field F from account A. Y is 1 if A owns positive algos, else 0\n \"\"\"\n\n add = AVMOpData(\n op_code=\"+\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.uint64]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A plus B. Fail on overflow.\n\n Overflow is an error condition which halts execution and fails the transaction. Full precision\n is available from `addw`.\n \"\"\"\n\n add_bytes = AVMOpData(\n op_code=\"b+\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bigint, StackType.bigint], returns=[StackType.bigint]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=10,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A plus B. A and B are interpreted as big-endian unsigned integers\n \"\"\"\n\n addw = AVMOpData(\n op_code=\"addw\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64],\n returns=[StackType.uint64, StackType.uint64],\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=2,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A plus B as a 128-bit result. X is the carry-bit, Y is the low-order 64 bits.\n \"\"\"\n\n and_ = AVMOpData(\n op_code=\"&&\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.bool]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A is not zero and B is not zero => {0 or 1}\n \"\"\"\n\n app_global_del = AVMOpData(\n op_code=\"app_global_del\",\n variants=Variant(\n signature=OpSignature(args=[StackType.state_key], returns=[]),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=2,\n supported_modes=RunMode.app,\n )\n \"\"\"\n delete key A from the global state of the current application\n\n params: state key.\n\n\n Deleting a key which is already absent has no effect on the application global state. (In\n particular, it does _not_ cause the program to fail.)\n \"\"\"\n\n app_global_get = AVMOpData(\n op_code=\"app_global_get\",\n variants=Variant(\n signature=OpSignature(args=[StackType.state_key], returns=[StackType.any]),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=2,\n supported_modes=RunMode.app,\n )\n \"\"\"\n global state of the key A in the current application\n\n params: state key. Return: value. The value is zero (of type uint64) if the key does not exist.\n \"\"\"\n\n app_global_get_ex = AVMOpData(\n op_code=\"app_global_get_ex\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.application, StackType.state_key],\n returns=[StackType.any, StackType.bool],\n ),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=2,\n supported_modes=RunMode.app,\n )\n \"\"\"\n X is the global state of application A, key B. Y is 1 if key existed, else 0\n\n params: Txn.ForeignApps offset (or, since v4, an _available_ application id), state key.\n Return: did_exist flag (top of the stack, 1 if the application and key existed and 0\n otherwise), value. The value is zero (of type uint64) if the key does not exist.\n \"\"\"\n\n app_global_put = AVMOpData(\n op_code=\"app_global_put\",\n variants=Variant(\n signature=OpSignature(args=[StackType.state_key, StackType.any], returns=[]),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=2,\n supported_modes=RunMode.app,\n )\n \"\"\"\n write B to key A in the global state of the current application\n \"\"\"\n\n app_local_del = AVMOpData(\n op_code=\"app_local_del\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.address_or_index, StackType.state_key], returns=[]\n ),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=2,\n supported_modes=RunMode.app,\n )\n \"\"\"\n delete key B from account A's local state of the current application\n\n params: Txn.Accounts offset (or, since v4, an _available_ account address), state key.\n\n\n Deleting a key which is already absent has no effect on the application local state. (In\n particular, it does _not_ cause the program to fail.)\n \"\"\"\n\n app_local_get = AVMOpData(\n op_code=\"app_local_get\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.address_or_index, StackType.state_key], returns=[StackType.any]\n ),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=2,\n supported_modes=RunMode.app,\n )\n \"\"\"\n local state of the key B in the current application in account A\n\n params: Txn.Accounts offset (or, since v4, an _available_ account address), state key. Return:\n value. The value is zero (of type uint64) if the key does not exist.\n \"\"\"\n\n app_local_get_ex = AVMOpData(\n op_code=\"app_local_get_ex\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.address_or_index, StackType.application, StackType.state_key],\n returns=[StackType.any, StackType.bool],\n ),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=2,\n supported_modes=RunMode.app,\n )\n \"\"\"\n X is the local state of application B, key C in account A. Y is 1 if key existed, else 0\n\n params: Txn.Accounts offset (or, since v4, an _available_ account address), _available_\n application id (or, since v4, a Txn.ForeignApps offset), state key. Return: did_exist flag (top\n of the stack, 1 if the application and key existed and 0 otherwise), value. The value is zero\n (of type uint64) if the key does not exist.\n \"\"\"\n\n app_local_put = AVMOpData(\n op_code=\"app_local_put\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.address_or_index, StackType.state_key, StackType.any], returns=[]\n ),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=2,\n supported_modes=RunMode.app,\n )\n \"\"\"\n write C to key B in account A's local state of the current application\n\n params: Txn.Accounts offset (or, since v4, an _available_ account address), state key, value.\n \"\"\"\n\n app_opted_in = AVMOpData(\n op_code=\"app_opted_in\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.address_or_index, StackType.application], returns=[StackType.bool]\n ),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=2,\n supported_modes=RunMode.app,\n )\n \"\"\"\n 1 if account A is opted in to application B, else 0\n\n params: Txn.Accounts offset (or, since v4, an _available_ account address), _available_\n application id (or, since v4, a Txn.ForeignApps offset). Return: 1 if opted in and 0 otherwise.\n \"\"\"\n\n app_params_get = AVMOpData(\n op_code=\"app_params_get\",\n variants=DynamicVariants(\n immediate_index=0,\n variant_map={\n \"AppApprovalProgram\": Variant(\n signature=OpSignature(\n args=[StackType.application], returns=[StackType.bytes, StackType.bool]\n ),\n enum=\"AppApprovalProgram\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"AppClearStateProgram\": Variant(\n signature=OpSignature(\n args=[StackType.application], returns=[StackType.bytes, StackType.bool]\n ),\n enum=\"AppClearStateProgram\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"AppGlobalNumUint\": Variant(\n signature=OpSignature(\n args=[StackType.application], returns=[StackType.uint64, StackType.bool]\n ),\n enum=\"AppGlobalNumUint\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"AppGlobalNumByteSlice\": Variant(\n signature=OpSignature(\n args=[StackType.application], returns=[StackType.uint64, StackType.bool]\n ),\n enum=\"AppGlobalNumByteSlice\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"AppLocalNumUint\": Variant(\n signature=OpSignature(\n args=[StackType.application], returns=[StackType.uint64, StackType.bool]\n ),\n enum=\"AppLocalNumUint\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"AppLocalNumByteSlice\": Variant(\n signature=OpSignature(\n args=[StackType.application], returns=[StackType.uint64, StackType.bool]\n ),\n enum=\"AppLocalNumByteSlice\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"AppExtraProgramPages\": Variant(\n signature=OpSignature(\n args=[StackType.application], returns=[StackType.uint64, StackType.bool]\n ),\n enum=\"AppExtraProgramPages\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"AppCreator\": Variant(\n signature=OpSignature(\n args=[StackType.application], returns=[StackType.address, StackType.bool]\n ),\n enum=\"AppCreator\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"AppAddress\": Variant(\n signature=OpSignature(\n args=[StackType.application], returns=[StackType.address, StackType.bool]\n ),\n enum=\"AppAddress\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n },\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=1,\n min_avm_version=5,\n supported_modes=RunMode.app,\n )\n \"\"\"\n X is field F from app A. Y is 1 if A exists, else 0\n\n params: Txn.ForeignApps offset or an _available_ app id. Return: did_exist flag (1 if the\n application existed and 0 otherwise), value.\n \"\"\"\n\n arg = AVMOpData(\n op_code=\"arg\",\n variants=Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=None,\n supported_modes=RunMode.lsig,\n min_avm_version=1,\n ),\n immediate_types=(ImmediateKind.uint8,),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.lsig,\n )\n \"\"\"\n Nth LogicSig argument\n \"\"\"\n\n arg_0 = AVMOpData(\n op_code=\"arg_0\",\n variants=Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=None,\n supported_modes=RunMode.lsig,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.lsig,\n )\n \"\"\"\n LogicSig argument 0\n \"\"\"\n\n arg_1 = AVMOpData(\n op_code=\"arg_1\",\n variants=Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=None,\n supported_modes=RunMode.lsig,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.lsig,\n )\n \"\"\"\n LogicSig argument 1\n \"\"\"\n\n arg_2 = AVMOpData(\n op_code=\"arg_2\",\n variants=Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=None,\n supported_modes=RunMode.lsig,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.lsig,\n )\n \"\"\"\n LogicSig argument 2\n \"\"\"\n\n arg_3 = AVMOpData(\n op_code=\"arg_3\",\n variants=Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=None,\n supported_modes=RunMode.lsig,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.lsig,\n )\n \"\"\"\n LogicSig argument 3\n \"\"\"\n\n args = AVMOpData(\n op_code=\"args\",\n variants=Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=None,\n supported_modes=RunMode.lsig,\n min_avm_version=5,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=5,\n supported_modes=RunMode.lsig,\n )\n \"\"\"\n Ath LogicSig argument\n \"\"\"\n\n assert_ = AVMOpData(\n op_code=\"assert\",\n variants=Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=3,\n supported_modes=RunMode.any,\n )\n \"\"\"\n immediately fail unless A is a non-zero number\n \"\"\"\n\n asset_holding_get = AVMOpData(\n op_code=\"asset_holding_get\",\n variants=DynamicVariants(\n immediate_index=0,\n variant_map={\n \"AssetBalance\": Variant(\n signature=OpSignature(\n args=[StackType.address_or_index, StackType.asset],\n returns=[StackType.uint64, StackType.bool],\n ),\n enum=\"AssetBalance\",\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n \"AssetFrozen\": Variant(\n signature=OpSignature(\n args=[StackType.address_or_index, StackType.asset],\n returns=[StackType.bool, StackType.bool],\n ),\n enum=\"AssetFrozen\",\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n },\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=1,\n min_avm_version=2,\n supported_modes=RunMode.app,\n )\n \"\"\"\n X is field F from account A's holding of asset B. Y is 1 if A is opted into B, else 0\n\n params: Txn.Accounts offset (or, since v4, an _available_ address), asset id (or, since v4, a\n Txn.ForeignAssets offset). Return: did_exist flag (1 if the asset existed and 0 otherwise),\n value.\n \"\"\"\n\n asset_params_get = AVMOpData(\n op_code=\"asset_params_get\",\n variants=DynamicVariants(\n immediate_index=0,\n variant_map={\n \"AssetTotal\": Variant(\n signature=OpSignature(\n args=[StackType.asset], returns=[StackType.uint64, StackType.bool]\n ),\n enum=\"AssetTotal\",\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n \"AssetDecimals\": Variant(\n signature=OpSignature(\n args=[StackType.asset], returns=[StackType.uint64, StackType.bool]\n ),\n enum=\"AssetDecimals\",\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n \"AssetDefaultFrozen\": Variant(\n signature=OpSignature(\n args=[StackType.asset], returns=[StackType.bool, StackType.bool]\n ),\n enum=\"AssetDefaultFrozen\",\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n \"AssetUnitName\": Variant(\n signature=OpSignature(\n args=[StackType.asset], returns=[StackType.bytes, StackType.bool]\n ),\n enum=\"AssetUnitName\",\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n \"AssetName\": Variant(\n signature=OpSignature(\n args=[StackType.asset], returns=[StackType.bytes, StackType.bool]\n ),\n enum=\"AssetName\",\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n \"AssetURL\": Variant(\n signature=OpSignature(\n args=[StackType.asset], returns=[StackType.bytes, StackType.bool]\n ),\n enum=\"AssetURL\",\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n \"AssetMetadataHash\": Variant(\n signature=OpSignature(\n args=[StackType.asset], returns=[StackType.bytes, StackType.bool]\n ),\n enum=\"AssetMetadataHash\",\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n \"AssetManager\": Variant(\n signature=OpSignature(\n args=[StackType.asset], returns=[StackType.address, StackType.bool]\n ),\n enum=\"AssetManager\",\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n \"AssetReserve\": Variant(\n signature=OpSignature(\n args=[StackType.asset], returns=[StackType.address, StackType.bool]\n ),\n enum=\"AssetReserve\",\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n \"AssetFreeze\": Variant(\n signature=OpSignature(\n args=[StackType.asset], returns=[StackType.address, StackType.bool]\n ),\n enum=\"AssetFreeze\",\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n \"AssetClawback\": Variant(\n signature=OpSignature(\n args=[StackType.asset], returns=[StackType.address, StackType.bool]\n ),\n enum=\"AssetClawback\",\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n \"AssetCreator\": Variant(\n signature=OpSignature(\n args=[StackType.asset], returns=[StackType.address, StackType.bool]\n ),\n enum=\"AssetCreator\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n },\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=1,\n min_avm_version=2,\n supported_modes=RunMode.app,\n )\n \"\"\"\n X is field F from asset A. Y is 1 if A exists, else 0\n\n params: Txn.ForeignAssets offset (or, since v4, an _available_ asset id. Return: did_exist flag\n (1 if the asset existed and 0 otherwise), value.\n \"\"\"\n\n balance = AVMOpData(\n op_code=\"balance\",\n variants=Variant(\n signature=OpSignature(args=[StackType.address_or_index], returns=[StackType.uint64]),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=2,\n supported_modes=RunMode.app,\n )\n \"\"\"\n balance for account A, in microalgos. The balance is observed after the effects of previous\n transactions in the group, and after the fee for the current transaction is deducted. Changes\n caused by inner transactions are observable immediately following `itxn_submit`\n\n params: Txn.Accounts offset (or, since v4, an _available_ account address), _available_\n application id (or, since v4, a Txn.ForeignApps offset). Return: value.\n \"\"\"\n\n base64_decode = AVMOpData(\n op_code=\"base64_decode\",\n variants=Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[StackType.bytes]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=None,\n min_avm_version=7,\n supported_modes=RunMode.any,\n )\n \"\"\"\n decode A which was base64-encoded using _encoding_ E. Fail if A is not base64 encoded with\n encoding E\n\n *Warning*: Usage should be restricted to very rare use cases. In almost all cases, smart\n contracts should directly handle non-encoded byte-strings. This opcode should only be used\n in cases where base64 is the only available option, e.g. interoperability with a third-party\n that only signs base64 strings.\n\n\n Decodes A using the base64 encoding E. Specify the encoding with an immediate arg either as\n URL and Filename Safe (`URLEncoding`) or Standard (`StdEncoding`). See [RFC 4648 sections 4 and\n 5](https:\/\/rfc-editor.org\/rfc\/rfc4648.html#section-4). It is assumed that the encoding ends\n with the exact number of `=` padding characters as required by the RFC. When padding occurs,\n any unused pad bits in the encoding must be set to zero or the decoding will fail. The special\n cases of `\\n` and `\\r` are allowed but completely ignored. An error will result when attempting\n to decode a string with a character that is not in the encoding alphabet or not one of `=`,\n `\\r`, or `\\n`.\n \"\"\"\n\n bitlen = AVMOpData(\n op_code=\"bitlen\",\n variants=Variant(\n signature=OpSignature(args=[StackType.any], returns=[StackType.uint64]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n The highest set bit in A. If A is a byte-array, it is interpreted as a big-endian unsigned\n integer. bitlen of 0 is 0, bitlen of 8 is 4\n\n bitlen interprets arrays as big-endian integers, unlike setbit\/getbit\n \"\"\"\n\n bitwise_and = AVMOpData(\n op_code=\"&\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.uint64]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A bitwise-and B\n \"\"\"\n\n bitwise_and_bytes = AVMOpData(\n op_code=\"b&\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.bytes], returns=[StackType.bytes]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=6,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A bitwise-and B. A and B are zero-left extended to the greater of their lengths\n \"\"\"\n\n bitwise_not = AVMOpData(\n op_code=\"~\",\n variants=Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n bitwise invert value A\n \"\"\"\n\n bitwise_not_bytes = AVMOpData(\n op_code=\"b~\",\n variants=Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[StackType.bytes]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=4,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A with all bits inverted\n \"\"\"\n\n bitwise_or = AVMOpData(\n op_code=\"|\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.uint64]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A bitwise-or B\n \"\"\"\n\n bitwise_or_bytes = AVMOpData(\n op_code=\"b|\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.bytes], returns=[StackType.bytes]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=6,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A bitwise-or B. A and B are zero-left extended to the greater of their lengths\n \"\"\"\n\n bitwise_xor = AVMOpData(\n op_code=\"^\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.uint64]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A bitwise-xor B\n \"\"\"\n\n bitwise_xor_bytes = AVMOpData(\n op_code=\"b^\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.bytes], returns=[StackType.bytes]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=6,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A bitwise-xor B. A and B are zero-left extended to the greater of their lengths\n \"\"\"\n\n block = AVMOpData(\n op_code=\"block\",\n variants=DynamicVariants(\n immediate_index=0,\n variant_map={\n \"BlkSeed\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"BlkSeed\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"BlkTimestamp\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"BlkTimestamp\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"BlkProposer\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.address]),\n enum=\"BlkProposer\",\n supported_modes=RunMode.any,\n min_avm_version=11,\n ),\n \"BlkFeesCollected\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"BlkFeesCollected\",\n supported_modes=RunMode.any,\n min_avm_version=11,\n ),\n \"BlkBonus\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"BlkBonus\",\n supported_modes=RunMode.any,\n min_avm_version=11,\n ),\n \"BlkBranch\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"BlkBranch\",\n supported_modes=RunMode.any,\n min_avm_version=11,\n ),\n \"BlkFeeSink\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.address]),\n enum=\"BlkFeeSink\",\n supported_modes=RunMode.any,\n min_avm_version=11,\n ),\n \"BlkProtocol\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"BlkProtocol\",\n supported_modes=RunMode.any,\n min_avm_version=11,\n ),\n \"BlkTxnCounter\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"BlkTxnCounter\",\n supported_modes=RunMode.any,\n min_avm_version=11,\n ),\n \"BlkProposerPayout\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"BlkProposerPayout\",\n supported_modes=RunMode.any,\n min_avm_version=11,\n ),\n },\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=1,\n min_avm_version=7,\n supported_modes=RunMode.any,\n )\n \"\"\"\n field F of block A. Fail unless A falls between txn.LastValid-1002 and txn.FirstValid\n (exclusive)\n \"\"\"\n\n box_create = AVMOpData(\n op_code=\"box_create\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.box_name, StackType.uint64], returns=[StackType.bool]\n ),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=8,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=8,\n supported_modes=RunMode.app,\n )\n \"\"\"\n create a box named A, of length B. Fail if the name A is empty or B exceeds 32,768. Returns 0\n if A already existed, else 1\n\n Newly created boxes are filled with 0 bytes. `box_create` will fail if the referenced box\n already exists with a different size. Otherwise, existing boxes are unchanged by `box_create`.\n \"\"\"\n\n box_del = AVMOpData(\n op_code=\"box_del\",\n variants=Variant(\n signature=OpSignature(args=[StackType.box_name], returns=[StackType.bool]),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=8,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=8,\n supported_modes=RunMode.app,\n )\n \"\"\"\n delete box named A if it exists. Return 1 if A existed, 0 otherwise\n \"\"\"\n\n box_extract = AVMOpData(\n op_code=\"box_extract\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.box_name, StackType.uint64, StackType.uint64],\n returns=[StackType.bytes],\n ),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=8,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=8,\n supported_modes=RunMode.app,\n )\n \"\"\"\n read C bytes from box A, starting at offset B. Fail if A does not exist, or the byte range is\n outside A's size.\n \"\"\"\n\n box_get = AVMOpData(\n op_code=\"box_get\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.box_name], returns=[StackType.bytes, StackType.bool]\n ),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=8,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=8,\n supported_modes=RunMode.app,\n )\n \"\"\"\n X is the contents of box A if A exists, else ''. Y is 1 if A exists, else 0.\n\n For boxes that exceed 4,096 bytes, consider `box_create`, `box_extract`, and `box_replace`\n \"\"\"\n\n box_len = AVMOpData(\n op_code=\"box_len\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.box_name], returns=[StackType.uint64, StackType.bool]\n ),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=8,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=8,\n supported_modes=RunMode.app,\n )\n \"\"\"\n X is the length of box A if A exists, else 0. Y is 1 if A exists, else 0.\n \"\"\"\n\n box_put = AVMOpData(\n op_code=\"box_put\",\n variants=Variant(\n signature=OpSignature(args=[StackType.box_name, StackType.bytes], returns=[]),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=8,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=8,\n supported_modes=RunMode.app,\n )\n \"\"\"\n replaces the contents of box A with byte-array B. Fails if A exists and len(B) != len(box A).\n Creates A if it does not exist\n\n For boxes that exceed 4,096 bytes, consider `box_create`, `box_extract`, and `box_replace`\n \"\"\"\n\n box_replace = AVMOpData(\n op_code=\"box_replace\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.box_name, StackType.uint64, StackType.bytes], returns=[]\n ),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=8,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=8,\n supported_modes=RunMode.app,\n )\n \"\"\"\n write byte-array C into box A, starting at offset B. Fail if A does not exist, or the byte\n range is outside A's size.\n \"\"\"\n\n box_resize = AVMOpData(\n op_code=\"box_resize\",\n variants=Variant(\n signature=OpSignature(args=[StackType.box_name, StackType.uint64], returns=[]),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=10,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=10,\n supported_modes=RunMode.app,\n )\n \"\"\"\n change the size of box named A to be of length B, adding zero bytes to end or removing bytes\n from the end, as needed. Fail if the name A is empty, A is not an existing box, or B exceeds\n 32,768.\n \"\"\"\n\n box_splice = AVMOpData(\n op_code=\"box_splice\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.box_name, StackType.uint64, StackType.uint64, StackType.bytes],\n returns=[],\n ),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=10,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=10,\n supported_modes=RunMode.app,\n )\n \"\"\"\n set box A to contain its previous bytes up to index B, followed by D, followed by the original\n bytes of A that began at index B+C.\n\n Boxes are of constant length. If C < len(D), then len(D)-C bytes will be removed from the end.\n If C > len(D), zero bytes will be appended to the end to reach the box length.\n \"\"\"\n\n bsqrt = AVMOpData(\n op_code=\"bsqrt\",\n variants=Variant(\n signature=OpSignature(args=[StackType.bigint], returns=[StackType.bigint]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=6,\n ),\n immediate_types=(),\n cost=40,\n min_avm_version=6,\n supported_modes=RunMode.any,\n )\n \"\"\"\n The largest integer I such that I^2 <= A. A and I are interpreted as big-endian unsigned\n integers\n \"\"\"\n\n btoi = AVMOpData(\n op_code=\"btoi\",\n variants=Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[StackType.uint64]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n converts big-endian byte array A to uint64. Fails if len(A) > 8. Padded by leading 0s if len(A)\n < 8.\n\n `btoi` fails if the input is longer than 8 bytes.\n \"\"\"\n\n bzero = AVMOpData(\n op_code=\"bzero\",\n variants=Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n zero filled byte-array of length A\n \"\"\"\n\n concat = AVMOpData(\n op_code=\"concat\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.bytes], returns=[StackType.bytes]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=2,\n supported_modes=RunMode.any,\n )\n \"\"\"\n join A and B\n\n `concat` fails if the result would be greater than 4096 bytes.\n \"\"\"\n\n div_floor = AVMOpData(\n op_code=\"\/\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.uint64]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A divided by B (truncated division). Fail if B == 0.\n\n `divmodw` is available to divide the two-element values produced by `mulw` and `addw`.\n \"\"\"\n\n div_floor_bytes = AVMOpData(\n op_code=\"b\/\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bigint, StackType.bigint], returns=[StackType.bigint]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=20,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A divided by B (truncated division). A and B are interpreted as big-endian unsigned integers.\n Fail if B is zero.\n \"\"\"\n\n divmodw = AVMOpData(\n op_code=\"divmodw\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64, StackType.uint64, StackType.uint64],\n returns=[StackType.uint64, StackType.uint64, StackType.uint64, StackType.uint64],\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=20,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n W,X = (A,B \/ C,D); Y,Z = (A,B modulo C,D)\n\n The notation J,K indicates that two uint64 values J and K are interpreted as a uint128 value,\n with J as the high uint64 and K the low.\n \"\"\"\n\n divw = AVMOpData(\n op_code=\"divw\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64, StackType.uint64],\n returns=[StackType.uint64],\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=6,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=6,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A,B \/ C. Fail if C == 0 or if result overflows.\n\n The notation A,B indicates that A and B are interpreted as a uint128 value, with A as the high\n uint64 and B the low.\n \"\"\"\n\n ec_add = AVMOpData(\n op_code=\"ec_add\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.bytes], returns=[StackType.bytes]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=10,\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=None,\n min_avm_version=10,\n supported_modes=RunMode.any,\n )\n \"\"\"\n for curve points A and B, return the curve point A + B\n\n A and B are curve points in affine representation: field element X concatenated with field\n element Y. Field element `Z` is encoded as follows.\n\n For the base field elements (Fp), `Z` is encoded as a big-endian number and must be lower than\n the field modulus.\n\n For the quadratic field extension (Fp2), `Z` is encoded as the concatenation of the individual\n encoding of the coefficients. For an Fp2 element of the form `Z = Z0 + Z1 i`, where `i` is a\n formal quadratic non-residue, the encoding of Z is the concatenation of the encoding of `Z0`\n and `Z1` in this order. (`Z0` and `Z1` must be less than the field modulus).\n\n\n The point at infinity is encoded as `(X,Y) = (0,0)`.\n\n Groups G1 and G2 are denoted additively.\n\n\n Fails if A or B is not in G.\n\n A and\/or B are allowed to be the point at infinity.\n\n Does _not_ check if A and B are in the main prime-order subgroup.\n \"\"\"\n\n ec_map_to = AVMOpData(\n op_code=\"ec_map_to\",\n variants=Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[StackType.bytes]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=10,\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=None,\n min_avm_version=10,\n supported_modes=RunMode.any,\n )\n \"\"\"\n maps field element A to group G\n\n BN254 points are mapped by the SVDW map. BLS12-381 points are mapped by the SSWU map.\n\n G1 element inputs are base field elements and G2 element inputs are quadratic field elements,\n with nearly the same encoding rules (for field elements) as defined in `ec_add`. There is one\n difference of encoding rule: G1 element inputs do not need to be 0-padded if they fit in less\n than 32 bytes for BN254 and less than 48 bytes for BLS12-381. (As usual, the empty byte array\n represents 0.) G2 elements inputs need to be always have the required size.\n \"\"\"\n\n ec_multi_scalar_mul = AVMOpData(\n op_code=\"ec_multi_scalar_mul\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.bytes], returns=[StackType.bytes]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=10,\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=None,\n min_avm_version=10,\n supported_modes=RunMode.any,\n )\n \"\"\"\n for curve points A and scalars B, return curve point B0A0 + B1A1 + B2A2 + ... + BnAn\n\n A is a list of concatenated points, encoded and checked as described in `ec_add`. B is a list\n of concatenated scalars which, unlike ec_scalar_mul, must all be exactly 32 bytes long.\n\n The name `ec_multi_scalar_mul` was chosen to reflect common usage, but a more consistent name\n would be `ec_multi_scalar_mul`. AVM values are limited to 4096 bytes, so `ec_multi_scalar_mul`\n is limited by the size of the points in the group being operated upon.\n \"\"\"\n\n ec_pairing_check = AVMOpData(\n op_code=\"ec_pairing_check\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.bytes], returns=[StackType.bool]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=10,\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=None,\n min_avm_version=10,\n supported_modes=RunMode.any,\n )\n \"\"\"\n 1 if the product of the pairing of each point in A with its respective point in B is equal to\n the identity element of the target group Gt, else 0\n\n A and B are concatenated points, encoded and checked as described in `ec_add`. A contains\n points of the group G, B contains points of the associated group (G2 if G is G1, and vice\n versa). Fails if A and B have a different number of points, or if any point is not in its\n described group or outside the main prime-order subgroup - a stronger condition than other\n opcodes. AVM values are limited to 4096 bytes, so `ec_pairing_check` is limited by the size of\n the points in the groups being operated upon.\n \"\"\"\n\n ec_scalar_mul = AVMOpData(\n op_code=\"ec_scalar_mul\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.bytes], returns=[StackType.bytes]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=10,\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=None,\n min_avm_version=10,\n supported_modes=RunMode.any,\n )\n \"\"\"\n for curve point A and scalar B, return the curve point BA, the point A multiplied by the scalar\n B.\n\n A is a curve point encoded and checked as described in `ec_add`. Scalar B is interpreted as a\n big-endian unsigned integer. Fails if B exceeds 32 bytes.\n \"\"\"\n\n ec_subgroup_check = AVMOpData(\n op_code=\"ec_subgroup_check\",\n variants=Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[StackType.bool]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=10,\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=None,\n min_avm_version=10,\n supported_modes=RunMode.any,\n )\n \"\"\"\n 1 if A is in the main prime-order subgroup of G (including the point at infinity) else 0.\n Program fails if A is not in G at all.\n \"\"\"\n\n ecdsa_pk_decompress = AVMOpData(\n op_code=\"ecdsa_pk_decompress\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes], returns=[StackType.bytes, StackType.bytes]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=5,\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=None,\n min_avm_version=5,\n supported_modes=RunMode.any,\n )\n \"\"\"\n decompress pubkey A into components X, Y\n\n The 33 byte public key in a compressed form to be decompressed into X and Y (top) components.\n All values are big-endian encoded.\n \"\"\"\n\n ecdsa_pk_recover = AVMOpData(\n op_code=\"ecdsa_pk_recover\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.uint64, StackType.bytes, StackType.bytes],\n returns=[StackType.bytes, StackType.bytes],\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=5,\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=2000,\n min_avm_version=5,\n supported_modes=RunMode.any,\n )\n \"\"\"\n for (data A, recovery id B, signature C, D) recover a public key\n\n S (top) and R elements of a signature, recovery id and data (bottom) are expected on the stack\n and used to deriver a public key. All values are big-endian encoded. The signed data must be 32\n bytes long.\n \"\"\"\n\n ecdsa_verify = AVMOpData(\n op_code=\"ecdsa_verify\",\n variants=Variant(\n signature=OpSignature(\n args=[\n StackType.bytes,\n StackType.bytes,\n StackType.bytes,\n StackType.bytes,\n StackType.bytes,\n ],\n returns=[StackType.bool],\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=5,\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=None,\n min_avm_version=5,\n supported_modes=RunMode.any,\n )\n \"\"\"\n for (data A, signature B, C and pubkey D, E) verify the signature of the data against the\n pubkey => {0 or 1}\n\n The 32 byte Y-component of a public key is the last element on the stack, preceded by\n X-component of a pubkey, preceded by S and R components of a signature, preceded by the data\n that is fifth element on the stack. All values are big-endian encoded. The signed data must be\n 32 bytes long, and signatures in lower-S form are only accepted.\n \"\"\"\n\n ed25519verify = AVMOpData(\n op_code=\"ed25519verify\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.bytes, StackType.bytes], returns=[StackType.bool]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1900,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n for (data A, signature B, pubkey C) verify the signature of (\"ProgData\" || program_hash ||\n data) against the pubkey => {0 or 1}\n\n The 32 byte public key is the last element on the stack, preceded by the 64 byte signature at\n the second-to-last element on the stack, preceded by the data which was signed at the third-to-\n last element on the stack.\n \"\"\"\n\n ed25519verify_bare = AVMOpData(\n op_code=\"ed25519verify_bare\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.bytes, StackType.bytes], returns=[StackType.bool]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n immediate_types=(),\n cost=1900,\n min_avm_version=7,\n supported_modes=RunMode.any,\n )\n \"\"\"\n for (data A, signature B, pubkey C) verify the signature of the data against the pubkey => {0\n or 1}\n \"\"\"\n\n eq = AVMOpData(\n op_code=\"==\",\n variants=Variant(\n signature=OpSignature(args=[StackType.any, StackType.any], returns=[StackType.bool]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A is equal to B => {0 or 1}\n \"\"\"\n\n eq_bytes = AVMOpData(\n op_code=\"b==\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bigint, StackType.bigint], returns=[StackType.bool]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n 1 if A is equal to B, else 0. A and B are interpreted as big-endian unsigned integers\n \"\"\"\n\n exp = AVMOpData(\n op_code=\"exp\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.uint64]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A raised to the Bth power. Fail if A == B == 0 and on overflow\n \"\"\"\n\n expw = AVMOpData(\n op_code=\"expw\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64],\n returns=[StackType.uint64, StackType.uint64],\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=10,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A raised to the Bth power as a 128-bit result in two uint64s. X is the high 64 bits, Y is the\n low. Fail if A == B == 0 or if the results exceeds 2^128-1\n \"\"\"\n\n extract = AVMOpData(\n op_code=\"extract\",\n variants=Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[StackType.bytes]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=5,\n ),\n immediate_types=(ImmediateKind.uint8, ImmediateKind.uint8),\n cost=1,\n min_avm_version=5,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A range of bytes from A starting at S up to but not including S+L. If L is 0, then extract to\n the end of the string. If S or S+L is larger than the array length, the program fails\n \"\"\"\n\n extract3 = AVMOpData(\n op_code=\"extract3\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.uint64, StackType.uint64],\n returns=[StackType.bytes],\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=5,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=5,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A range of bytes from A starting at B up to but not including B+C. If B+C is larger than the\n array length, the program fails\n\n `extract3` can be called using `extract` with no immediates.\n \"\"\"\n\n extract_uint16 = AVMOpData(\n op_code=\"extract_uint16\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.uint64], returns=[StackType.uint64]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=5,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=5,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A uint16 formed from a range of big-endian bytes from A starting at B up to but not including\n B+2. If B+2 is larger than the array length, the program fails\n \"\"\"\n\n extract_uint32 = AVMOpData(\n op_code=\"extract_uint32\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.uint64], returns=[StackType.uint64]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=5,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=5,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A uint32 formed from a range of big-endian bytes from A starting at B up to but not including\n B+4. If B+4 is larger than the array length, the program fails\n \"\"\"\n\n extract_uint64 = AVMOpData(\n op_code=\"extract_uint64\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.uint64], returns=[StackType.uint64]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=5,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=5,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A uint64 formed from a range of big-endian bytes from A starting at B up to but not including\n B+8. If B+8 is larger than the array length, the program fails\n \"\"\"\n\n falcon_verify = AVMOpData(\n op_code=\"falcon_verify\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.bytes, StackType.bytes], returns=[StackType.bool]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=12,\n ),\n immediate_types=(),\n cost=1700,\n min_avm_version=12,\n supported_modes=RunMode.any,\n )\n \"\"\"\n for (data A, compressed-format signature B, pubkey C) verify the signature of data against the\n pubkey\n \"\"\"\n\n gaid = AVMOpData(\n op_code=\"gaid\",\n variants=Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=4,\n ),\n immediate_types=(ImmediateKind.uint8,),\n cost=1,\n min_avm_version=4,\n supported_modes=RunMode.app,\n )\n \"\"\"\n ID of the asset or application created in the Tth transaction of the current group\n\n `gaid` fails unless the requested transaction created an asset or application and T <\n GroupIndex.\n \"\"\"\n\n gaids = AVMOpData(\n op_code=\"gaids\",\n variants=Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=4,\n supported_modes=RunMode.app,\n )\n \"\"\"\n ID of the asset or application created in the Ath transaction of the current group\n\n `gaids` fails unless the requested transaction created an asset or application and A <\n GroupIndex.\n \"\"\"\n\n getbit = AVMOpData(\n op_code=\"getbit\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.any, StackType.uint64], returns=[StackType.uint64]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=3,\n supported_modes=RunMode.any,\n )\n \"\"\"\n Bth bit of (byte-array or integer) A. If B is greater than or equal to the bit length of the\n value (8*byte length), the program fails\n\n see explanation of bit ordering in setbit\n \"\"\"\n\n getbyte = AVMOpData(\n op_code=\"getbyte\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.uint64], returns=[StackType.uint64]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=3,\n supported_modes=RunMode.any,\n )\n \"\"\"\n Bth byte of A, as an integer. If B is greater than or equal to the array length, the program\n fails\n \"\"\"\n\n gitxn = AVMOpData(\n op_code=\"gitxn\",\n variants=DynamicVariants(\n immediate_index=1,\n variant_map={\n \"Sender\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"Sender\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Fee\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"Fee\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"FirstValid\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"FirstValid\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"FirstValidTime\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"FirstValidTime\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"LastValid\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"LastValid\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Note\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"Note\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Lease\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"Lease\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Receiver\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"Receiver\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Amount\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"Amount\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"CloseRemainderTo\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"CloseRemainderTo\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VotePK\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"VotePK\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"SelectionPK\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"SelectionPK\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VoteFirst\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"VoteFirst\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VoteLast\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"VoteLast\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VoteKeyDilution\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"VoteKeyDilution\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Type\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"Type\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"TypeEnum\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"TypeEnum\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"XferAsset\": Variant(\n signature=OpSignature(args=[], returns=[StackType.asset]),\n enum=\"XferAsset\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetAmount\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"AssetAmount\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetSender\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"AssetSender\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetReceiver\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"AssetReceiver\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetCloseTo\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"AssetCloseTo\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"GroupIndex\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"GroupIndex\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"TxID\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"TxID\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"ApplicationID\": Variant(\n signature=OpSignature(args=[], returns=[StackType.application]),\n enum=\"ApplicationID\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"OnCompletion\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"OnCompletion\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ApplicationArgs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ApplicationArgs\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"NumAppArgs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumAppArgs\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Accounts\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"Accounts\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"NumAccounts\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumAccounts\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ApprovalProgram\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ApprovalProgram\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ClearStateProgram\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ClearStateProgram\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"RekeyTo\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"RekeyTo\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAsset\": Variant(\n signature=OpSignature(args=[], returns=[StackType.asset]),\n enum=\"ConfigAsset\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetTotal\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"ConfigAssetTotal\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetDecimals\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"ConfigAssetDecimals\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetDefaultFrozen\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bool]),\n enum=\"ConfigAssetDefaultFrozen\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetUnitName\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ConfigAssetUnitName\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetName\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ConfigAssetName\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetURL\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ConfigAssetURL\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetMetadataHash\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ConfigAssetMetadataHash\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetManager\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"ConfigAssetManager\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetReserve\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"ConfigAssetReserve\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetFreeze\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"ConfigAssetFreeze\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetClawback\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"ConfigAssetClawback\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"FreezeAsset\": Variant(\n signature=OpSignature(args=[], returns=[StackType.asset]),\n enum=\"FreezeAsset\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"FreezeAssetAccount\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"FreezeAssetAccount\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"FreezeAssetFrozen\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bool]),\n enum=\"FreezeAssetFrozen\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Assets\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"Assets\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"NumAssets\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumAssets\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Applications\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"Applications\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"NumApplications\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumApplications\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"GlobalNumUint\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"GlobalNumUint\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"GlobalNumByteSlice\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"GlobalNumByteSlice\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"LocalNumUint\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"LocalNumUint\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"LocalNumByteSlice\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"LocalNumByteSlice\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"ExtraProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"ExtraProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n \"Nonparticipation\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bool]),\n enum=\"Nonparticipation\",\n supported_modes=RunMode.any,\n min_avm_version=5,\n ),\n \"Logs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"Logs\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"NumLogs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumLogs\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"CreatedAssetID\": Variant(\n signature=OpSignature(args=[], returns=[StackType.asset]),\n enum=\"CreatedAssetID\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"CreatedApplicationID\": Variant(\n signature=OpSignature(args=[], returns=[StackType.application]),\n enum=\"CreatedApplicationID\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"LastLog\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"LastLog\",\n supported_modes=RunMode.app,\n min_avm_version=6,\n ),\n \"StateProofPK\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"StateProofPK\",\n supported_modes=RunMode.any,\n min_avm_version=6,\n ),\n \"ApprovalProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ApprovalProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"NumApprovalProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumApprovalProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"ClearStateProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ClearStateProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"NumClearStateProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumClearStateProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n },\n ),\n immediate_types=(ImmediateKind.uint8, ImmediateKind.arg_enum),\n cost=1,\n min_avm_version=6,\n supported_modes=RunMode.app,\n )\n \"\"\"\n field F of the Tth transaction in the last inner group submitted\n \"\"\"\n\n gitxna = AVMOpData(\n op_code=\"gitxna\",\n variants=DynamicVariants(\n immediate_index=1,\n variant_map={\n \"ApplicationArgs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ApplicationArgs\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Accounts\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"Accounts\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Assets\": Variant(\n signature=OpSignature(args=[], returns=[StackType.asset]),\n enum=\"Assets\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Applications\": Variant(\n signature=OpSignature(args=[], returns=[StackType.application]),\n enum=\"Applications\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Logs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"Logs\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"ApprovalProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ApprovalProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"ClearStateProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ClearStateProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n },\n ),\n immediate_types=(ImmediateKind.uint8, ImmediateKind.arg_enum, ImmediateKind.uint8),\n cost=1,\n min_avm_version=6,\n supported_modes=RunMode.app,\n )\n \"\"\"\n Ith value of the array field F from the Tth transaction in the last inner group submitted\n \"\"\"\n\n gitxnas = AVMOpData(\n op_code=\"gitxnas\",\n variants=DynamicVariants(\n immediate_index=1,\n variant_map={\n \"ApplicationArgs\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ApplicationArgs\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Accounts\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.address]),\n enum=\"Accounts\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Assets\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.asset]),\n enum=\"Assets\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Applications\": Variant(\n signature=OpSignature(\n args=[StackType.uint64], returns=[StackType.application]\n ),\n enum=\"Applications\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Logs\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"Logs\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"ApprovalProgramPages\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ApprovalProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"ClearStateProgramPages\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ClearStateProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n },\n ),\n immediate_types=(ImmediateKind.uint8, ImmediateKind.arg_enum),\n cost=1,\n min_avm_version=6,\n supported_modes=RunMode.app,\n )\n \"\"\"\n Ath value of the array field F from the Tth transaction in the last inner group submitted\n \"\"\"\n\n gload = AVMOpData(\n op_code=\"gload\",\n variants=Variant(\n signature=OpSignature(args=[], returns=[StackType.any]),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=4,\n ),\n immediate_types=(ImmediateKind.uint8, ImmediateKind.uint8),\n cost=1,\n min_avm_version=4,\n supported_modes=RunMode.app,\n )\n \"\"\"\n Ith scratch space value of the Tth transaction in the current group\n\n `gload` fails unless the requested transaction is an ApplicationCall and T < GroupIndex.\n \"\"\"\n\n gloads = AVMOpData(\n op_code=\"gloads\",\n variants=Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.any]),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=4,\n ),\n immediate_types=(ImmediateKind.uint8,),\n cost=1,\n min_avm_version=4,\n supported_modes=RunMode.app,\n )\n \"\"\"\n Ith scratch space value of the Ath transaction in the current group\n\n `gloads` fails unless the requested transaction is an ApplicationCall and A < GroupIndex.\n \"\"\"\n\n gloadss = AVMOpData(\n op_code=\"gloadss\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.any]\n ),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=6,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=6,\n supported_modes=RunMode.app,\n )\n \"\"\"\n Bth scratch space value of the Ath transaction in the current group\n \"\"\"\n\n global_ = AVMOpData(\n op_code=\"global\",\n variants=DynamicVariants(\n immediate_index=0,\n variant_map={\n \"MinTxnFee\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"MinTxnFee\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"MinBalance\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"MinBalance\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"MaxTxnLife\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"MaxTxnLife\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"ZeroAddress\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"ZeroAddress\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"GroupSize\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"GroupSize\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"LogicSigVersion\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"LogicSigVersion\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Round\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"Round\",\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n \"LatestTimestamp\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"LatestTimestamp\",\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n \"CurrentApplicationID\": Variant(\n signature=OpSignature(args=[], returns=[StackType.application]),\n enum=\"CurrentApplicationID\",\n supported_modes=RunMode.app,\n min_avm_version=2,\n ),\n \"CreatorAddress\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"CreatorAddress\",\n supported_modes=RunMode.app,\n min_avm_version=3,\n ),\n \"CurrentApplicationAddress\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"CurrentApplicationAddress\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"GroupID\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"GroupID\",\n supported_modes=RunMode.any,\n min_avm_version=5,\n ),\n \"OpcodeBudget\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"OpcodeBudget\",\n supported_modes=RunMode.any,\n min_avm_version=6,\n ),\n \"CallerApplicationID\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"CallerApplicationID\",\n supported_modes=RunMode.app,\n min_avm_version=6,\n ),\n \"CallerApplicationAddress\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"CallerApplicationAddress\",\n supported_modes=RunMode.app,\n min_avm_version=6,\n ),\n \"AssetCreateMinBalance\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"AssetCreateMinBalance\",\n supported_modes=RunMode.any,\n min_avm_version=10,\n ),\n \"AssetOptInMinBalance\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"AssetOptInMinBalance\",\n supported_modes=RunMode.any,\n min_avm_version=10,\n ),\n \"GenesisHash\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"GenesisHash\",\n supported_modes=RunMode.any,\n min_avm_version=10,\n ),\n \"PayoutsEnabled\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bool]),\n enum=\"PayoutsEnabled\",\n supported_modes=RunMode.any,\n min_avm_version=11,\n ),\n \"PayoutsGoOnlineFee\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"PayoutsGoOnlineFee\",\n supported_modes=RunMode.any,\n min_avm_version=11,\n ),\n \"PayoutsPercent\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"PayoutsPercent\",\n supported_modes=RunMode.any,\n min_avm_version=11,\n ),\n \"PayoutsMinBalance\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"PayoutsMinBalance\",\n supported_modes=RunMode.any,\n min_avm_version=11,\n ),\n \"PayoutsMaxBalance\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"PayoutsMaxBalance\",\n supported_modes=RunMode.any,\n min_avm_version=11,\n ),\n },\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n global field F\n \"\"\"\n\n gt = AVMOpData(\n op_code=\">\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.bool]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A greater than B => {0 or 1}\n \"\"\"\n\n gt_bytes = AVMOpData(\n op_code=\"b>\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bigint, StackType.bigint], returns=[StackType.bool]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n 1 if A is greater than B, else 0. A and B are interpreted as big-endian unsigned integers\n \"\"\"\n\n gte = AVMOpData(\n op_code=\">=\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.bool]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A greater than or equal to B => {0 or 1}\n \"\"\"\n\n gte_bytes = AVMOpData(\n op_code=\"b>=\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bigint, StackType.bigint], returns=[StackType.bool]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n 1 if A is greater than or equal to B, else 0. A and B are interpreted as big-endian unsigned\n integers\n \"\"\"\n\n gtxn = AVMOpData(\n op_code=\"gtxn\",\n variants=DynamicVariants(\n immediate_index=1,\n variant_map={\n \"Sender\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"Sender\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Fee\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"Fee\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"FirstValid\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"FirstValid\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"FirstValidTime\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"FirstValidTime\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"LastValid\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"LastValid\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Note\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"Note\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Lease\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"Lease\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Receiver\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"Receiver\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Amount\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"Amount\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"CloseRemainderTo\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"CloseRemainderTo\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VotePK\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"VotePK\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"SelectionPK\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"SelectionPK\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VoteFirst\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"VoteFirst\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VoteLast\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"VoteLast\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VoteKeyDilution\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"VoteKeyDilution\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Type\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"Type\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"TypeEnum\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"TypeEnum\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"XferAsset\": Variant(\n signature=OpSignature(args=[], returns=[StackType.asset]),\n enum=\"XferAsset\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetAmount\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"AssetAmount\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetSender\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"AssetSender\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetReceiver\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"AssetReceiver\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetCloseTo\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"AssetCloseTo\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"GroupIndex\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"GroupIndex\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"TxID\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"TxID\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"ApplicationID\": Variant(\n signature=OpSignature(args=[], returns=[StackType.application]),\n enum=\"ApplicationID\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"OnCompletion\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"OnCompletion\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ApplicationArgs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ApplicationArgs\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"NumAppArgs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumAppArgs\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Accounts\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"Accounts\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"NumAccounts\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumAccounts\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ApprovalProgram\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ApprovalProgram\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ClearStateProgram\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ClearStateProgram\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"RekeyTo\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"RekeyTo\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAsset\": Variant(\n signature=OpSignature(args=[], returns=[StackType.asset]),\n enum=\"ConfigAsset\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetTotal\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"ConfigAssetTotal\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetDecimals\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"ConfigAssetDecimals\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetDefaultFrozen\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bool]),\n enum=\"ConfigAssetDefaultFrozen\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetUnitName\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ConfigAssetUnitName\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetName\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ConfigAssetName\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetURL\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ConfigAssetURL\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetMetadataHash\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ConfigAssetMetadataHash\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetManager\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"ConfigAssetManager\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetReserve\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"ConfigAssetReserve\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetFreeze\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"ConfigAssetFreeze\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetClawback\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"ConfigAssetClawback\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"FreezeAsset\": Variant(\n signature=OpSignature(args=[], returns=[StackType.asset]),\n enum=\"FreezeAsset\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"FreezeAssetAccount\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"FreezeAssetAccount\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"FreezeAssetFrozen\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bool]),\n enum=\"FreezeAssetFrozen\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Assets\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"Assets\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"NumAssets\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumAssets\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Applications\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"Applications\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"NumApplications\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumApplications\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"GlobalNumUint\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"GlobalNumUint\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"GlobalNumByteSlice\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"GlobalNumByteSlice\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"LocalNumUint\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"LocalNumUint\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"LocalNumByteSlice\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"LocalNumByteSlice\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"ExtraProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"ExtraProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n \"Nonparticipation\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bool]),\n enum=\"Nonparticipation\",\n supported_modes=RunMode.any,\n min_avm_version=5,\n ),\n \"Logs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"Logs\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"NumLogs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumLogs\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"CreatedAssetID\": Variant(\n signature=OpSignature(args=[], returns=[StackType.asset]),\n enum=\"CreatedAssetID\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"CreatedApplicationID\": Variant(\n signature=OpSignature(args=[], returns=[StackType.application]),\n enum=\"CreatedApplicationID\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"LastLog\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"LastLog\",\n supported_modes=RunMode.app,\n min_avm_version=6,\n ),\n \"StateProofPK\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"StateProofPK\",\n supported_modes=RunMode.any,\n min_avm_version=6,\n ),\n \"ApprovalProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ApprovalProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"NumApprovalProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumApprovalProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"ClearStateProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ClearStateProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"NumClearStateProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumClearStateProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n },\n ),\n immediate_types=(ImmediateKind.uint8, ImmediateKind.arg_enum),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n field F of the Tth transaction in the current group\n\n for notes on transaction fields available, see `txn`. If this transaction is _i_ in the group,\n `gtxn i field` is equivalent to `txn field`.\n \"\"\"\n\n gtxna = AVMOpData(\n op_code=\"gtxna\",\n variants=DynamicVariants(\n immediate_index=1,\n variant_map={\n \"ApplicationArgs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ApplicationArgs\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Accounts\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"Accounts\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Assets\": Variant(\n signature=OpSignature(args=[], returns=[StackType.asset]),\n enum=\"Assets\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Applications\": Variant(\n signature=OpSignature(args=[], returns=[StackType.application]),\n enum=\"Applications\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Logs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"Logs\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"ApprovalProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ApprovalProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"ClearStateProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ClearStateProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n },\n ),\n immediate_types=(ImmediateKind.uint8, ImmediateKind.arg_enum, ImmediateKind.uint8),\n cost=1,\n min_avm_version=2,\n supported_modes=RunMode.any,\n )\n \"\"\"\n Ith value of the array field F from the Tth transaction in the current group\n\n `gtxna` can be called using `gtxn` with 3 immediates.\n \"\"\"\n\n gtxnas = AVMOpData(\n op_code=\"gtxnas\",\n variants=DynamicVariants(\n immediate_index=1,\n variant_map={\n \"ApplicationArgs\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ApplicationArgs\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Accounts\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.address]),\n enum=\"Accounts\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Assets\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.asset]),\n enum=\"Assets\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Applications\": Variant(\n signature=OpSignature(\n args=[StackType.uint64], returns=[StackType.application]\n ),\n enum=\"Applications\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Logs\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"Logs\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"ApprovalProgramPages\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ApprovalProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"ClearStateProgramPages\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ClearStateProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n },\n ),\n immediate_types=(ImmediateKind.uint8, ImmediateKind.arg_enum),\n cost=1,\n min_avm_version=5,\n supported_modes=RunMode.any,\n )\n \"\"\"\n Ath value of the array field F from the Tth transaction in the current group\n \"\"\"\n\n gtxns = AVMOpData(\n op_code=\"gtxns\",\n variants=DynamicVariants(\n immediate_index=0,\n variant_map={\n \"Sender\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.address]),\n enum=\"Sender\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Fee\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"Fee\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"FirstValid\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"FirstValid\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"FirstValidTime\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"FirstValidTime\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"LastValid\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"LastValid\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Note\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"Note\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Lease\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"Lease\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Receiver\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.address]),\n enum=\"Receiver\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Amount\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"Amount\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"CloseRemainderTo\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.address]),\n enum=\"CloseRemainderTo\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VotePK\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"VotePK\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"SelectionPK\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"SelectionPK\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VoteFirst\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"VoteFirst\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VoteLast\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"VoteLast\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VoteKeyDilution\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"VoteKeyDilution\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Type\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"Type\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"TypeEnum\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"TypeEnum\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"XferAsset\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.asset]),\n enum=\"XferAsset\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetAmount\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"AssetAmount\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetSender\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.address]),\n enum=\"AssetSender\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetReceiver\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.address]),\n enum=\"AssetReceiver\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetCloseTo\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.address]),\n enum=\"AssetCloseTo\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"GroupIndex\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"GroupIndex\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"TxID\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"TxID\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"ApplicationID\": Variant(\n signature=OpSignature(\n args=[StackType.uint64], returns=[StackType.application]\n ),\n enum=\"ApplicationID\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"OnCompletion\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"OnCompletion\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ApplicationArgs\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ApplicationArgs\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"NumAppArgs\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"NumAppArgs\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Accounts\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.address]),\n enum=\"Accounts\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"NumAccounts\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"NumAccounts\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ApprovalProgram\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ApprovalProgram\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ClearStateProgram\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ClearStateProgram\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"RekeyTo\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.address]),\n enum=\"RekeyTo\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAsset\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.asset]),\n enum=\"ConfigAsset\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetTotal\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"ConfigAssetTotal\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetDecimals\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"ConfigAssetDecimals\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetDefaultFrozen\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bool]),\n enum=\"ConfigAssetDefaultFrozen\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetUnitName\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ConfigAssetUnitName\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetName\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ConfigAssetName\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetURL\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ConfigAssetURL\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetMetadataHash\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ConfigAssetMetadataHash\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetManager\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.address]),\n enum=\"ConfigAssetManager\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetReserve\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.address]),\n enum=\"ConfigAssetReserve\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetFreeze\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.address]),\n enum=\"ConfigAssetFreeze\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetClawback\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.address]),\n enum=\"ConfigAssetClawback\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"FreezeAsset\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.asset]),\n enum=\"FreezeAsset\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"FreezeAssetAccount\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.address]),\n enum=\"FreezeAssetAccount\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"FreezeAssetFrozen\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bool]),\n enum=\"FreezeAssetFrozen\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Assets\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"Assets\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"NumAssets\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"NumAssets\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Applications\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"Applications\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"NumApplications\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"NumApplications\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"GlobalNumUint\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"GlobalNumUint\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"GlobalNumByteSlice\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"GlobalNumByteSlice\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"LocalNumUint\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"LocalNumUint\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"LocalNumByteSlice\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"LocalNumByteSlice\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"ExtraProgramPages\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"ExtraProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n \"Nonparticipation\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bool]),\n enum=\"Nonparticipation\",\n supported_modes=RunMode.any,\n min_avm_version=5,\n ),\n \"Logs\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"Logs\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"NumLogs\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"NumLogs\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"CreatedAssetID\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.asset]),\n enum=\"CreatedAssetID\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"CreatedApplicationID\": Variant(\n signature=OpSignature(\n args=[StackType.uint64], returns=[StackType.application]\n ),\n enum=\"CreatedApplicationID\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"LastLog\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"LastLog\",\n supported_modes=RunMode.app,\n min_avm_version=6,\n ),\n \"StateProofPK\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"StateProofPK\",\n supported_modes=RunMode.any,\n min_avm_version=6,\n ),\n \"ApprovalProgramPages\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ApprovalProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"NumApprovalProgramPages\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"NumApprovalProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"ClearStateProgramPages\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ClearStateProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"NumClearStateProgramPages\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=\"NumClearStateProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n },\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=1,\n min_avm_version=3,\n supported_modes=RunMode.any,\n )\n \"\"\"\n field F of the Ath transaction in the current group\n\n for notes on transaction fields available, see `txn`. If top of stack is _i_, `gtxns field` is\n equivalent to `gtxn _i_ field`. gtxns exists so that _i_ can be calculated, often based on the\n index of the current transaction.\n \"\"\"\n\n gtxnsa = AVMOpData(\n op_code=\"gtxnsa\",\n variants=DynamicVariants(\n immediate_index=0,\n variant_map={\n \"ApplicationArgs\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ApplicationArgs\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Accounts\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.address]),\n enum=\"Accounts\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Assets\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.asset]),\n enum=\"Assets\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Applications\": Variant(\n signature=OpSignature(\n args=[StackType.uint64], returns=[StackType.application]\n ),\n enum=\"Applications\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Logs\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"Logs\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"ApprovalProgramPages\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ApprovalProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"ClearStateProgramPages\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ClearStateProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n },\n ),\n immediate_types=(ImmediateKind.arg_enum, ImmediateKind.uint8),\n cost=1,\n min_avm_version=3,\n supported_modes=RunMode.any,\n )\n \"\"\"\n Ith value of the array field F from the Ath transaction in the current group\n\n `gtxnsa` can be called using `gtxns` with 2 immediates.\n \"\"\"\n\n gtxnsas = AVMOpData(\n op_code=\"gtxnsas\",\n variants=DynamicVariants(\n immediate_index=0,\n variant_map={\n \"ApplicationArgs\": Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.bytes]\n ),\n enum=\"ApplicationArgs\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Accounts\": Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.address]\n ),\n enum=\"Accounts\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Assets\": Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.asset]\n ),\n enum=\"Assets\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Applications\": Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.application]\n ),\n enum=\"Applications\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Logs\": Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.bytes]\n ),\n enum=\"Logs\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"ApprovalProgramPages\": Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.bytes]\n ),\n enum=\"ApprovalProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"ClearStateProgramPages\": Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.bytes]\n ),\n enum=\"ClearStateProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n },\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=1,\n min_avm_version=5,\n supported_modes=RunMode.any,\n )\n \"\"\"\n Bth value of the array field F from the Ath transaction in the current group\n \"\"\"\n\n itob = AVMOpData(\n op_code=\"itob\",\n variants=Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n converts uint64 A to big-endian byte array, always of length 8\n \"\"\"\n\n itxn = AVMOpData(\n op_code=\"itxn\",\n variants=DynamicVariants(\n immediate_index=0,\n variant_map={\n \"Sender\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"Sender\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Fee\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"Fee\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"FirstValid\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"FirstValid\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"FirstValidTime\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"FirstValidTime\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"LastValid\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"LastValid\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Note\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"Note\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Lease\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"Lease\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Receiver\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"Receiver\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Amount\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"Amount\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"CloseRemainderTo\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"CloseRemainderTo\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VotePK\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"VotePK\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"SelectionPK\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"SelectionPK\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VoteFirst\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"VoteFirst\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VoteLast\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"VoteLast\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VoteKeyDilution\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"VoteKeyDilution\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Type\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"Type\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"TypeEnum\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"TypeEnum\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"XferAsset\": Variant(\n signature=OpSignature(args=[], returns=[StackType.asset]),\n enum=\"XferAsset\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetAmount\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"AssetAmount\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetSender\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"AssetSender\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetReceiver\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"AssetReceiver\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetCloseTo\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"AssetCloseTo\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"GroupIndex\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"GroupIndex\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"TxID\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"TxID\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"ApplicationID\": Variant(\n signature=OpSignature(args=[], returns=[StackType.application]),\n enum=\"ApplicationID\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"OnCompletion\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"OnCompletion\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ApplicationArgs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ApplicationArgs\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"NumAppArgs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumAppArgs\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Accounts\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"Accounts\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"NumAccounts\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumAccounts\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ApprovalProgram\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ApprovalProgram\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ClearStateProgram\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ClearStateProgram\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"RekeyTo\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"RekeyTo\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAsset\": Variant(\n signature=OpSignature(args=[], returns=[StackType.asset]),\n enum=\"ConfigAsset\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetTotal\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"ConfigAssetTotal\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetDecimals\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"ConfigAssetDecimals\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetDefaultFrozen\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bool]),\n enum=\"ConfigAssetDefaultFrozen\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetUnitName\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ConfigAssetUnitName\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetName\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ConfigAssetName\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetURL\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ConfigAssetURL\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetMetadataHash\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ConfigAssetMetadataHash\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetManager\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"ConfigAssetManager\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetReserve\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"ConfigAssetReserve\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetFreeze\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"ConfigAssetFreeze\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetClawback\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"ConfigAssetClawback\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"FreezeAsset\": Variant(\n signature=OpSignature(args=[], returns=[StackType.asset]),\n enum=\"FreezeAsset\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"FreezeAssetAccount\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"FreezeAssetAccount\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"FreezeAssetFrozen\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bool]),\n enum=\"FreezeAssetFrozen\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Assets\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"Assets\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"NumAssets\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumAssets\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Applications\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"Applications\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"NumApplications\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumApplications\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"GlobalNumUint\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"GlobalNumUint\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"GlobalNumByteSlice\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"GlobalNumByteSlice\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"LocalNumUint\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"LocalNumUint\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"LocalNumByteSlice\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"LocalNumByteSlice\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"ExtraProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"ExtraProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n \"Nonparticipation\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bool]),\n enum=\"Nonparticipation\",\n supported_modes=RunMode.any,\n min_avm_version=5,\n ),\n \"Logs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"Logs\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"NumLogs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumLogs\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"CreatedAssetID\": Variant(\n signature=OpSignature(args=[], returns=[StackType.asset]),\n enum=\"CreatedAssetID\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"CreatedApplicationID\": Variant(\n signature=OpSignature(args=[], returns=[StackType.application]),\n enum=\"CreatedApplicationID\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"LastLog\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"LastLog\",\n supported_modes=RunMode.app,\n min_avm_version=6,\n ),\n \"StateProofPK\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"StateProofPK\",\n supported_modes=RunMode.any,\n min_avm_version=6,\n ),\n \"ApprovalProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ApprovalProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"NumApprovalProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumApprovalProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"ClearStateProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ClearStateProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"NumClearStateProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumClearStateProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n },\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=1,\n min_avm_version=5,\n supported_modes=RunMode.app,\n )\n \"\"\"\n field F of the last inner transaction\n \"\"\"\n\n itxn_begin = AVMOpData(\n op_code=\"itxn_begin\",\n variants=Variant(\n signature=OpSignature(args=[], returns=[]),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=5,\n supported_modes=RunMode.app,\n )\n \"\"\"\n begin preparation of a new inner transaction in a new transaction group\n\n `itxn_begin` initializes Sender to the application address; Fee to the minimum allowable,\n taking into account MinTxnFee and credit from overpaying in earlier transactions;\n FirstValid\/LastValid to the values in the invoking transaction, and all other fields to zero or\n empty values.\n \"\"\"\n\n itxn_field = AVMOpData(\n op_code=\"itxn_field\",\n variants=DynamicVariants(\n immediate_index=0,\n variant_map={\n \"Sender\": Variant(\n signature=OpSignature(args=[StackType.address], returns=[]),\n enum=\"Sender\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Fee\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[]),\n enum=\"Fee\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Note\": Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[]),\n enum=\"Note\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Receiver\": Variant(\n signature=OpSignature(args=[StackType.address], returns=[]),\n enum=\"Receiver\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Amount\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[]),\n enum=\"Amount\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"CloseRemainderTo\": Variant(\n signature=OpSignature(args=[StackType.address], returns=[]),\n enum=\"CloseRemainderTo\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VotePK\": Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[]),\n enum=\"VotePK\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"SelectionPK\": Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[]),\n enum=\"SelectionPK\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VoteFirst\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[]),\n enum=\"VoteFirst\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VoteLast\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[]),\n enum=\"VoteLast\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VoteKeyDilution\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[]),\n enum=\"VoteKeyDilution\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Type\": Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[]),\n enum=\"Type\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"TypeEnum\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[]),\n enum=\"TypeEnum\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"XferAsset\": Variant(\n signature=OpSignature(args=[StackType.asset], returns=[]),\n enum=\"XferAsset\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetAmount\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[]),\n enum=\"AssetAmount\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetSender\": Variant(\n signature=OpSignature(args=[StackType.address], returns=[]),\n enum=\"AssetSender\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetReceiver\": Variant(\n signature=OpSignature(args=[StackType.address], returns=[]),\n enum=\"AssetReceiver\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetCloseTo\": Variant(\n signature=OpSignature(args=[StackType.address], returns=[]),\n enum=\"AssetCloseTo\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"ApplicationID\": Variant(\n signature=OpSignature(args=[StackType.application], returns=[]),\n enum=\"ApplicationID\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"OnCompletion\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[]),\n enum=\"OnCompletion\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ApplicationArgs\": Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[]),\n enum=\"ApplicationArgs\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Accounts\": Variant(\n signature=OpSignature(args=[StackType.address], returns=[]),\n enum=\"Accounts\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ApprovalProgram\": Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[]),\n enum=\"ApprovalProgram\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ClearStateProgram\": Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[]),\n enum=\"ClearStateProgram\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"RekeyTo\": Variant(\n signature=OpSignature(args=[StackType.address], returns=[]),\n enum=\"RekeyTo\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAsset\": Variant(\n signature=OpSignature(args=[StackType.asset], returns=[]),\n enum=\"ConfigAsset\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetTotal\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[]),\n enum=\"ConfigAssetTotal\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetDecimals\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[]),\n enum=\"ConfigAssetDecimals\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetDefaultFrozen\": Variant(\n signature=OpSignature(args=[StackType.bool], returns=[]),\n enum=\"ConfigAssetDefaultFrozen\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetUnitName\": Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[]),\n enum=\"ConfigAssetUnitName\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetName\": Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[]),\n enum=\"ConfigAssetName\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetURL\": Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[]),\n enum=\"ConfigAssetURL\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetMetadataHash\": Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[]),\n enum=\"ConfigAssetMetadataHash\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetManager\": Variant(\n signature=OpSignature(args=[StackType.address], returns=[]),\n enum=\"ConfigAssetManager\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetReserve\": Variant(\n signature=OpSignature(args=[StackType.address], returns=[]),\n enum=\"ConfigAssetReserve\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetFreeze\": Variant(\n signature=OpSignature(args=[StackType.address], returns=[]),\n enum=\"ConfigAssetFreeze\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetClawback\": Variant(\n signature=OpSignature(args=[StackType.address], returns=[]),\n enum=\"ConfigAssetClawback\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"FreezeAsset\": Variant(\n signature=OpSignature(args=[StackType.asset], returns=[]),\n enum=\"FreezeAsset\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"FreezeAssetAccount\": Variant(\n signature=OpSignature(args=[StackType.address], returns=[]),\n enum=\"FreezeAssetAccount\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"FreezeAssetFrozen\": Variant(\n signature=OpSignature(args=[StackType.bool], returns=[]),\n enum=\"FreezeAssetFrozen\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Assets\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[]),\n enum=\"Assets\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Applications\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[]),\n enum=\"Applications\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"GlobalNumUint\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[]),\n enum=\"GlobalNumUint\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"GlobalNumByteSlice\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[]),\n enum=\"GlobalNumByteSlice\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"LocalNumUint\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[]),\n enum=\"LocalNumUint\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"LocalNumByteSlice\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[]),\n enum=\"LocalNumByteSlice\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"ExtraProgramPages\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[]),\n enum=\"ExtraProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n \"Nonparticipation\": Variant(\n signature=OpSignature(args=[StackType.bool], returns=[]),\n enum=\"Nonparticipation\",\n supported_modes=RunMode.any,\n min_avm_version=5,\n ),\n \"StateProofPK\": Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[]),\n enum=\"StateProofPK\",\n supported_modes=RunMode.any,\n min_avm_version=6,\n ),\n \"ApprovalProgramPages\": Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[]),\n enum=\"ApprovalProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"ClearStateProgramPages\": Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[]),\n enum=\"ClearStateProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n },\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=1,\n min_avm_version=5,\n supported_modes=RunMode.app,\n )\n \"\"\"\n set field F of the current inner transaction to A\n\n `itxn_field` fails if A is of the wrong type for F, including a byte array of the wrong size\n for use as an address when F is an address field. `itxn_field` also fails if A is an account,\n asset, or app that is not _available_, or an attempt is made extend an array field beyond the\n limit imposed by consensus parameters. (Addresses set into asset params of acfg transactions\n need not be _available_.)\n \"\"\"\n\n itxn_next = AVMOpData(\n op_code=\"itxn_next\",\n variants=Variant(\n signature=OpSignature(args=[], returns=[]),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=6,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=6,\n supported_modes=RunMode.app,\n )\n \"\"\"\n begin preparation of a new inner transaction in the same transaction group\n\n `itxn_next` initializes the transaction exactly as `itxn_begin` does\n \"\"\"\n\n itxn_submit = AVMOpData(\n op_code=\"itxn_submit\",\n variants=Variant(\n signature=OpSignature(args=[], returns=[]),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=5,\n supported_modes=RunMode.app,\n )\n \"\"\"\n execute the current inner transaction group. Fail if executing this group would exceed the\n inner transaction limit, or if any transaction in the group fails.\n\n `itxn_submit` resets the current transaction so that it can not be resubmitted. A new\n `itxn_begin` is required to prepare another inner transaction.\n \"\"\"\n\n itxna = AVMOpData(\n op_code=\"itxna\",\n variants=DynamicVariants(\n immediate_index=0,\n variant_map={\n \"ApplicationArgs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ApplicationArgs\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Accounts\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"Accounts\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Assets\": Variant(\n signature=OpSignature(args=[], returns=[StackType.asset]),\n enum=\"Assets\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Applications\": Variant(\n signature=OpSignature(args=[], returns=[StackType.application]),\n enum=\"Applications\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Logs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"Logs\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"ApprovalProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ApprovalProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"ClearStateProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ClearStateProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n },\n ),\n immediate_types=(ImmediateKind.arg_enum, ImmediateKind.uint8),\n cost=1,\n min_avm_version=5,\n supported_modes=RunMode.app,\n )\n \"\"\"\n Ith value of the array field F of the last inner transaction\n \"\"\"\n\n itxnas = AVMOpData(\n op_code=\"itxnas\",\n variants=DynamicVariants(\n immediate_index=0,\n variant_map={\n \"ApplicationArgs\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ApplicationArgs\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Accounts\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.address]),\n enum=\"Accounts\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Assets\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.asset]),\n enum=\"Assets\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Applications\": Variant(\n signature=OpSignature(\n args=[StackType.uint64], returns=[StackType.application]\n ),\n enum=\"Applications\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Logs\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"Logs\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"ApprovalProgramPages\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ApprovalProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"ClearStateProgramPages\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ClearStateProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n },\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=1,\n min_avm_version=6,\n supported_modes=RunMode.app,\n )\n \"\"\"\n Ath value of the array field F of the last inner transaction\n \"\"\"\n\n json_ref = AVMOpData(\n op_code=\"json_ref\",\n variants=DynamicVariants(\n immediate_index=0,\n variant_map={\n \"JSONString\": Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.bytes], returns=[StackType.bytes]\n ),\n enum=\"JSONString\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"JSONUint64\": Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.bytes], returns=[StackType.uint64]\n ),\n enum=\"JSONUint64\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"JSONObject\": Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.bytes], returns=[StackType.bytes]\n ),\n enum=\"JSONObject\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n },\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=None,\n min_avm_version=7,\n supported_modes=RunMode.any,\n )\n \"\"\"\n key B's value, of type R, from a [valid](jsonspec.md) utf-8 encoded json object A\n\n *Warning*: Usage should be restricted to very rare use cases, as JSON decoding is expensive and\n quite limited. In addition, JSON objects are large and not optimized for size.\n\n\n Almost all smart contracts should use simpler and smaller methods (such as the\n [ABI](https:\/\/arc.algorand.foundation\/ARCs\/arc-0004). This opcode should only be used in cases\n where JSON is only available option, e.g. when a third-party only signs JSON.\n \"\"\"\n\n keccak256 = AVMOpData(\n op_code=\"keccak256\",\n variants=Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[StackType.bytes]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=130,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n Keccak256 hash of value A, yields [32]byte\n \"\"\"\n\n len_ = AVMOpData(\n op_code=\"len\",\n variants=Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[StackType.uint64]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n yields length of byte value A\n \"\"\"\n\n load = AVMOpData(\n op_code=\"load\",\n variants=Variant(\n signature=OpSignature(args=[], returns=[StackType.any]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(ImmediateKind.uint8,),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n Ith scratch space value. All scratch spaces are 0 at program start.\n \"\"\"\n\n loads = AVMOpData(\n op_code=\"loads\",\n variants=Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.any]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=5,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=5,\n supported_modes=RunMode.any,\n )\n \"\"\"\n Ath scratch space value. All scratch spaces are 0 at program start.\n \"\"\"\n\n log = AVMOpData(\n op_code=\"log\",\n variants=Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[]),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=5,\n supported_modes=RunMode.app,\n )\n \"\"\"\n write A to log state of the current application\n\n `log` fails if called more than MaxLogCalls times in a program, or if the sum of logged bytes\n exceeds 1024 bytes.\n \"\"\"\n\n lt = AVMOpData(\n op_code=\"<\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.bool]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A less than B => {0 or 1}\n \"\"\"\n\n lt_bytes = AVMOpData(\n op_code=\"b<\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bigint, StackType.bigint], returns=[StackType.bool]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n 1 if A is less than B, else 0. A and B are interpreted as big-endian unsigned integers\n \"\"\"\n\n lte = AVMOpData(\n op_code=\"<=\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.bool]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A less than or equal to B => {0 or 1}\n \"\"\"\n\n lte_bytes = AVMOpData(\n op_code=\"b<=\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bigint, StackType.bigint], returns=[StackType.bool]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n 1 if A is less than or equal to B, else 0. A and B are interpreted as big-endian unsigned\n integers\n \"\"\"\n\n mimc = AVMOpData(\n op_code=\"mimc\",\n variants=Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[StackType.bytes]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=11,\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=None,\n min_avm_version=11,\n supported_modes=RunMode.any,\n )\n \"\"\"\n MiMC hash of scalars A, using curve and parameters specified by configuration C\n\n A is a list of concatenated 32 byte big-endian unsigned integer scalars. Fail if A's length is\n not a multiple of 32 or any element exceeds the curve modulus.\n\n\n The MiMC hash function has known collisions since any input which is a multiple of the elliptic\n curve modulus will hash to the same value. MiMC is thus not a general purpose hash function,\n but meant to be used in zero knowledge applications to match a zk-circuit implementation.\n \"\"\"\n\n min_balance = AVMOpData(\n op_code=\"min_balance\",\n variants=Variant(\n signature=OpSignature(args=[StackType.address_or_index], returns=[StackType.uint64]),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=3,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=3,\n supported_modes=RunMode.app,\n )\n \"\"\"\n minimum required balance for account A, in microalgos. Required balance is affected by ASA,\n App, and Box usage. When creating or opting into an app, the minimum balance grows before the\n app code runs, therefore the increase is visible there. When deleting or closing out, the\n minimum balance decreases after the app executes. Changes caused by inner transactions or box\n usage are observable immediately following the opcode effecting the change.\n\n params: Txn.Accounts offset (or, since v4, an _available_ account address), _available_\n application id (or, since v4, a Txn.ForeignApps offset). Return: value.\n \"\"\"\n\n mod = AVMOpData(\n op_code=\"%\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.uint64]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A modulo B. Fail if B == 0.\n \"\"\"\n\n mod_bytes = AVMOpData(\n op_code=\"b%\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bigint, StackType.bigint], returns=[StackType.bigint]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=20,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A modulo B. A and B are interpreted as big-endian unsigned integers. Fail if B is zero.\n \"\"\"\n\n mul = AVMOpData(\n op_code=\"*\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.uint64]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A times B. Fail on overflow.\n\n Overflow is an error condition which halts execution and fails the transaction. Full precision\n is available from `mulw`.\n \"\"\"\n\n mul_bytes = AVMOpData(\n op_code=\"b*\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bigint, StackType.bigint], returns=[StackType.bigint]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=20,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A times B. A and B are interpreted as big-endian unsigned integers.\n \"\"\"\n\n mulw = AVMOpData(\n op_code=\"mulw\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64],\n returns=[StackType.uint64, StackType.uint64],\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A times B as a 128-bit result in two uint64s. X is the high 64 bits, Y is the low\n \"\"\"\n\n neq = AVMOpData(\n op_code=\"!=\",\n variants=Variant(\n signature=OpSignature(args=[StackType.any, StackType.any], returns=[StackType.bool]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A is not equal to B => {0 or 1}\n \"\"\"\n\n neq_bytes = AVMOpData(\n op_code=\"b!=\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bigint, StackType.bigint], returns=[StackType.bool]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n 0 if A is equal to B, else 1. A and B are interpreted as big-endian unsigned integers\n \"\"\"\n\n not_ = AVMOpData(\n op_code=\"!\",\n variants=Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bool]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A == 0 yields 1; else 0\n \"\"\"\n\n online_stake = AVMOpData(\n op_code=\"online_stake\",\n variants=Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=None,\n supported_modes=RunMode.app,\n min_avm_version=11,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=11,\n supported_modes=RunMode.app,\n )\n \"\"\"\n the total online stake in the agreement round\n \"\"\"\n\n or_ = AVMOpData(\n op_code=\"||\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.bool]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A is not zero or B is not zero => {0 or 1}\n \"\"\"\n\n replace2 = AVMOpData(\n op_code=\"replace2\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.bytes], returns=[StackType.bytes]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n immediate_types=(ImmediateKind.uint8,),\n cost=1,\n min_avm_version=7,\n supported_modes=RunMode.any,\n )\n \"\"\"\n Copy of A with the bytes starting at S replaced by the bytes of B. Fails if S+len(B) exceeds\n len(A)\n\n `replace2` can be called using `replace` with 1 immediate.\n \"\"\"\n\n replace3 = AVMOpData(\n op_code=\"replace3\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.uint64, StackType.bytes],\n returns=[StackType.bytes],\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=7,\n supported_modes=RunMode.any,\n )\n \"\"\"\n Copy of A with the bytes starting at B replaced by the bytes of C. Fails if B+len(C) exceeds\n len(A)\n\n `replace3` can be called using `replace` with no immediates.\n \"\"\"\n\n select = AVMOpData(\n op_code=\"select\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.any, StackType.any, StackType.bool], returns=[StackType.any]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=3,\n supported_modes=RunMode.any,\n )\n \"\"\"\n selects one of two values based on top-of-stack: B if C != 0, else A\n \"\"\"\n\n setbit = AVMOpData(\n op_code=\"setbit\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.any, StackType.uint64, StackType.uint64], returns=[StackType.any]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=3,\n supported_modes=RunMode.any,\n )\n \"\"\"\n Copy of (byte-array or integer) A, with the Bth bit set to (0 or 1) C. If B is greater than or\n equal to the bit length of the value (8*byte length), the program fails\n\n When A is a uint64, index 0 is the least significant bit. Setting bit 3 to 1 on the integer 0\n yields 8, or 2^3. When A is a byte array, index 0 is the leftmost bit of the leftmost byte.\n Setting bits 0 through 11 to 1 in a 4-byte-array of 0s yields the byte array 0xfff00000.\n Setting bit 3 to 1 on the 1-byte-array 0x00 yields the byte array 0x10.\n \"\"\"\n\n setbyte = AVMOpData(\n op_code=\"setbyte\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.uint64, StackType.uint64],\n returns=[StackType.bytes],\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=3,\n supported_modes=RunMode.any,\n )\n \"\"\"\n Copy of A with the Bth byte set to small integer (between 0..255) C. If B is greater than or\n equal to the array length, the program fails\n \"\"\"\n\n sha256 = AVMOpData(\n op_code=\"sha256\",\n variants=Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[StackType.bytes]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=35,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n SHA256 hash of value A, yields [32]byte\n \"\"\"\n\n sha3_256 = AVMOpData(\n op_code=\"sha3_256\",\n variants=Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[StackType.bytes]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n immediate_types=(),\n cost=130,\n min_avm_version=7,\n supported_modes=RunMode.any,\n )\n \"\"\"\n SHA3_256 hash of value A, yields [32]byte\n \"\"\"\n\n sha512_256 = AVMOpData(\n op_code=\"sha512_256\",\n variants=Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[StackType.bytes]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=45,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n SHA512_256 hash of value A, yields [32]byte\n \"\"\"\n\n shl = AVMOpData(\n op_code=\"shl\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.uint64]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A times 2^B, modulo 2^64\n \"\"\"\n\n shr = AVMOpData(\n op_code=\"shr\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.uint64]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A divided by 2^B\n \"\"\"\n\n sqrt = AVMOpData(\n op_code=\"sqrt\",\n variants=Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.uint64]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=4,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n The largest integer I such that I^2 <= A\n \"\"\"\n\n store = AVMOpData(\n op_code=\"store\",\n variants=Variant(\n signature=OpSignature(args=[StackType.any], returns=[]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(ImmediateKind.uint8,),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n store A to the Ith scratch space\n \"\"\"\n\n stores = AVMOpData(\n op_code=\"stores\",\n variants=Variant(\n signature=OpSignature(args=[StackType.uint64, StackType.any], returns=[]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=5,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=5,\n supported_modes=RunMode.any,\n )\n \"\"\"\n store B to the Ath scratch space\n \"\"\"\n\n sub = AVMOpData(\n op_code=\"-\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.uint64, StackType.uint64], returns=[StackType.uint64]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=1,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A minus B. Fail if B > A.\n \"\"\"\n\n sub_bytes = AVMOpData(\n op_code=\"b-\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bigint, StackType.bigint], returns=[StackType.bigint]\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n immediate_types=(),\n cost=10,\n min_avm_version=4,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A minus B. A and B are interpreted as big-endian unsigned integers. Fail on underflow.\n \"\"\"\n\n substring = AVMOpData(\n op_code=\"substring\",\n variants=Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[StackType.bytes]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n immediate_types=(ImmediateKind.uint8, ImmediateKind.uint8),\n cost=1,\n min_avm_version=2,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A range of bytes from A starting at S up to but not including E. If E < S, or either is larger\n than the array length, the program fails\n \"\"\"\n\n substring3 = AVMOpData(\n op_code=\"substring3\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.uint64, StackType.uint64],\n returns=[StackType.bytes],\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n immediate_types=(),\n cost=1,\n min_avm_version=2,\n supported_modes=RunMode.any,\n )\n \"\"\"\n A range of bytes from A starting at B up to but not including C. If C < B, or either is larger\n than the array length, the program fails\n \"\"\"\n\n sumhash512 = AVMOpData(\n op_code=\"sumhash512\",\n variants=Variant(\n signature=OpSignature(args=[StackType.bytes], returns=[StackType.bytes]),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=12,\n ),\n immediate_types=(),\n cost=None,\n min_avm_version=12,\n supported_modes=RunMode.any,\n )\n \"\"\"\n sumhash512 of value A, yields [64]byte\n \"\"\"\n\n txn = AVMOpData(\n op_code=\"txn\",\n variants=DynamicVariants(\n immediate_index=0,\n variant_map={\n \"Sender\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"Sender\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Fee\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"Fee\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"FirstValid\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"FirstValid\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"FirstValidTime\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"FirstValidTime\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"LastValid\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"LastValid\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Note\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"Note\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Lease\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"Lease\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Receiver\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"Receiver\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Amount\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"Amount\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"CloseRemainderTo\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"CloseRemainderTo\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VotePK\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"VotePK\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"SelectionPK\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"SelectionPK\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VoteFirst\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"VoteFirst\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VoteLast\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"VoteLast\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"VoteKeyDilution\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"VoteKeyDilution\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"Type\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"Type\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"TypeEnum\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"TypeEnum\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"XferAsset\": Variant(\n signature=OpSignature(args=[], returns=[StackType.asset]),\n enum=\"XferAsset\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetAmount\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"AssetAmount\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetSender\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"AssetSender\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetReceiver\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"AssetReceiver\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"AssetCloseTo\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"AssetCloseTo\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"GroupIndex\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"GroupIndex\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"TxID\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"TxID\",\n supported_modes=RunMode.any,\n min_avm_version=0,\n ),\n \"ApplicationID\": Variant(\n signature=OpSignature(args=[], returns=[StackType.application]),\n enum=\"ApplicationID\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"OnCompletion\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"OnCompletion\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ApplicationArgs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ApplicationArgs\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"NumAppArgs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumAppArgs\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Accounts\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"Accounts\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"NumAccounts\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumAccounts\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ApprovalProgram\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ApprovalProgram\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ClearStateProgram\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ClearStateProgram\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"RekeyTo\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"RekeyTo\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAsset\": Variant(\n signature=OpSignature(args=[], returns=[StackType.asset]),\n enum=\"ConfigAsset\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetTotal\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"ConfigAssetTotal\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetDecimals\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"ConfigAssetDecimals\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetDefaultFrozen\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bool]),\n enum=\"ConfigAssetDefaultFrozen\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetUnitName\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ConfigAssetUnitName\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetName\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ConfigAssetName\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetURL\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ConfigAssetURL\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetMetadataHash\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ConfigAssetMetadataHash\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetManager\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"ConfigAssetManager\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetReserve\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"ConfigAssetReserve\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetFreeze\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"ConfigAssetFreeze\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"ConfigAssetClawback\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"ConfigAssetClawback\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"FreezeAsset\": Variant(\n signature=OpSignature(args=[], returns=[StackType.asset]),\n enum=\"FreezeAsset\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"FreezeAssetAccount\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"FreezeAssetAccount\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"FreezeAssetFrozen\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bool]),\n enum=\"FreezeAssetFrozen\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Assets\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"Assets\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"NumAssets\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumAssets\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Applications\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"Applications\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"NumApplications\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumApplications\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"GlobalNumUint\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"GlobalNumUint\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"GlobalNumByteSlice\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"GlobalNumByteSlice\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"LocalNumUint\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"LocalNumUint\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"LocalNumByteSlice\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"LocalNumByteSlice\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"ExtraProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"ExtraProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=4,\n ),\n \"Nonparticipation\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bool]),\n enum=\"Nonparticipation\",\n supported_modes=RunMode.any,\n min_avm_version=5,\n ),\n \"Logs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"Logs\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"NumLogs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumLogs\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"CreatedAssetID\": Variant(\n signature=OpSignature(args=[], returns=[StackType.asset]),\n enum=\"CreatedAssetID\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"CreatedApplicationID\": Variant(\n signature=OpSignature(args=[], returns=[StackType.application]),\n enum=\"CreatedApplicationID\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"LastLog\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"LastLog\",\n supported_modes=RunMode.app,\n min_avm_version=6,\n ),\n \"StateProofPK\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"StateProofPK\",\n supported_modes=RunMode.any,\n min_avm_version=6,\n ),\n \"ApprovalProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ApprovalProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"NumApprovalProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumApprovalProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"ClearStateProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ClearStateProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"NumClearStateProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.uint64]),\n enum=\"NumClearStateProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n },\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=1,\n min_avm_version=1,\n supported_modes=RunMode.any,\n )\n \"\"\"\n field F of current transaction\n \"\"\"\n\n txna = AVMOpData(\n op_code=\"txna\",\n variants=DynamicVariants(\n immediate_index=0,\n variant_map={\n \"ApplicationArgs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ApplicationArgs\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Accounts\": Variant(\n signature=OpSignature(args=[], returns=[StackType.address]),\n enum=\"Accounts\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Assets\": Variant(\n signature=OpSignature(args=[], returns=[StackType.asset]),\n enum=\"Assets\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Applications\": Variant(\n signature=OpSignature(args=[], returns=[StackType.application]),\n enum=\"Applications\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Logs\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"Logs\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"ApprovalProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ApprovalProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"ClearStateProgramPages\": Variant(\n signature=OpSignature(args=[], returns=[StackType.bytes]),\n enum=\"ClearStateProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n },\n ),\n immediate_types=(ImmediateKind.arg_enum, ImmediateKind.uint8),\n cost=1,\n min_avm_version=2,\n supported_modes=RunMode.any,\n )\n \"\"\"\n Ith value of the array field F of the current transaction\n\n `txna` can be called using `txn` with 2 immediates.\n \"\"\"\n\n txnas = AVMOpData(\n op_code=\"txnas\",\n variants=DynamicVariants(\n immediate_index=0,\n variant_map={\n \"ApplicationArgs\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ApplicationArgs\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Accounts\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.address]),\n enum=\"Accounts\",\n supported_modes=RunMode.any,\n min_avm_version=2,\n ),\n \"Assets\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.asset]),\n enum=\"Assets\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Applications\": Variant(\n signature=OpSignature(\n args=[StackType.uint64], returns=[StackType.application]\n ),\n enum=\"Applications\",\n supported_modes=RunMode.any,\n min_avm_version=3,\n ),\n \"Logs\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"Logs\",\n supported_modes=RunMode.app,\n min_avm_version=5,\n ),\n \"ApprovalProgramPages\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ApprovalProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n \"ClearStateProgramPages\": Variant(\n signature=OpSignature(args=[StackType.uint64], returns=[StackType.bytes]),\n enum=\"ClearStateProgramPages\",\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n },\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=1,\n min_avm_version=5,\n supported_modes=RunMode.any,\n )\n \"\"\"\n Ath value of the array field F of the current transaction\n \"\"\"\n\n voter_params_get = AVMOpData(\n op_code=\"voter_params_get\",\n variants=DynamicVariants(\n immediate_index=0,\n variant_map={\n \"VoterBalance\": Variant(\n signature=OpSignature(\n args=[StackType.address_or_index],\n returns=[StackType.uint64, StackType.bool],\n ),\n enum=\"VoterBalance\",\n supported_modes=RunMode.app,\n min_avm_version=11,\n ),\n \"VoterIncentiveEligible\": Variant(\n signature=OpSignature(\n args=[StackType.address_or_index], returns=[StackType.bool, StackType.bool]\n ),\n enum=\"VoterIncentiveEligible\",\n supported_modes=RunMode.app,\n min_avm_version=11,\n ),\n },\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=1,\n min_avm_version=11,\n supported_modes=RunMode.app,\n )\n \"\"\"\n X is field F from online account A as of the balance round: 320 rounds before the current\n round. Y is 1 if A had positive algos online in the agreement round, else Y is 0 and X is a\n type specific zero-value\n \"\"\"\n\n vrf_verify = AVMOpData(\n op_code=\"vrf_verify\",\n variants=Variant(\n signature=OpSignature(\n args=[StackType.bytes, StackType.bytes, StackType.bytes],\n returns=[StackType.bytes, StackType.bool],\n ),\n enum=None,\n supported_modes=RunMode.any,\n min_avm_version=7,\n ),\n immediate_types=(ImmediateKind.arg_enum,),\n cost=5700,\n min_avm_version=7,\n supported_modes=RunMode.any,\n )\n \"\"\"\n Verify the proof B of message A against pubkey C. Returns vrf output and verification flag.\n\n `VrfAlgorand` is the VRF used in Algorand. It is ECVRF-ED25519-SHA512-Elligator2, specified in\n the IETF internet draft [draft-irtf-cfrg-vrf-03](https:\/\/datatracker.ietf.org\/doc\/draft-irtf-\n cfrg-vrf\/03\/).\n \"\"\"\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/avm_ops.py","language":"Python","license":"NOASSERTION","size":240926} {"code":"import enum\nfrom collections.abc import Sequence\n\nimport attrs\n\n\nclass StackType(enum.StrEnum):\n uint64 = enum.auto()\n bytes = \"[]byte\"\n bool = enum.auto()\n address = enum.auto()\n address_or_index = enum.auto()\n any = enum.auto()\n bigint = enum.auto()\n box_name = \"boxName\"\n asset = enum.auto()\n application = enum.auto()\n state_key = \"stateKey\"\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}.{self.name}\"\n\n\nclass RunMode(enum.StrEnum):\n app = enum.auto()\n lsig = enum.auto()\n any = enum.auto()\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}.{self.name}\"\n\n\nclass ImmediateKind(enum.StrEnum):\n uint8 = enum.auto()\n arg_enum = enum.auto()\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}.{self.name}\"\n\n\n@attrs.frozen\nclass OpSignature:\n args: Sequence[StackType]\n returns: Sequence[StackType]\n\n\n@attrs.frozen\nclass Variant:\n signature: OpSignature\n enum: str | None\n supported_modes: RunMode\n min_avm_version: int\n\n\n@attrs.frozen\nclass DynamicVariants:\n immediate_index: int\n variant_map: dict[str, Variant]\n\n\n@attrs.define(kw_only=True)\nclass AVMOpData:\n op_code: str\n variants: Variant | DynamicVariants\n immediate_types: Sequence[ImmediateKind] = attrs.field(default=())\n cost: int | None\n min_avm_version: int\n supported_modes: RunMode\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/avm_ops_models.py","language":"Python","license":"NOASSERTION","size":1398} {"code":"","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/builder\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"from collections.abc import Sequence\n\nfrom puya.awst import wtypes\nfrom puya.errors import InternalError\nfrom puya.ir.context import IRFunctionBuildContext\nfrom puya.ir.models import Register, Value, ValueProvider, ValueTuple\nfrom puya.ir.types_ import IRType, get_wtype_arity, sum_wtypes_arity, wtype_to_ir_type\nfrom puya.ir.utils import format_tuple_index\nfrom puya.parse import SourceLocation\n\n\ndef get_tuple_item_values(\n *,\n tuple_values: Sequence[Value],\n tuple_wtype: wtypes.WTuple,\n index: int | tuple[int, int | None],\n target_wtype: wtypes.WType,\n source_location: SourceLocation,\n) -> ValueProvider:\n if isinstance(index, tuple):\n skip_values = sum_wtypes_arity(tuple_wtype.types[: index[0]])\n target_arity = sum_wtypes_arity(tuple_wtype.types[index[0] : index[1]])\n else:\n skip_values = sum_wtypes_arity(tuple_wtype.types[:index])\n target_arity = get_wtype_arity(tuple_wtype.types[index])\n\n if target_arity != get_wtype_arity(target_wtype):\n raise InternalError(\n \"arity difference between result type and expected type\", source_location\n )\n\n values = tuple_values[skip_values : skip_values + target_arity]\n\n if len(values) == 1 and not isinstance(target_wtype, wtypes.WTuple):\n return values[0]\n return ValueTuple(values=values, source_location=source_location)\n\n\ndef build_tuple_registers(\n context: IRFunctionBuildContext,\n base_name: str,\n wtype: wtypes.WType,\n source_location: SourceLocation | None,\n) -> list[Register]:\n return [\n context.ssa.new_register(name, ir_type, source_location)\n for name, ir_type in build_tuple_item_names(base_name, wtype, source_location)\n ]\n\n\ndef build_tuple_item_names(\n base_name: str,\n wtype: wtypes.WType,\n source_location: SourceLocation | None,\n) -> list[tuple[str, IRType]]:\n if not isinstance(wtype, wtypes.WTuple):\n return [(base_name, wtype_to_ir_type(wtype, source_location))]\n return [\n reg\n for idx, item_type in enumerate(wtype.types)\n for reg in build_tuple_item_names(\n format_tuple_index(wtype, base_name, idx), item_type, source_location\n )\n ]\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/builder\/_tuple_util.py","language":"Python","license":"NOASSERTION","size":2203} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport attrs\n\nfrom puya.awst import (\n nodes as awst_nodes,\n wtypes,\n)\nfrom puya.errors import InternalError\nfrom puya.ir.avm_ops import AVMOp\nfrom puya.ir.context import TMP_VAR_INDICATOR, IRFunctionBuildContext\nfrom puya.ir.models import (\n Assignment,\n BytesConstant,\n Intrinsic,\n InvokeSubroutine,\n Register,\n UInt64Constant,\n Value,\n ValueProvider,\n)\nfrom puya.ir.types_ import AVMBytesEncoding, IRType\nfrom puya.parse import SourceLocation\n\n\ndef assign(\n context: IRFunctionBuildContext,\n source: ValueProvider,\n *,\n name: str,\n assignment_location: SourceLocation | None,\n register_location: SourceLocation | None = None,\n) -> Register:\n (ir_type,) = source.types\n target = context.ssa.new_register(name, ir_type, register_location or assignment_location)\n assign_targets(\n context=context,\n source=source,\n targets=[target],\n assignment_location=assignment_location,\n )\n return target\n\n\ndef new_register_version(context: IRFunctionBuildContext, reg: Register) -> Register:\n return context.ssa.new_register(\n name=reg.name, ir_type=reg.ir_type, location=reg.source_location\n )\n\n\ndef assign_temp(\n context: IRFunctionBuildContext,\n source: ValueProvider,\n *,\n temp_description: str,\n source_location: SourceLocation | None,\n) -> Register:\n (ir_type,) = source.types\n target = mktemp(context, ir_type, source_location, description=temp_description)\n assign_targets(\n context,\n source=source,\n targets=[target],\n assignment_location=source_location,\n )\n return target\n\n\ndef assign_targets(\n context: IRFunctionBuildContext,\n *,\n source: ValueProvider,\n targets: list[Register],\n assignment_location: SourceLocation | None,\n) -> None:\n if not (source.types or targets):\n return\n for target in targets:\n context.ssa.write_variable(target.name, context.block_builder.active_block, target)\n context.block_builder.add(\n Assignment(targets=targets, source=source, source_location=assignment_location)\n )\n # also update any implicitly returned variables\n implicit_params = {p.name for p in context.subroutine.parameters if p.implicit_return}\n for target in targets:\n if target.name in implicit_params:\n _update_implicit_out_var(context, target.name, target.ir_type)\n\n\ndef _update_implicit_out_var(context: IRFunctionBuildContext, var: str, ir_type: IRType) -> None:\n # emit conditional assignment equivalent to\n # if var%is_original:\n # var%out = var\n loc = SourceLocation(file=None, line=1)\n wtype = wtypes.bytes_wtype if ir_type == IRType.bytes else wtypes.uint64_wtype\n node = awst_nodes.IfElse(\n condition=awst_nodes.VarExpression(\n name=get_implicit_return_is_original(var),\n wtype=wtypes.bool_wtype,\n source_location=loc,\n ),\n if_branch=awst_nodes.Block(\n body=[\n awst_nodes.AssignmentStatement(\n target=awst_nodes.VarExpression(\n name=get_implicit_return_out(var),\n wtype=wtype,\n source_location=loc,\n ),\n value=awst_nodes.VarExpression(\n name=var,\n wtype=wtype,\n source_location=loc,\n ),\n source_location=loc,\n )\n ],\n source_location=loc,\n ),\n else_branch=None,\n source_location=loc,\n )\n node.accept(context.visitor)\n\n\ndef get_implicit_return_is_original(var_name: str) -> str:\n return f\"{var_name}{TMP_VAR_INDICATOR}is_original\"\n\n\ndef get_implicit_return_out(var_name: str) -> str:\n return f\"{var_name}{TMP_VAR_INDICATOR}out\"\n\n\ndef mktemp(\n context: IRFunctionBuildContext,\n ir_type: IRType,\n source_location: SourceLocation | None,\n *,\n description: str,\n) -> Register:\n name = context.next_tmp_name(description)\n return context.ssa.new_register(name, ir_type, source_location)\n\n\ndef assign_intrinsic_op(\n context: IRFunctionBuildContext,\n *,\n target: str | Register,\n op: AVMOp,\n args: Sequence[int | bytes | Value],\n source_location: SourceLocation | None,\n immediates: list[int | str] | None = None,\n return_type: IRType | None = None,\n) -> Register:\n intrinsic = Intrinsic(\n op=op,\n immediates=immediates or [],\n args=[_convert_constants(a, source_location) for a in args],\n types=(\n [return_type]\n if return_type is not None\n else typing.cast(Sequence[IRType], attrs.NOTHING)\n ),\n source_location=source_location,\n )\n if isinstance(target, str):\n target_reg = mktemp(context, intrinsic.types[0], source_location, description=target)\n else:\n target_reg = new_register_version(context, target)\n assign_targets(\n context,\n targets=[target_reg],\n source=intrinsic,\n assignment_location=source_location,\n )\n return target_reg\n\n\ndef _convert_constants(arg: int | bytes | Value, source_location: SourceLocation | None) -> Value:\n match arg:\n case int(val):\n return UInt64Constant(value=val, source_location=source_location)\n case bytes(b_val):\n return BytesConstant(\n value=b_val, encoding=AVMBytesEncoding.unknown, source_location=source_location\n )\n case _:\n return arg\n\n\ndef invoke_puya_lib_subroutine(\n context: IRFunctionBuildContext,\n *,\n full_name: str,\n args: Sequence[Value | int | bytes],\n source_location: SourceLocation,\n) -> InvokeSubroutine:\n sub = context.embedded_funcs_lookup[full_name]\n return InvokeSubroutine(\n target=sub,\n args=[_convert_constants(arg, source_location) for arg in args],\n source_location=source_location,\n )\n\n\ndef assert_value(\n context: IRFunctionBuildContext, value: Value, *, source_location: SourceLocation, comment: str\n) -> None:\n context.block_builder.add(\n Intrinsic(\n op=AVMOp.assert_,\n source_location=source_location,\n args=[value],\n error_message=comment,\n )\n )\n\n\ndef extract_const_int(expr: awst_nodes.Expression | int | None) -> int | None:\n \"\"\"\n Check expr is an IntegerConstant, int literal, or None, and return constant value (or None)\n \"\"\"\n match expr:\n case None:\n return None\n case awst_nodes.IntegerConstant(value=value):\n return value\n case int(value):\n return value\n case _:\n raise InternalError(\n f\"Expected either constant or None for index, got {type(expr).__name__}\",\n expr.source_location,\n )\n\n\n@attrs.frozen\nclass OpFactory:\n context: IRFunctionBuildContext\n source_location: SourceLocation | None\n\n def assign(self, value: ValueProvider, temp_desc: str) -> Register:\n register = assign_temp(\n self.context, value, temp_description=temp_desc, source_location=self.source_location\n )\n return register\n\n def assign_multiple(self, **values: ValueProvider) -> Sequence[Register]:\n return [self.assign(value, desc) for desc, value in values.items()]\n\n def add(self, a: Value, b: Value | int, temp_desc: str) -> Register:\n result = assign_intrinsic_op(\n self.context,\n target=temp_desc,\n op=AVMOp.add,\n args=[a, b],\n source_location=self.source_location,\n )\n return result\n\n def sub(self, a: Value, b: Value | int, temp_desc: str) -> Register:\n result = assign_intrinsic_op(\n self.context,\n target=temp_desc,\n op=AVMOp.sub,\n args=[a, b],\n source_location=self.source_location,\n )\n return result\n\n def mul(self, a: Value, b: Value | int, temp_desc: str) -> Register:\n result = assign_intrinsic_op(\n self.context,\n target=temp_desc,\n op=AVMOp.mul,\n args=[a, b],\n source_location=self.source_location,\n )\n return result\n\n def len(self, value: Value, temp_desc: str) -> Register:\n result = assign_intrinsic_op(\n self.context,\n target=temp_desc,\n op=AVMOp.len_,\n args=[value],\n source_location=self.source_location,\n )\n return result\n\n def eq(self, a: Value, b: Value, temp_desc: str) -> Register:\n result = assign_intrinsic_op(\n self.context,\n target=temp_desc,\n op=AVMOp.eq,\n args=[a, b],\n source_location=self.source_location,\n )\n return result\n\n def select(self, false: Value, true: Value, condition: Value, temp_desc: str) -> Register:\n result = assign_intrinsic_op(\n self.context,\n target=temp_desc,\n op=AVMOp.select,\n args=[false, true, condition],\n return_type=true.ir_type,\n source_location=self.source_location,\n )\n return result\n\n def extract_uint16(self, a: Value, b: Value | int, temp_desc: str) -> Register:\n result = assign_intrinsic_op(\n self.context,\n target=temp_desc,\n op=AVMOp.extract_uint16,\n args=[a, b],\n source_location=self.source_location,\n )\n return result\n\n def itob(self, value: Value | int, temp_desc: str) -> Register:\n itob = assign_intrinsic_op(\n self.context,\n target=temp_desc,\n op=AVMOp.itob,\n args=[value],\n source_location=self.source_location,\n )\n return itob\n\n def as_u16_bytes(self, a: Value | int, temp_desc: str) -> Register:\n as_bytes = self.itob(a, \"as_bytes\")\n result = assign_intrinsic_op(\n self.context,\n target=temp_desc,\n op=AVMOp.extract,\n immediates=[6, 2],\n args=[as_bytes],\n source_location=self.source_location,\n )\n return result\n\n def concat(self, a: Value | bytes, b: Value | bytes, temp_desc: str) -> Register:\n result = assign_intrinsic_op(\n self.context,\n target=temp_desc,\n op=AVMOp.concat,\n args=[a, b],\n source_location=self.source_location,\n )\n return result\n\n def constant(self, value: int | bytes) -> Value:\n if isinstance(value, int):\n return UInt64Constant(value=value, source_location=self.source_location)\n else:\n return BytesConstant(\n value=value, encoding=AVMBytesEncoding.base16, source_location=self.source_location\n )\n\n def set_bit(self, *, value: Value, index: int, bit: Value | int, temp_desc: str) -> Register:\n result = assign_intrinsic_op(\n self.context,\n target=temp_desc,\n op=AVMOp.setbit,\n args=[value, index, bit],\n return_type=value.ir_type,\n source_location=self.source_location,\n )\n return result\n\n def get_bit(self, value: Value, index: Value | int, temp_desc: str) -> Register:\n result = assign_intrinsic_op(\n self.context,\n target=temp_desc,\n op=AVMOp.getbit,\n args=[value, index],\n source_location=self.source_location,\n )\n return result\n\n def extract_to_end(self, value: Value, start: int, temp_desc: str) -> Register:\n if start > 255:\n raise InternalError(\n \"Cannot use extract with a length of 0 if start > 255\", self.source_location\n )\n result = assign_intrinsic_op(\n self.context,\n target=temp_desc,\n op=AVMOp.extract,\n immediates=[start, 0],\n args=[value],\n source_location=self.source_location,\n )\n return result\n\n def substring3(\n self,\n value: Value | bytes,\n start: Value | int,\n end_ex: Value | int,\n temp_desc: str,\n ) -> Register:\n result = assign_intrinsic_op(\n self.context,\n target=temp_desc,\n op=AVMOp.substring3,\n args=[value, start, end_ex],\n source_location=self.source_location,\n )\n return result\n\n def replace(\n self,\n value: Value | bytes,\n index: Value | int,\n replacement: Value | bytes,\n temp_desc: str,\n ) -> Register:\n result = assign_intrinsic_op(\n self.context,\n target=temp_desc,\n source_location=self.source_location,\n op=AVMOp.replace3,\n args=[value, index, replacement],\n )\n return result\n\n def extract3(\n self,\n value: Value | bytes,\n index: Value | int,\n length: Value | int,\n temp_desc: str,\n ) -> Register:\n result = assign_intrinsic_op(\n self.context,\n target=temp_desc,\n op=AVMOp.extract3,\n args=[value, index, length],\n source_location=self.source_location,\n )\n return result\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/builder\/_utils.py","language":"Python","license":"NOASSERTION","size":13454} {"code":"from collections.abc import Sequence\nfrom itertools import zip_longest\n\nimport attrs\n\nfrom puya import log\nfrom puya.avm import AVMType\nfrom puya.awst import (\n nodes as awst_nodes,\n wtypes,\n)\nfrom puya.errors import CodeError, InternalError\nfrom puya.ir.avm_ops import AVMOp\nfrom puya.ir.builder._utils import (\n OpFactory,\n assert_value,\n assign_intrinsic_op,\n assign_targets,\n assign_temp,\n invoke_puya_lib_subroutine,\n mktemp,\n)\nfrom puya.ir.builder.assignment import handle_assignment\nfrom puya.ir.context import IRFunctionBuildContext\nfrom puya.ir.models import (\n Intrinsic,\n Register,\n UInt64Constant,\n Value,\n ValueProvider,\n ValueTuple,\n)\nfrom puya.ir.types_ import IRType, get_wtype_arity\nfrom puya.parse import SourceLocation, sequential_source_locations_merge\nfrom puya.utils import bits_to_bytes, round_bits_to_nearest_bytes\n\nlogger = log.get_logger(__name__)\n\n\n@attrs.frozen(kw_only=True)\nclass ArrayIterator:\n context: IRFunctionBuildContext\n array_wtype: wtypes.ARC4Array\n array: Value\n array_length: Value\n source_location: SourceLocation\n\n def get_value_at_index(self, index: Value) -> ValueProvider:\n return arc4_array_index(\n self.context,\n array_wtype=self.array_wtype,\n array=self.array,\n index=index,\n source_location=self.source_location,\n assert_bounds=False, # iteration is always within bounds\n )\n\n\ndef decode_expr(context: IRFunctionBuildContext, expr: awst_nodes.ARC4Decode) -> ValueProvider:\n value = context.visitor.visit_and_materialise_single(expr.value)\n return _decode_arc4_value(context, value, expr.value.wtype, expr.wtype, expr.source_location)\n\n\ndef _decode_arc4_value(\n context: IRFunctionBuildContext,\n value: Value,\n arc4_wtype: wtypes.WType,\n target_wtype: wtypes.WType,\n loc: SourceLocation,\n) -> ValueProvider:\n match arc4_wtype, target_wtype:\n case wtypes.ARC4UIntN(), wtypes.biguint_wtype:\n return value\n case wtypes.ARC4UIntN(), (wtypes.uint64_wtype | wtypes.bool_wtype):\n return Intrinsic(\n op=AVMOp.btoi,\n args=[value],\n source_location=loc,\n )\n case wtypes.arc4_bool_wtype, wtypes.bool_wtype:\n return Intrinsic(\n op=AVMOp.getbit,\n args=[value, UInt64Constant(value=0, source_location=None)],\n source_location=loc,\n types=(IRType.bool,),\n )\n case wtypes.ARC4DynamicArray(element_type=wtypes.ARC4UIntN(n=8)), (\n wtypes.bytes_wtype\n | wtypes.string_wtype\n ):\n return Intrinsic(\n op=AVMOp.extract,\n immediates=[2, 0],\n args=[value],\n source_location=loc,\n )\n case (\n wtypes.ARC4Tuple()\n | wtypes.ARC4Struct() as arc4_tuple,\n wtypes.WTuple() as native_tuple,\n ) if (len(arc4_tuple.types) == len(native_tuple.types)):\n return _visit_arc4_tuple_decode(\n context, arc4_tuple, value, target_wtype=native_tuple, source_location=loc\n )\n raise InternalError(\n f\"unsupported ARC4Decode operation from {arc4_wtype} to {target_wtype}\", loc\n )\n\n\ndef encode_arc4_struct(\n context: IRFunctionBuildContext, expr: awst_nodes.NewStruct, wtype: wtypes.ARC4Struct\n) -> ValueProvider:\n assert expr.wtype == wtype\n elements = [\n context.visitor.visit_and_materialise_single(expr.values[field_name])\n for field_name in expr.wtype.fields\n ]\n return _visit_arc4_tuple_encode(context, elements, wtype.types, expr.source_location)\n\n\ndef encode_expr(context: IRFunctionBuildContext, expr: awst_nodes.ARC4Encode) -> ValueProvider:\n value = context.visitor.visit_expr(expr.value)\n return _encode_expr(context, value, expr.value.wtype, expr.wtype, expr.source_location)\n\n\ndef _encode_expr(\n context: IRFunctionBuildContext,\n value_provider: ValueProvider,\n value_wtype: wtypes.WType,\n arc4_wtype: wtypes.ARC4Type,\n loc: SourceLocation,\n) -> ValueProvider:\n match arc4_wtype:\n case wtypes.arc4_bool_wtype:\n (value,) = context.visitor.materialise_value_provider(\n value_provider, description=\"to_encode\"\n )\n return _encode_arc4_bool(context, value, loc)\n case wtypes.ARC4UIntN(n=bits):\n (value,) = context.visitor.materialise_value_provider(\n value_provider, description=\"to_encode\"\n )\n num_bytes = bits \/\/ 8\n return _itob_fixed(context, value, num_bytes, loc)\n case wtypes.ARC4Tuple(types=arc4_item_types):\n assert isinstance(\n value_wtype, wtypes.WTuple\n ), f\"expected WTuple argument, got {value_wtype.name}\"\n elements = context.visitor.materialise_value_provider(\n value_provider, description=\"elements_to_encode\"\n )\n arc4_items = _encode_arc4_tuple_items(\n context, elements, value_wtype.types, arc4_item_types, loc\n )\n return _visit_arc4_tuple_encode(context, arc4_items, arc4_item_types, loc)\n case wtypes.ARC4Struct(types=arc4_item_types):\n assert isinstance(\n value_wtype, wtypes.WTuple\n ), f\"expected WTuple argument, got {value_wtype.name}\"\n elements = context.visitor.materialise_value_provider(\n value_provider, description=\"elements_to_encode\"\n )\n arc4_items = _encode_arc4_tuple_items(\n context, elements, value_wtype.types, arc4_item_types, loc\n )\n return _visit_arc4_tuple_encode(context, arc4_items, arc4_item_types, loc)\n case wtypes.ARC4DynamicArray(element_type=wtypes.ARC4UIntN(n=8)):\n (value,) = context.visitor.materialise_value_provider(\n value_provider, description=\"to_encode\"\n )\n factory = OpFactory(context, loc)\n length = factory.len(value, \"length\")\n length_uint16 = factory.as_u16_bytes(length, \"length_uint16\")\n return factory.concat(length_uint16, value, \"encoded_value\")\n case wtypes.ARC4DynamicArray() | wtypes.ARC4StaticArray():\n raise InternalError(\n \"NewArray should be used instead of ARC4Encode for arrays\",\n loc,\n )\n case _:\n raise InternalError(\n f\"Unsupported wtype for ARC4Encode: {value_wtype}\",\n location=loc,\n )\n\n\ndef _encode_arc4_tuple_items(\n context: IRFunctionBuildContext,\n elements: list[Value],\n item_wtypes: Sequence[wtypes.WType],\n arc4_item_wtypes: Sequence[wtypes.ARC4Type],\n loc: SourceLocation,\n) -> Sequence[Value]:\n arc4_items = []\n for item_wtype, arc4_item_wtype in zip(item_wtypes, arc4_item_wtypes, strict=True):\n item_arity = get_wtype_arity(item_wtype)\n item_elements = elements[:item_arity]\n elements = elements[item_arity:]\n if item_wtype == arc4_item_wtype:\n arc4_items.extend(item_elements)\n continue\n\n item_value_provider = (\n item_elements[0]\n if item_arity == 1\n else ValueTuple(\n values=item_elements,\n source_location=sequential_source_locations_merge(\n [e.source_location for e in item_elements]\n ),\n )\n )\n arc4_item_vp = _encode_expr(\n context,\n item_value_provider,\n item_wtype,\n arc4_item_wtype,\n item_value_provider.source_location or loc,\n )\n (arc4_item,) = context.visitor.materialise_value_provider(arc4_item_vp, \"arc4_item\")\n arc4_items.append(arc4_item)\n return arc4_items\n\n\ndef encode_arc4_array(context: IRFunctionBuildContext, expr: awst_nodes.NewArray) -> ValueProvider:\n if not isinstance(expr.wtype, wtypes.ARC4Array):\n raise InternalError(\"Expected ARC4 Array expression\", expr.source_location)\n len_prefix = (\n len(expr.values).to_bytes(2, \"big\")\n if isinstance(expr.wtype, wtypes.ARC4DynamicArray)\n else b\"\"\n )\n\n factory = OpFactory(context, expr.source_location)\n elements = [context.visitor.visit_and_materialise_single(value) for value in expr.values]\n element_type = expr.wtype.element_type\n\n if element_type == wtypes.arc4_bool_wtype:\n array_head_and_tail = factory.constant(b\"\")\n for index, el in enumerate(elements):\n if index % 8 == 0:\n array_head_and_tail = factory.concat(\n array_head_and_tail, el, temp_desc=\"array_head_and_tail\"\n )\n else:\n is_true = factory.get_bit(el, 0, \"is_true\")\n\n array_head_and_tail = factory.set_bit(\n value=array_head_and_tail,\n index=index,\n bit=is_true,\n temp_desc=\"array_head_and_tail\",\n )\n else:\n array_head_and_tail = _arc4_items_as_arc4_tuple(\n context, element_type, elements, expr.source_location\n )\n\n return factory.concat(len_prefix, array_head_and_tail, \"array_data\")\n\n\ndef arc4_array_index(\n context: IRFunctionBuildContext,\n *,\n array_wtype: wtypes.ARC4Array,\n array: Value,\n index: Value,\n source_location: SourceLocation,\n assert_bounds: bool = True,\n) -> ValueProvider:\n factory = OpFactory(context, source_location)\n array_length_vp = _get_arc4_array_length(array_wtype, array, source_location)\n array_head_and_tail_vp = _get_arc4_array_head_and_tail(array_wtype, array, source_location)\n array_head_and_tail = factory.assign(array_head_and_tail_vp, \"array_head_and_tail\")\n item_wtype = array_wtype.element_type\n\n if is_arc4_dynamic_size(item_wtype):\n inner_element_size = _maybe_get_inner_element_size(item_wtype)\n if inner_element_size is not None:\n if assert_bounds:\n _assert_index_in_bounds(context, index, array_length_vp, source_location)\n return _read_dynamic_item_using_length_from_arc4_container(\n context,\n array_head_and_tail=array_head_and_tail,\n inner_element_size=inner_element_size,\n index=index,\n source_location=source_location,\n )\n else:\n # no _assert_index_in_bounds here as end offset calculation implicitly checks\n return _read_dynamic_item_using_end_offset_from_arc4_container(\n context,\n array_length_vp=array_length_vp,\n array_head_and_tail=array_head_and_tail,\n index=index,\n source_location=source_location,\n )\n if item_wtype == wtypes.arc4_bool_wtype:\n if assert_bounds:\n # this catches the edge case of bit arrays that are not a multiple of 8\n # e.g. reading index 6 & 7 of an array that has a length of 6\n _assert_index_in_bounds(context, index, array_length_vp, source_location)\n return _read_nth_bool_from_arc4_container(\n context,\n data=array_head_and_tail,\n index=index,\n source_location=source_location,\n )\n else:\n item_bit_size = _get_arc4_fixed_bit_size(item_wtype)\n # no _assert_index_in_bounds here as static items will error on read if past end of array\n return _read_static_item_from_arc4_container(\n data=array_head_and_tail,\n offset=factory.mul(index, item_bit_size \/\/ 8, \"item_offset\"),\n item_wtype=item_wtype,\n source_location=source_location,\n )\n\n\ndef arc4_tuple_index(\n context: IRFunctionBuildContext,\n base: Value,\n index: int,\n wtype: wtypes.ARC4Tuple | wtypes.ARC4Struct,\n source_location: SourceLocation,\n) -> ValueProvider:\n return _read_nth_item_of_arc4_heterogeneous_container(\n context,\n array_head_and_tail=base,\n index=index,\n tuple_type=wtype,\n source_location=source_location,\n )\n\n\ndef build_for_in_array(\n context: IRFunctionBuildContext,\n array_wtype: wtypes.ARC4Array,\n array_expr: awst_nodes.Expression,\n source_location: SourceLocation,\n) -> ArrayIterator:\n if not array_wtype.element_type.immutable:\n raise InternalError(\n \"Attempted iteration of an ARC4 array of mutable objects\", source_location\n )\n array = context.visitor.visit_and_materialise_single(array_expr)\n length_vp = _get_arc4_array_length(array_wtype, array, source_location)\n array_length = assign_temp(\n context,\n length_vp,\n temp_description=\"array_length\",\n source_location=source_location,\n )\n return ArrayIterator(\n context=context,\n array=array,\n array_length=array_length,\n array_wtype=array_wtype,\n source_location=source_location,\n )\n\n\ndef handle_arc4_assign(\n context: IRFunctionBuildContext,\n target: awst_nodes.Expression,\n value: ValueProvider,\n source_location: SourceLocation,\n *,\n is_nested_update: bool,\n) -> Value:\n result: Value\n match target:\n case awst_nodes.IndexExpression(\n base=awst_nodes.Expression(\n wtype=wtypes.ARC4DynamicArray() | wtypes.ARC4StaticArray() as array_wtype\n ) as base_expr,\n index=index_value,\n ):\n item = _arc4_replace_array_item(\n context,\n base_expr=base_expr,\n index_value_expr=index_value,\n wtype=array_wtype,\n value=value,\n source_location=source_location,\n )\n return handle_arc4_assign(\n context,\n target=base_expr,\n value=item,\n source_location=source_location,\n is_nested_update=True,\n )\n case awst_nodes.FieldExpression(\n base=awst_nodes.Expression(wtype=wtypes.ARC4Struct() as struct_wtype) as base_expr,\n name=field_name,\n ):\n item = _arc4_replace_struct_item(\n context,\n base_expr=base_expr,\n field_name=field_name,\n wtype=struct_wtype,\n value=value,\n source_location=source_location,\n )\n return handle_arc4_assign(\n context,\n target=base_expr,\n value=item,\n source_location=source_location,\n is_nested_update=True,\n )\n case awst_nodes.TupleItemExpression(\n base=awst_nodes.Expression(wtype=wtypes.ARC4Tuple() as tuple_wtype) as base_expr,\n index=index_value,\n ):\n item = _arc4_replace_tuple_item(\n context,\n base_expr=base_expr,\n index_int=index_value,\n wtype=tuple_wtype,\n value=value,\n source_location=source_location,\n )\n return handle_arc4_assign(\n context,\n target=base_expr,\n value=item,\n source_location=source_location,\n is_nested_update=True,\n )\n # this function is sometimes invoked outside an assignment expr\/stmt, which\n # is how a non l-value expression can be possible\n # TODO: refactor this so that this special case is handled where it originates\n case awst_nodes.TupleItemExpression(\n wtype=item_wtype,\n ) if not item_wtype.immutable:\n (result,) = handle_assignment(\n context,\n target,\n value=value,\n assignment_location=source_location,\n is_nested_update=True,\n )\n return result\n case _:\n (result,) = handle_assignment(\n context,\n target,\n value=value,\n assignment_location=source_location,\n is_nested_update=is_nested_update,\n )\n return result\n\n\ndef concat_values(\n context: IRFunctionBuildContext,\n left_expr: awst_nodes.Expression,\n right_expr: awst_nodes.Expression,\n source_location: SourceLocation,\n) -> Value:\n factory = OpFactory(context, source_location)\n # check left is a valid ARC4 array to concat with\n left_wtype = left_expr.wtype\n if not isinstance(left_wtype, wtypes.ARC4DynamicArray):\n raise InternalError(\"Expected left expression to be a dynamic ARC4 array\", source_location)\n left_element_type = left_wtype.element_type\n\n # check right is a valid type to concat\n right_wtype = right_expr.wtype\n if isinstance(right_wtype, wtypes.ARC4Array):\n right_element_type = right_wtype.element_type\n elif isinstance(right_wtype, wtypes.WTuple) and all(\n t == left_element_type for t in right_wtype.types\n ):\n right_element_type = left_element_type\n else:\n right_element_type = None\n\n if left_element_type != right_element_type:\n raise CodeError(\n f\"Unexpected operand types or order for concatenation:\"\n f\" {left_wtype} and {right_wtype}\",\n source_location,\n )\n\n if left_element_type == wtypes.arc4_bool_wtype:\n left = context.visitor.visit_and_materialise_single(left_expr)\n (r_data, r_length) = _get_arc4_array_tail_data_and_item_count(\n context, right_expr, source_location\n )\n is_packed = UInt64Constant(\n value=1 if isinstance(right_wtype, wtypes.ARC4Array) else 0,\n source_location=source_location,\n )\n return factory.assign(\n invoke_puya_lib_subroutine(\n context,\n full_name=\"_puya_lib.arc4.dynamic_array_concat_bits\",\n args=[left, r_data, r_length, is_packed],\n source_location=source_location,\n ),\n \"concat_result\",\n )\n if is_arc4_static_size(left_element_type):\n element_size = _get_arc4_fixed_bit_size(left_element_type)\n return _concat_dynamic_array_fixed_size(\n context,\n left=left_expr,\n right=right_expr,\n source_location=source_location,\n byte_size=element_size \/\/ 8,\n )\n if _is_byte_length_header(left_element_type):\n left = context.visitor.visit_and_materialise_single(left_expr)\n (r_data, r_length) = _get_arc4_array_tail_data_and_item_count(\n context, right_expr, source_location\n )\n return factory.assign(\n invoke_puya_lib_subroutine(\n context,\n full_name=\"_puya_lib.arc4.dynamic_array_concat_byte_length_head\",\n args=[left, r_data, r_length],\n source_location=source_location,\n ),\n \"concat_result\",\n )\n if is_arc4_dynamic_size(left_element_type):\n assert isinstance(left_wtype, wtypes.ARC4DynamicArray)\n left = context.visitor.visit_and_materialise_single(left_expr)\n if isinstance(right_wtype, wtypes.WTuple):\n right_values = context.visitor.visit_and_materialise(right_expr)\n r_count_vp: ValueProvider = UInt64Constant(\n value=len(right_wtype.types), source_location=source_location\n )\n r_head_and_tail_vp: ValueProvider = _arc4_items_as_arc4_tuple(\n context, left_element_type, right_values, source_location\n )\n elif isinstance(right_wtype, wtypes.ARC4Array):\n right = context.visitor.visit_and_materialise_single(right_expr)\n r_count_vp = _get_arc4_array_length(right_wtype, right, source_location)\n r_head_and_tail_vp = _get_arc4_array_head_and_tail(right_wtype, right, source_location)\n else:\n raise InternalError(\"Expected array\", source_location)\n args = factory.assign_multiple(\n l_count=_get_arc4_array_length(left_wtype, left, source_location),\n l_head_and_tail=_get_arc4_array_head_and_tail(left_wtype, left, source_location),\n r_count=r_count_vp,\n r_head_and_tail=r_head_and_tail_vp,\n )\n return factory.assign(\n invoke_puya_lib_subroutine(\n context,\n full_name=\"_puya_lib.arc4.dynamic_array_concat_dynamic_element\",\n args=list(args),\n source_location=source_location,\n ),\n \"concat_result\",\n )\n\n raise InternalError(\"Unexpected element type\", source_location)\n\n\ndef pop_arc4_array(\n context: IRFunctionBuildContext,\n expr: awst_nodes.ArrayPop,\n array_wtype: wtypes.ARC4DynamicArray,\n) -> ValueProvider:\n source_location = expr.source_location\n\n base = context.visitor.visit_and_materialise_single(expr.base)\n args: list[Value | int | bytes] = [base]\n if array_wtype.element_type == wtypes.arc4_bool_wtype:\n method_name = \"dynamic_array_pop_bit\"\n elif _is_byte_length_header(array_wtype.element_type): # TODO: multi_byte_length prefix?\n method_name = \"dynamic_array_pop_byte_length_head\"\n elif is_arc4_dynamic_size(array_wtype.element_type):\n method_name = \"dynamic_array_pop_dynamic_element\"\n else:\n fixed_size = _get_arc4_fixed_bit_size(array_wtype.element_type)\n method_name = \"dynamic_array_pop_fixed_size\"\n args.append(fixed_size \/\/ 8)\n\n popped = mktemp(context, IRType.bytes, source_location, description=\"popped\")\n data = mktemp(context, IRType.bytes, source_location, description=\"data\")\n assign_targets(\n context,\n targets=[popped, data],\n source=invoke_puya_lib_subroutine(\n context,\n full_name=f\"_puya_lib.arc4.{method_name}\",\n args=args,\n source_location=source_location,\n ),\n assignment_location=source_location,\n )\n\n handle_arc4_assign(\n context,\n target=expr.base,\n value=data,\n is_nested_update=True,\n source_location=source_location,\n )\n\n return popped\n\n\nARC4_TRUE = 0b10000000.to_bytes(1, \"big\")\nARC4_FALSE = 0b00000000.to_bytes(1, \"big\")\n\n\ndef _encode_arc4_bool(\n context: IRFunctionBuildContext, bit: Value, source_location: SourceLocation\n) -> Value:\n factory = OpFactory(context, source_location)\n value = factory.constant(0x00.to_bytes(1, \"big\"))\n return factory.set_bit(value=value, index=0, bit=bit, temp_desc=\"encoded_bool\")\n\n\ndef _visit_arc4_tuple_decode(\n context: IRFunctionBuildContext,\n wtype: wtypes.ARC4Tuple | wtypes.ARC4Struct,\n value: Value,\n target_wtype: wtypes.WTuple,\n source_location: SourceLocation,\n) -> ValueProvider:\n items = list[Value]()\n for index, (target_item_wtype, item_wtype) in enumerate(\n zip(target_wtype.types, wtype.types, strict=True)\n ):\n item_value = _read_nth_item_of_arc4_heterogeneous_container(\n context,\n array_head_and_tail=value,\n tuple_type=wtype,\n index=index,\n source_location=source_location,\n )\n item = assign_temp(\n context,\n temp_description=f\"item{index}\",\n source=item_value,\n source_location=source_location,\n )\n if target_item_wtype != item_wtype:\n decoded_item = _decode_arc4_value(\n context, item, item_wtype, target_item_wtype, source_location\n )\n items.extend(context.visitor.materialise_value_provider(decoded_item, item.name))\n else:\n items.append(item)\n return ValueTuple(source_location=source_location, values=items)\n\n\ndef _is_byte_length_header(wtype: wtypes.ARC4Type) -> bool:\n return (\n isinstance(wtype, wtypes.ARC4DynamicArray)\n and is_arc4_static_size(wtype.element_type)\n and _get_arc4_fixed_bit_size(wtype.element_type) == 8\n )\n\n\ndef _maybe_get_inner_element_size(item_wtype: wtypes.ARC4Type) -> int | None:\n match item_wtype:\n case wtypes.ARC4Array(element_type=inner_static_element_type) if is_arc4_static_size(\n inner_static_element_type\n ):\n pass\n case _:\n return None\n return _get_arc4_fixed_bit_size(inner_static_element_type) \/\/ 8\n\n\ndef _read_dynamic_item_using_length_from_arc4_container(\n context: IRFunctionBuildContext,\n *,\n array_head_and_tail: Value,\n inner_element_size: int,\n index: Value,\n source_location: SourceLocation,\n) -> ValueProvider:\n factory = OpFactory(context, source_location)\n item_offset_offset = factory.mul(index, 2, \"item_offset_offset\")\n item_start_offset = factory.extract_uint16(\n array_head_and_tail, item_offset_offset, \"item_offset\"\n )\n item_length = factory.extract_uint16(array_head_and_tail, item_start_offset, \"item_length\")\n item_length_in_bytes = factory.mul(item_length, inner_element_size, \"item_length_in_bytes\")\n item_total_length = factory.add(item_length_in_bytes, 2, \"item_head_tail_length\")\n return Intrinsic(\n op=AVMOp.extract3,\n args=[array_head_and_tail, item_start_offset, item_total_length],\n source_location=source_location,\n )\n\n\ndef _read_dynamic_item_using_end_offset_from_arc4_container(\n context: IRFunctionBuildContext,\n *,\n array_length_vp: ValueProvider,\n array_head_and_tail: Value,\n index: Value,\n source_location: SourceLocation,\n) -> ValueProvider:\n factory = OpFactory(context, source_location)\n item_offset_offset = factory.mul(index, 2, \"item_offset_offset\")\n item_start_offset = factory.extract_uint16(\n array_head_and_tail, item_offset_offset, \"item_offset\"\n )\n\n array_length = factory.assign(array_length_vp, \"array_length\")\n next_item_index = factory.add(index, 1, \"next_index\")\n # three possible outcomes of this op will determine the end offset\n # next_item_index < array_length -> has_next is true, use next_item_offset\n # next_item_index == array_length -> has_next is false, use array_length\n # next_item_index > array_length -> op will fail, comment provides context to error\n has_next = factory.assign(\n Intrinsic(\n op=AVMOp.sub,\n args=[array_length, next_item_index],\n source_location=source_location,\n error_message=\"Index access is out of bounds\",\n ),\n \"has_next\",\n )\n end_of_array = factory.len(array_head_and_tail, \"end_of_array\")\n next_item_offset_offset = factory.mul(next_item_index, 2, \"next_item_offset_offset\")\n # next_item_offset_offset will be past the array head when has_next is false, but this is ok as\n # the value will not be used. Additionally, next_item_offset_offset will always be a valid\n # offset in the overall array, because there will be at least 1 element (due to has_next\n # checking out of bounds) and this element will be dynamically sized,\n # which means it's data has at least one u16 in its header\n # e.g. reading here... has at least one u16 ........\n # v v\n # ArrayHead(u16, u16) ArrayTail(DynamicItemHead(... u16, ...), ..., DynamicItemTail, ...)\n next_item_offset = factory.extract_uint16(\n array_head_and_tail, next_item_offset_offset, \"next_item_offset\"\n )\n\n item_end_offset = factory.select(end_of_array, next_item_offset, has_next, \"end_offset\")\n return Intrinsic(\n op=AVMOp.substring3,\n args=[array_head_and_tail, item_start_offset, item_end_offset],\n source_location=source_location,\n )\n\n\ndef _visit_arc4_tuple_encode(\n context: IRFunctionBuildContext,\n elements: Sequence[Value],\n tuple_items: Sequence[wtypes.ARC4Type],\n expr_loc: SourceLocation,\n) -> ValueProvider:\n header_size = _determine_arc4_tuple_head_size(tuple_items, round_end_result=True)\n factory = OpFactory(context, expr_loc)\n current_tail_offset = factory.assign(factory.constant(header_size \/\/ 8), \"current_tail_offset\")\n encoded_tuple_buffer = factory.assign(factory.constant(b\"\"), \"encoded_tuple_buffer\")\n\n for index, (element, el_wtype) in enumerate(zip(elements, tuple_items, strict=True)):\n if el_wtype == wtypes.arc4_bool_wtype:\n # Pack boolean\n before_header = _determine_arc4_tuple_head_size(\n tuple_items[0:index], round_end_result=False\n )\n if before_header % 8 == 0:\n encoded_tuple_buffer = factory.concat(\n encoded_tuple_buffer, element, \"encoded_tuple_buffer\"\n )\n else:\n is_true = factory.get_bit(element, 0, \"is_true\")\n encoded_tuple_buffer = factory.set_bit(\n value=encoded_tuple_buffer,\n index=before_header,\n bit=is_true,\n temp_desc=\"encoded_tuple_buffer\",\n )\n elif is_arc4_static_size(el_wtype):\n # Append value\n encoded_tuple_buffer = factory.concat(\n encoded_tuple_buffer, element, \"encoded_tuple_buffer\"\n )\n else:\n # Append pointer\n offset_as_uint16 = factory.as_u16_bytes(current_tail_offset, \"offset_as_uint16\")\n encoded_tuple_buffer = factory.concat(\n encoded_tuple_buffer, offset_as_uint16, \"encoded_tuple_buffer\"\n )\n # Update Pointer\n data_length = factory.len(element, \"data_length\")\n current_tail_offset = factory.add(\n current_tail_offset, data_length, \"current_tail_offset\"\n )\n\n for element, el_wtype in zip(elements, tuple_items, strict=True):\n if is_arc4_dynamic_size(el_wtype):\n encoded_tuple_buffer = factory.concat(\n encoded_tuple_buffer, element, \"encoded_tuple_buffer\"\n )\n return encoded_tuple_buffer\n\n\ndef _arc4_replace_struct_item(\n context: IRFunctionBuildContext,\n base_expr: awst_nodes.Expression,\n field_name: str,\n wtype: wtypes.ARC4Struct,\n value: ValueProvider,\n source_location: SourceLocation,\n) -> Value:\n if not isinstance(wtype, wtypes.ARC4Struct):\n raise InternalError(\"Unsupported indexed assignment target\", source_location)\n try:\n index_int = wtype.names.index(field_name)\n except ValueError:\n raise CodeError(f\"Invalid arc4.Struct field name {field_name}\", source_location) from None\n return _arc4_replace_tuple_item(context, base_expr, index_int, wtype, value, source_location)\n\n\ndef _arc4_replace_tuple_item(\n context: IRFunctionBuildContext,\n base_expr: awst_nodes.Expression,\n index_int: int,\n wtype: wtypes.ARC4Struct | wtypes.ARC4Tuple,\n value: ValueProvider,\n source_location: SourceLocation,\n) -> Value:\n factory = OpFactory(context, source_location)\n base = context.visitor.visit_and_materialise_single(base_expr)\n value = factory.assign(value, \"assigned_value\")\n element_type = wtype.types[index_int]\n header_up_to_item = _determine_arc4_tuple_head_size(\n wtype.types[0:index_int],\n round_end_result=element_type != wtypes.arc4_bool_wtype,\n )\n if element_type == wtypes.arc4_bool_wtype:\n # Use Set bit\n is_true = factory.get_bit(value, 0, \"is_true\")\n return factory.set_bit(\n value=base,\n index=header_up_to_item,\n bit=is_true,\n temp_desc=\"updated_data\",\n )\n elif is_arc4_static_size(element_type):\n return factory.replace(\n base,\n header_up_to_item \/\/ 8,\n value,\n \"updated_data\",\n )\n else:\n dynamic_indices = [index for index, t in enumerate(wtype.types) if is_arc4_dynamic_size(t)]\n\n item_offset = factory.extract_uint16(base, header_up_to_item \/\/ 8, \"item_offset\")\n data_up_to_item = factory.extract3(base, 0, item_offset, \"data_up_to_item\")\n dynamic_indices_after_item = [i for i in dynamic_indices if i > index_int]\n\n if not dynamic_indices_after_item:\n # This is the last dynamic type in the tuple\n # No need to update headers - just replace the data\n return factory.concat(data_up_to_item, value, \"updated_data\")\n header_up_to_next_dynamic_item = _determine_arc4_tuple_head_size(\n types=wtype.types[0 : dynamic_indices_after_item[0]],\n round_end_result=True,\n )\n\n # update tail portion with new item\n next_item_offset = factory.extract_uint16(\n base,\n header_up_to_next_dynamic_item \/\/ 8,\n \"next_item_offset\",\n )\n total_data_length = factory.len(base, \"total_data_length\")\n data_beyond_item = factory.substring3(\n base,\n next_item_offset,\n total_data_length,\n \"data_beyond_item\",\n )\n updated_data = factory.concat(data_up_to_item, value, \"updated_data\")\n updated_data = factory.concat(updated_data, data_beyond_item, \"updated_data\")\n\n # loop through head and update any offsets after modified item\n item_length = factory.sub(next_item_offset, item_offset, \"item_length\")\n new_value_length = factory.len(value, \"new_value_length\")\n for dynamic_index in dynamic_indices_after_item:\n header_up_to_dynamic_item = _determine_arc4_tuple_head_size(\n types=wtype.types[0:dynamic_index],\n round_end_result=True,\n )\n\n tail_offset = factory.extract_uint16(\n updated_data, header_up_to_dynamic_item \/\/ 8, \"tail_offset\"\n )\n # have to add the new length and then subtract the original to avoid underflow\n tail_offset = factory.add(tail_offset, new_value_length, \"tail_offset\")\n tail_offset = factory.sub(tail_offset, item_length, \"tail_offset\")\n tail_offset_bytes = factory.as_u16_bytes(tail_offset, \"tail_offset_bytes\")\n\n updated_data = factory.replace(\n updated_data, header_up_to_dynamic_item \/\/ 8, tail_offset_bytes, \"updated_data\"\n )\n return updated_data\n\n\ndef _read_nth_item_of_arc4_heterogeneous_container(\n context: IRFunctionBuildContext,\n *,\n array_head_and_tail: Value,\n tuple_type: wtypes.ARC4Tuple | wtypes.ARC4Struct,\n index: int,\n source_location: SourceLocation,\n) -> ValueProvider:\n tuple_item_types = tuple_type.types\n\n item_wtype = tuple_item_types[index]\n head_up_to_item = _determine_arc4_tuple_head_size(\n tuple_item_types[:index], round_end_result=False\n )\n if item_wtype == wtypes.arc4_bool_wtype:\n return _read_nth_bool_from_arc4_container(\n context,\n data=array_head_and_tail,\n index=UInt64Constant(\n value=head_up_to_item,\n source_location=source_location,\n ),\n source_location=source_location,\n )\n head_offset = UInt64Constant(\n value=bits_to_bytes(head_up_to_item), source_location=source_location\n )\n if is_arc4_dynamic_size(item_wtype):\n item_start_offset = assign_intrinsic_op(\n context,\n target=\"item_start_offset\",\n op=AVMOp.extract_uint16,\n args=[array_head_and_tail, head_offset],\n source_location=source_location,\n )\n\n next_index = index + 1\n for tuple_item_index, tuple_item_type in enumerate(\n tuple_item_types[next_index:], start=next_index\n ):\n if is_arc4_dynamic_size(tuple_item_type):\n head_up_to_next_dynamic_item = _determine_arc4_tuple_head_size(\n tuple_item_types[:tuple_item_index], round_end_result=False\n )\n next_dynamic_head_offset = UInt64Constant(\n value=bits_to_bytes(head_up_to_next_dynamic_item),\n source_location=source_location,\n )\n item_end_offset = assign_intrinsic_op(\n context,\n target=\"item_end_offset\",\n op=AVMOp.extract_uint16,\n args=[array_head_and_tail, next_dynamic_head_offset],\n source_location=source_location,\n )\n break\n else:\n item_end_offset = assign_intrinsic_op(\n context,\n target=\"item_end_offset\",\n op=AVMOp.len_,\n args=[array_head_and_tail],\n source_location=source_location,\n )\n return Intrinsic(\n op=AVMOp.substring3,\n args=[array_head_and_tail, item_start_offset, item_end_offset],\n source_location=source_location,\n )\n else:\n return _read_static_item_from_arc4_container(\n data=array_head_and_tail,\n offset=head_offset,\n item_wtype=item_wtype,\n source_location=source_location,\n )\n\n\ndef _read_nth_bool_from_arc4_container(\n context: IRFunctionBuildContext,\n *,\n data: Value,\n index: Value,\n source_location: SourceLocation,\n) -> ValueProvider:\n # index is the bit position\n is_true = assign_temp(\n context,\n temp_description=\"is_true\",\n source=Intrinsic(op=AVMOp.getbit, args=[data, index], source_location=source_location),\n source_location=source_location,\n )\n return _encode_arc4_bool(context, is_true, source_location)\n\n\ndef _read_static_item_from_arc4_container(\n *,\n data: Value,\n offset: Value,\n item_wtype: wtypes.ARC4Type,\n source_location: SourceLocation,\n) -> ValueProvider:\n item_bit_size = _get_arc4_fixed_bit_size(item_wtype)\n item_length = UInt64Constant(value=item_bit_size \/\/ 8, source_location=source_location)\n return Intrinsic(\n op=AVMOp.extract3,\n args=[data, offset, item_length],\n source_location=source_location,\n error_message=\"Index access is out of bounds\",\n )\n\n\ndef _get_arc4_array_tail_data_and_item_count(\n context: IRFunctionBuildContext, expr: awst_nodes.Expression, source_location: SourceLocation\n) -> tuple[Value, Value]:\n \"\"\"\n For ARC4 containers (dynamic array, static array) will return the tail data and item count\n For native tuples will return the tuple items packed into the equivalent static array\n of tail data and item count\n \"\"\"\n factory = OpFactory(context, source_location)\n match expr:\n case awst_nodes.Expression(\n wtype=wtypes.ARC4DynamicArray() | wtypes.ARC4StaticArray() as arr_wtype\n ):\n array = context.visitor.visit_and_materialise_single(expr)\n array_length = factory.assign(\n _get_arc4_array_length(arr_wtype, array, source_location),\n \"array_length\",\n )\n array_head_and_tail = factory.assign(\n _get_arc4_array_head_and_tail(arr_wtype, array, source_location),\n \"array_head_and_tail\",\n )\n array_tail = _get_arc4_array_tail(\n context,\n element_wtype=arr_wtype.element_type,\n array_head_and_tail=array_head_and_tail,\n array_length=array_length,\n source_location=source_location,\n )\n return array_tail, array_length\n case awst_nodes.TupleExpression() as tuple_expr:\n if not all(isinstance(t, wtypes.ARC4Type) for t in tuple_expr.wtype.types):\n raise InternalError(\"Expected tuple to contain only ARC4 types\", source_location)\n\n values = context.visitor.visit_and_materialise(tuple_expr)\n data = factory.constant(b\"\")\n for val in values:\n data = factory.concat(data, val, \"data\")\n tuple_length = UInt64Constant(\n value=len(values),\n source_location=source_location,\n )\n return data, tuple_length\n case _:\n raise InternalError(f\"Unsupported array type: {expr.wtype}\")\n\n\ndef _itob_fixed(\n context: IRFunctionBuildContext, value: Value, num_bytes: int, source_location: SourceLocation\n) -> ValueProvider:\n if value.atype == AVMType.uint64:\n val_as_bytes = assign_temp(\n context,\n temp_description=\"val_as_bytes\",\n source=Intrinsic(op=AVMOp.itob, args=[value], source_location=source_location),\n source_location=source_location,\n )\n\n if num_bytes == 8:\n return val_as_bytes\n if num_bytes < 8:\n return Intrinsic(\n op=AVMOp.extract,\n immediates=[8 - num_bytes, num_bytes],\n args=[val_as_bytes],\n source_location=source_location,\n )\n bytes_value: Value = val_as_bytes\n else:\n len_ = assign_temp(\n context,\n temp_description=\"len_\",\n source=Intrinsic(op=AVMOp.len_, args=[value], source_location=source_location),\n source_location=source_location,\n )\n no_overflow = assign_temp(\n context,\n temp_description=\"no_overflow\",\n source=Intrinsic(\n op=AVMOp.lte,\n args=[\n len_,\n UInt64Constant(value=num_bytes, source_location=source_location),\n ],\n source_location=source_location,\n ),\n source_location=source_location,\n )\n\n context.block_builder.add(\n Intrinsic(\n op=AVMOp.assert_,\n args=[no_overflow],\n source_location=source_location,\n error_message=\"overflow\",\n )\n )\n bytes_value = value\n\n b_zeros = assign_temp(\n context,\n temp_description=\"b_zeros\",\n source=Intrinsic(\n op=AVMOp.bzero,\n args=[UInt64Constant(value=num_bytes, source_location=source_location)],\n source_location=source_location,\n ),\n source_location=source_location,\n )\n return Intrinsic(\n op=AVMOp.bitwise_or_bytes,\n args=[bytes_value, b_zeros],\n source_location=source_location,\n )\n\n\ndef _arc4_replace_array_item(\n context: IRFunctionBuildContext,\n *,\n base_expr: awst_nodes.Expression,\n index_value_expr: awst_nodes.Expression,\n wtype: wtypes.ARC4DynamicArray | wtypes.ARC4StaticArray,\n value: ValueProvider,\n source_location: SourceLocation,\n) -> Value:\n base = context.visitor.visit_and_materialise_single(base_expr)\n\n value = assign_temp(\n context, value, temp_description=\"assigned_value\", source_location=source_location\n )\n\n index = context.visitor.visit_and_materialise_single(index_value_expr)\n\n def updated_result(method_name: str, args: list[Value | int | bytes]) -> Register:\n invoke = invoke_puya_lib_subroutine(\n context,\n full_name=f\"_puya_lib.arc4.{method_name}\",\n args=args,\n source_location=source_location,\n )\n return assign_temp(\n context, invoke, temp_description=\"updated_value\", source_location=source_location\n )\n\n if _is_byte_length_header(wtype.element_type):\n if isinstance(wtype, wtypes.ARC4DynamicArray):\n return updated_result(\"dynamic_array_replace_byte_length_head\", [base, value, index])\n else:\n return updated_result(\n \"static_array_replace_byte_length_head\", [base, value, index, wtype.array_size]\n )\n elif is_arc4_dynamic_size(wtype.element_type):\n if isinstance(wtype, wtypes.ARC4DynamicArray):\n return updated_result(\"dynamic_array_replace_dynamic_element\", [base, value, index])\n else:\n return updated_result(\n \"static_array_replace_dynamic_element\", [base, value, index, wtype.array_size]\n )\n array_length = (\n UInt64Constant(value=wtype.array_size, source_location=source_location)\n if isinstance(wtype, wtypes.ARC4StaticArray)\n else Intrinsic(\n source_location=source_location,\n op=AVMOp.extract_uint16,\n args=[base, UInt64Constant(value=0, source_location=source_location)],\n )\n )\n _assert_index_in_bounds(context, index, array_length, source_location)\n\n element_size = _get_arc4_fixed_bit_size(wtype.element_type)\n dynamic_offset = 0 if isinstance(wtype, wtypes.ARC4StaticArray) else 2\n if element_size == 1:\n dynamic_offset *= 8\n offset_per_item = element_size\n else:\n offset_per_item = element_size \/\/ 8\n\n if isinstance(index_value_expr, awst_nodes.IntegerConstant):\n write_offset: Value = UInt64Constant(\n value=index_value_expr.value * offset_per_item + dynamic_offset,\n source_location=source_location,\n )\n else:\n write_offset = assign_intrinsic_op(\n context,\n target=\"write_offset\",\n op=AVMOp.mul,\n args=[index, offset_per_item],\n source_location=source_location,\n )\n if dynamic_offset:\n write_offset = assign_intrinsic_op(\n context,\n target=write_offset,\n op=AVMOp.add,\n args=[write_offset, dynamic_offset],\n source_location=source_location,\n )\n\n if element_size == 1:\n is_true = assign_intrinsic_op(\n context,\n target=\"is_true\",\n op=AVMOp.getbit,\n args=[value, 0],\n source_location=source_location,\n )\n updated_target = assign_intrinsic_op(\n context,\n target=\"updated_target\",\n op=AVMOp.setbit,\n args=[base, write_offset, is_true],\n return_type=base.ir_type,\n source_location=source_location,\n )\n else:\n updated_target = assign_intrinsic_op(\n context,\n target=\"updated_target\",\n op=AVMOp.replace3,\n args=[base, write_offset, value],\n source_location=source_location,\n )\n return updated_target\n\n\ndef _concat_dynamic_array_fixed_size(\n context: IRFunctionBuildContext,\n *,\n left: awst_nodes.Expression,\n right: awst_nodes.Expression,\n source_location: SourceLocation,\n byte_size: int,\n) -> Value:\n factory = OpFactory(context, source_location)\n\n def array_data(expr: awst_nodes.Expression) -> Value:\n match expr.wtype:\n case wtypes.ARC4StaticArray():\n return context.visitor.visit_and_materialise_single(expr)\n case wtypes.ARC4DynamicArray():\n expr_value = context.visitor.visit_and_materialise_single(expr)\n return factory.extract_to_end(expr_value, 2, \"expr_value_trimmed\")\n case wtypes.WTuple():\n values = context.visitor.visit_and_materialise(expr)\n data = factory.constant(b\"\")\n for val in values:\n data = factory.concat(data, val, \"data\")\n return data\n case _:\n raise InternalError(\n f\"Unexpected operand type for concatenation {expr.wtype}\", source_location\n )\n\n left_data = array_data(left)\n right_data = array_data(right)\n concatenated = factory.concat(left_data, right_data, \"concatenated\")\n if byte_size == 1:\n len_ = factory.len(concatenated, \"len_\")\n else:\n byte_len = factory.len(concatenated, \"byte_len\")\n len_ = assign_intrinsic_op(\n context,\n source_location=source_location,\n op=AVMOp.div_floor,\n args=[byte_len, byte_size],\n target=\"len_\",\n )\n\n len_16_bit = factory.as_u16_bytes(len_, \"len_16_bit\")\n return factory.concat(len_16_bit, concatenated, \"concat_result\")\n\n\ndef _arc4_items_as_arc4_tuple(\n context: IRFunctionBuildContext,\n item_wtype: wtypes.ARC4Type,\n items: Sequence[Value],\n source_location: SourceLocation,\n) -> Value:\n factory = OpFactory(context, source_location)\n result = factory.constant(b\"\")\n if is_arc4_dynamic_size(item_wtype):\n tail_offset: Value = UInt64Constant(value=len(items) * 2, source_location=source_location)\n for item in items:\n next_item_head = factory.as_u16_bytes(tail_offset, \"next_item_head\")\n result = factory.concat(result, next_item_head, \"result\")\n tail_offset = factory.add(\n tail_offset, factory.len(item, \"next_item_len\"), \"tail_offset\"\n )\n for item in items:\n result = factory.concat(result, item, \"result\")\n\n return result\n\n\ndef _assert_index_in_bounds(\n context: IRFunctionBuildContext,\n index: Value,\n length: ValueProvider,\n source_location: SourceLocation,\n) -> None:\n if isinstance(index, UInt64Constant) and isinstance(length, UInt64Constant):\n if 0 <= index.value < length.value:\n return\n raise CodeError(\"Index access is out of bounds\", source_location)\n\n array_length = assign_temp(\n context,\n source_location=source_location,\n temp_description=\"array_length\",\n source=length,\n )\n\n index_is_in_bounds = assign_temp(\n context,\n source_location=source_location,\n temp_description=\"index_is_in_bounds\",\n source=Intrinsic(\n op=AVMOp.lt,\n args=[index, array_length],\n source_location=source_location,\n ),\n )\n\n assert_value(\n context,\n index_is_in_bounds,\n source_location=source_location,\n comment=\"Index access is out of bounds\",\n )\n\n\ndef _get_arc4_array_length(\n wtype: wtypes.ARC4Array,\n array: Value,\n source_location: SourceLocation,\n) -> ValueProvider:\n match wtype:\n case wtypes.ARC4StaticArray(array_size=array_size):\n return UInt64Constant(value=array_size, source_location=source_location)\n case wtypes.ARC4DynamicArray():\n return Intrinsic(\n op=AVMOp.extract_uint16,\n args=[\n array,\n UInt64Constant(value=0, source_location=source_location),\n ],\n source_location=source_location,\n )\n case _:\n raise InternalError(\"Unexpected ARC4 array type\", source_location)\n\n\ndef _get_arc4_array_head_and_tail(\n wtype: wtypes.ARC4Array,\n array: Value,\n source_location: SourceLocation,\n) -> ValueProvider:\n match wtype:\n case wtypes.ARC4StaticArray():\n return array\n case wtypes.ARC4DynamicArray():\n return Intrinsic(\n op=AVMOp.extract,\n args=[array],\n immediates=[2, 0],\n source_location=source_location,\n )\n case _:\n raise InternalError(\"Unexpected ARC4 array type\", source_location)\n\n\ndef _get_arc4_array_tail(\n context: IRFunctionBuildContext,\n *,\n element_wtype: wtypes.ARC4Type,\n array_length: Value,\n array_head_and_tail: Value,\n source_location: SourceLocation,\n) -> Value:\n if is_arc4_static_size(element_wtype):\n # no header for static sized elements\n return array_head_and_tail\n\n factory = OpFactory(context, source_location)\n # special case to use extract with immediate length of 0 where possible\n # TODO: have an IR pseudo op, extract_to_end that handles this for non constant values?\n if isinstance(array_length, UInt64Constant) and array_length.value <= 127:\n return factory.extract_to_end(array_length, array_length.value * 2, \"data\")\n start_of_tail = factory.mul(array_length, 2, \"start_of_tail\")\n total_length = factory.len(array_head_and_tail, \"total_length\")\n return factory.substring3(array_head_and_tail, start_of_tail, total_length, \"data\")\n\n\ndef is_arc4_dynamic_size(wtype: wtypes.ARC4Type) -> bool:\n match wtype:\n case wtypes.ARC4DynamicArray():\n return True\n case wtypes.ARC4StaticArray(element_type=element_type):\n return is_arc4_dynamic_size(element_type)\n case wtypes.ARC4Tuple(types=types) | wtypes.ARC4Struct(types=types):\n return any(map(is_arc4_dynamic_size, types))\n return False\n\n\ndef is_arc4_static_size(wtype: wtypes.ARC4Type) -> bool:\n return not is_arc4_dynamic_size(wtype)\n\n\ndef _get_arc4_fixed_bit_size(wtype: wtypes.ARC4Type) -> int:\n if is_arc4_dynamic_size(wtype):\n raise InternalError(f\"Cannot get fixed bit size for a dynamic ABI type: {wtype}\")\n match wtype:\n case wtypes.arc4_bool_wtype:\n return 1\n case wtypes.ARC4UIntN(n=n) | wtypes.ARC4UFixedNxM(n=n):\n return n\n case wtypes.ARC4StaticArray(element_type=element_type, array_size=array_size):\n el_size = _get_arc4_fixed_bit_size(element_type)\n return round_bits_to_nearest_bytes(array_size * el_size)\n case wtypes.ARC4Tuple(types=types) | wtypes.ARC4Struct(types=types):\n return _determine_arc4_tuple_head_size(types, round_end_result=True)\n raise InternalError(f\"Unexpected ABI wtype: {wtype}\")\n\n\ndef _determine_arc4_tuple_head_size(\n types: Sequence[wtypes.ARC4Type], *, round_end_result: bool\n) -> int:\n bit_size = 0\n for t, next_t in zip_longest(types, types[1:]):\n size = 16 if is_arc4_dynamic_size(t) else _get_arc4_fixed_bit_size(t)\n bit_size += size\n if t == wtypes.arc4_bool_wtype and next_t != t and (round_end_result or next_t):\n bit_size = round_bits_to_nearest_bytes(bit_size)\n return bit_size\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/builder\/arc4.py","language":"Python","license":"NOASSERTION","size":54081} {"code":"import typing\nfrom collections.abc import Sequence\n\nfrom puya import log\nfrom puya.avm import AVMType\nfrom puya.awst import (\n nodes as awst_nodes,\n wtypes,\n)\nfrom puya.errors import CodeError, InternalError\nfrom puya.ir.avm_ops import AVMOp\nfrom puya.ir.builder import arc4\nfrom puya.ir.builder._tuple_util import build_tuple_registers\nfrom puya.ir.builder._utils import (\n assign,\n assign_targets,\n assign_temp,\n get_implicit_return_is_original,\n)\nfrom puya.ir.context import IRFunctionBuildContext\nfrom puya.ir.models import (\n Intrinsic,\n UInt64Constant,\n Value,\n ValueProvider,\n ValueTuple,\n)\nfrom puya.ir.types_ import IRType, get_wtype_arity\nfrom puya.ir.utils import format_tuple_index\nfrom puya.parse import SourceLocation\n\nlogger = log.get_logger(__name__)\n\n\ndef handle_assignment_expr(\n context: IRFunctionBuildContext,\n target: awst_nodes.Lvalue,\n value: awst_nodes.Expression,\n assignment_location: SourceLocation,\n) -> Sequence[Value]:\n expr_values = context.visitor.visit_expr(value)\n return handle_assignment(\n context,\n target=target,\n value=expr_values,\n is_nested_update=False,\n assignment_location=assignment_location,\n )\n\n\ndef handle_assignment(\n context: IRFunctionBuildContext,\n target: awst_nodes.Expression,\n value: ValueProvider,\n assignment_location: SourceLocation,\n *,\n is_nested_update: bool,\n) -> Sequence[Value]:\n match target:\n # special case: a nested update can cause a tuple item to be re-assigned\n # TODO: refactor this so that this special case is handled where it originates\n case (\n awst_nodes.TupleItemExpression(wtype=var_type, source_location=var_loc) as ti_expr\n ) if (\n # including assumptions in condition, so assignment will error if they are not true\n not var_type.immutable # mutable arc4 type\n and is_nested_update # is a reassignment due to a nested update\n and var_type.scalar_type is not None # only updating a scalar value\n ):\n base_name = _get_tuple_var_name(ti_expr)\n return _handle_maybe_implicit_return_assignment(\n context,\n base_name=base_name,\n wtype=var_type,\n value=value,\n var_loc=var_loc,\n assignment_loc=assignment_location,\n is_nested_update=is_nested_update,\n )\n case awst_nodes.VarExpression(name=base_name, source_location=var_loc, wtype=var_type):\n return _handle_maybe_implicit_return_assignment(\n context,\n base_name=base_name,\n wtype=var_type,\n value=value,\n var_loc=var_loc,\n assignment_loc=assignment_location,\n is_nested_update=is_nested_update,\n )\n case awst_nodes.TupleExpression() as tup_expr:\n source = context.visitor.materialise_value_provider(\n value, description=\"tuple_assignment\"\n )\n results = list[Value]()\n for item in tup_expr.items:\n arity = get_wtype_arity(item.wtype)\n values = source[:arity]\n del source[:arity]\n if len(values) != arity:\n raise CodeError(\"not enough values to unpack\", assignment_location)\n if arity == 1:\n nested_value: ValueProvider = values[0]\n else:\n nested_value = ValueTuple(values=values, source_location=value.source_location)\n results.extend(\n handle_assignment(\n context,\n target=item,\n value=nested_value,\n is_nested_update=False,\n assignment_location=assignment_location,\n )\n )\n if source:\n raise CodeError(\"too many values to unpack\", assignment_location)\n return results\n case awst_nodes.AppStateExpression(\n key=awst_key, wtype=wtype, source_location=field_location\n ):\n _ = wtypes.persistable_stack_type(wtype, field_location) # double check\n key_value = context.visitor.visit_and_materialise_single(awst_key)\n (mat_value,) = context.visitor.materialise_value_provider(\n value, description=\"new_state_value\"\n )\n context.block_builder.add(\n Intrinsic(\n op=AVMOp.app_global_put,\n args=[key_value, mat_value],\n source_location=assignment_location,\n )\n )\n return [mat_value]\n case awst_nodes.AppAccountStateExpression(\n key=awst_key, account=account_expr, wtype=wtype, source_location=field_location\n ):\n _ = wtypes.persistable_stack_type(wtype, field_location) # double check\n account = context.visitor.visit_and_materialise_single(account_expr)\n key_value = context.visitor.visit_and_materialise_single(awst_key)\n (mat_value,) = context.visitor.materialise_value_provider(\n value, description=\"new_state_value\"\n )\n context.block_builder.add(\n Intrinsic(\n op=AVMOp.app_local_put,\n args=[account, key_value, mat_value],\n source_location=assignment_location,\n )\n )\n return [mat_value]\n case awst_nodes.BoxValueExpression(\n key=awst_key, wtype=wtype, source_location=field_location\n ):\n scalar_type = wtypes.persistable_stack_type(wtype, field_location) # double check\n key_value = context.visitor.visit_and_materialise_single(awst_key)\n (mat_value,) = context.visitor.materialise_value_provider(\n value, description=\"new_box_value\"\n )\n if scalar_type == AVMType.bytes:\n serialized_value = mat_value\n if not (isinstance(wtype, wtypes.ARC4Type) and arc4.is_arc4_static_size(wtype)):\n context.block_builder.add(\n Intrinsic(\n op=AVMOp.box_del, args=[key_value], source_location=assignment_location\n )\n )\n elif scalar_type == AVMType.uint64:\n serialized_value = assign_temp(\n context=context,\n temp_description=\"new_box_value\",\n source=Intrinsic(\n op=AVMOp.itob,\n args=[mat_value],\n source_location=assignment_location,\n ),\n source_location=assignment_location,\n )\n else:\n typing.assert_never(scalar_type)\n context.block_builder.add(\n Intrinsic(\n op=AVMOp.box_put,\n args=[key_value, serialized_value],\n source_location=assignment_location,\n )\n )\n return [mat_value]\n case awst_nodes.IndexExpression() as ix_expr:\n if isinstance(ix_expr.base.wtype, wtypes.WArray):\n raise NotImplementedError\n elif isinstance(ix_expr.base.wtype, wtypes.ARC4Type): # noqa: RET506\n return (\n arc4.handle_arc4_assign(\n context,\n target=ix_expr,\n value=value,\n is_nested_update=is_nested_update,\n source_location=assignment_location,\n ),\n )\n else:\n raise InternalError(\n f\"Indexed assignment operation IR lowering\"\n f\" not implemented for base type {ix_expr.base.wtype.name}\",\n assignment_location,\n )\n case awst_nodes.FieldExpression() as field_expr:\n if isinstance(field_expr.base.wtype, wtypes.WStructType):\n raise NotImplementedError\n elif isinstance(field_expr.base.wtype, wtypes.ARC4Struct): # noqa: RET506\n return (\n arc4.handle_arc4_assign(\n context,\n target=field_expr,\n value=value,\n is_nested_update=is_nested_update,\n source_location=assignment_location,\n ),\n )\n else:\n raise InternalError(\n f\"Field assignment operation IR lowering\"\n f\" not implemented for base type {field_expr.base.wtype.name}\",\n assignment_location,\n )\n case _:\n raise CodeError(\n \"expression is not valid as an assignment target\", target.source_location\n )\n\n\ndef _handle_maybe_implicit_return_assignment(\n context: IRFunctionBuildContext,\n *,\n base_name: str,\n wtype: wtypes.WType,\n value: ValueProvider,\n var_loc: SourceLocation,\n assignment_loc: SourceLocation,\n is_nested_update: bool,\n) -> Sequence[Value]:\n registers = build_tuple_registers(context, base_name, wtype, var_loc)\n for register in registers:\n is_implicit_return = register.name in (\n p.name for p in context.subroutine.parameters if p.implicit_return\n )\n # if an implicitly returned value is explicitly reassigned, then set a register which will\n # prevent the original from being updated any further\n if is_implicit_return and not is_nested_update:\n assign(\n context,\n UInt64Constant(value=0, ir_type=IRType.bool, source_location=None),\n name=get_implicit_return_is_original(register.name),\n assignment_location=None,\n )\n\n assign_targets(\n context,\n source=value,\n targets=registers,\n assignment_location=assignment_loc,\n )\n return registers\n\n\ndef _get_tuple_var_name(expr: awst_nodes.TupleItemExpression) -> str:\n if isinstance(expr.base.wtype, wtypes.WTuple):\n if isinstance(expr.base, awst_nodes.TupleItemExpression):\n return format_tuple_index(expr.base.wtype, _get_tuple_var_name(expr.base), expr.index)\n if isinstance(expr.base, awst_nodes.VarExpression):\n return format_tuple_index(expr.base.wtype, expr.base.name, expr.index)\n raise CodeError(\"invalid assignment target\", expr.base.source_location)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/builder\/assignment.py","language":"Python","license":"NOASSERTION","size":10805} {"code":"import contextlib\nimport typing\nfrom collections.abc import Iterator, Sequence\n\nimport attrs\n\nfrom puya import log\nfrom puya.awst import nodes as awst_nodes\nfrom puya.errors import InternalError\nfrom puya.ir.models import (\n Assignment,\n BasicBlock,\n ControlOp,\n Goto,\n Op,\n Register,\n)\nfrom puya.ir.ssa import BraunSSA\nfrom puya.parse import SourceLocation\nfrom puya.utils import lazy_setdefault\n\nlogger = log.get_logger(__name__)\n\n\n@attrs.frozen(kw_only=True)\nclass _LoopTargets:\n on_break: BasicBlock\n on_continue: BasicBlock\n\n\nclass BlocksBuilder:\n def __init__(\n self,\n parameters: Sequence[Register],\n default_source_location: SourceLocation,\n ) -> None:\n self._loop_targets_stack: list[_LoopTargets] = []\n blocks = [BasicBlock(id=0, source_location=default_source_location)]\n self._blocks = blocks\n # initialize ssa\n self.ssa = BraunSSA(blocks, parameters, self.active_block)\n self.ssa.seal_block(self.active_block)\n\n self._pending_labelled_blocks = dict[awst_nodes.Label, BasicBlock]()\n self._created_labelled_blocks = dict[awst_nodes.Label, BasicBlock]()\n\n @property\n def active_block(self) -> BasicBlock:\n return self._blocks[-1]\n\n def add(self, op: Op) -> None:\n \"\"\"Add an op\"\"\"\n curr = self.active_block\n if curr.terminated:\n self._unreachable_error(op)\n else:\n curr.ops.append(op)\n if isinstance(op, Assignment):\n for target in op.targets:\n if not self.ssa.has_write(target.name, curr):\n raise InternalError(\n f\"ssa.write_variable not called for {target.name} in block {curr}\"\n )\n\n def maybe_terminate(self, control_op: ControlOp) -> bool:\n \"\"\"Add the control op for the block, if not already terminated.\"\"\"\n curr = self.active_block\n if curr.terminated:\n return False\n\n for target in control_op.targets():\n if self.ssa.is_sealed(target):\n raise InternalError(\n f\"Cannot add predecessor to block, as it is already sealed: \"\n f\"predecessor={curr}, block={target}\"\n )\n target.predecessors.append(curr)\n\n curr.terminator = control_op\n logger.debug(f\"Terminated {curr}\")\n return True\n\n def terminate(self, control_op: ControlOp) -> None:\n if not self.maybe_terminate(control_op):\n self._unreachable_error(control_op)\n\n def _unreachable_error(self, op: Op | ControlOp) -> None:\n if op.source_location:\n location = op.source_location\n message = \"unreachable code\"\n else:\n terminator_location = (\n self.active_block.terminator and self.active_block.terminator.source_location\n )\n location = terminator_location or self.active_block.source_location\n message = \"unreachable code follows\"\n logger.error(message, location=location)\n\n def goto(self, target: BasicBlock, source_location: SourceLocation | None = None) -> None:\n \"\"\"Add goto to a basic block, iff current block is not already terminated\"\"\"\n self.maybe_terminate(Goto(target=target, source_location=source_location))\n\n def goto_label(self, label: awst_nodes.Label, source_location: SourceLocation) -> None:\n try:\n target = self._created_labelled_blocks[label]\n except KeyError:\n target = lazy_setdefault(\n self._pending_labelled_blocks,\n label,\n lambda _: BasicBlock(label=label, source_location=source_location),\n )\n self.goto(target, source_location)\n\n def activate_block(self, block: BasicBlock) -> None:\n self._activate_block(block)\n self._seal_block_if_unlabelled(block)\n\n @contextlib.contextmanager\n def activate_open_block(self, block: BasicBlock) -> Iterator[None]:\n self._activate_block(block)\n try:\n yield\n finally:\n self._seal_block_if_unlabelled(block)\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 not self.active_block.terminated:\n raise InternalError(\n \"Attempted to activate a new block when current block has not been terminated\"\n )\n if not block.predecessors:\n raise InternalError(\"Attempted to add a (non-entry) block with no predecessors\")\n assert block.id is None\n block.id = len(self._blocks)\n self._blocks.append(block)\n\n def try_activate_block(self, block: BasicBlock) -> bool:\n if block.predecessors:\n self.activate_block(block)\n return True\n if not block.is_empty:\n # here as a sanity - there shouldn't've been any modifications of \"next\" block contents\n raise InternalError(\"next block has no predecessors but does have op(s)\")\n return False\n\n @contextlib.contextmanager\n def enter_loop(self, on_continue: BasicBlock, on_break: BasicBlock) -> Iterator[None]:\n self._loop_targets_stack.append(_LoopTargets(on_continue=on_continue, on_break=on_break))\n try:\n yield\n finally:\n self._loop_targets_stack.pop()\n\n def loop_break(self, source_location: SourceLocation) -> None:\n try:\n targets = self._loop_targets_stack[-1]\n except IndexError as ex:\n # TODO: this might be a code error or an internal error\n raise InternalError(\"break outside of loop\", source_location) from ex\n self.goto(target=targets.on_break, source_location=source_location)\n\n def loop_continue(self, source_location: SourceLocation) -> None:\n try:\n targets = self._loop_targets_stack[-1]\n except IndexError as ex:\n # TODO: this might be a code error or an internal error\n raise InternalError(\"continue outside of loop\", source_location) from ex\n self.goto(target=targets.on_continue, source_location=source_location)\n\n @typing.overload\n def mkblock(\n self, source_location: SourceLocation, \/, description: str | None\n ) -> BasicBlock: ...\n\n @typing.overload\n def mkblock(\n self, block: awst_nodes.Block, \/, description: str | None = None\n ) -> BasicBlock: ...\n\n @typing.overload\n def mkblock(\n self,\n block: awst_nodes.Block | None,\n \/,\n description: str,\n *,\n fallback_location: SourceLocation,\n ) -> BasicBlock: ...\n\n def mkblock(\n self,\n block_or_source_location: awst_nodes.Block | SourceLocation | None,\n \/,\n description: str | None = None,\n *,\n fallback_location: SourceLocation | None = None,\n ) -> BasicBlock:\n if isinstance(block_or_source_location, awst_nodes.Block):\n label = block_or_source_location.label\n comment = block_or_source_location.comment or description\n loc = block_or_source_location.source_location\n else:\n label = None\n comment = description\n loc_ = block_or_source_location or fallback_location\n assert loc_ is not None\n loc = loc_\n if label in self._created_labelled_blocks:\n raise InternalError(\n f\"block for label {label} has already been created\", fallback_location\n )\n if (label is not None) and (pending := self._pending_labelled_blocks.pop(label, None)):\n result = pending\n result.source_location = loc\n result.comment = comment\n else:\n result = BasicBlock(label=label, comment=comment, source_location=loc)\n if label is not None:\n self._created_labelled_blocks[label] = result\n return result\n\n def mkblocks(\n self, *descriptions: str, source_location: SourceLocation\n ) -> Iterator[BasicBlock]:\n for description in descriptions:\n yield self.mkblock(source_location, description)\n\n def finalise(self) -> list[BasicBlock]:\n for pending_label, pending in self._pending_labelled_blocks.items():\n logger.error(\n f\"block with label {pending_label} not found\", location=pending.source_location\n )\n for block in self._created_labelled_blocks.values():\n self.ssa.seal_block(block)\n self.ssa.verify_complete()\n return self._blocks.copy()\n\n def _seal_block_if_unlabelled(self, block: BasicBlock) -> None:\n if block.label is None:\n self.ssa.seal_block(block)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/builder\/blocks.py","language":"Python","license":"NOASSERTION","size":8792} {"code":"from puya.awst import nodes as awst_nodes\nfrom puya.ir.avm_ops import AVMOp\nfrom puya.ir.builder._utils import assign_intrinsic_op, assign_temp\nfrom puya.ir.context import IRFunctionBuildContext\nfrom puya.ir.models import Intrinsic, UInt64Constant, Value, ValueProvider\nfrom puya.ir.types_ import IRType\nfrom puya.parse import SourceLocation\n\n\ndef visit_bytes_slice_expression(\n context: IRFunctionBuildContext, expr: awst_nodes.SliceExpression\n) -> ValueProvider:\n base = context.visitor.visit_and_materialise_single(expr.base)\n if expr.begin_index is None and expr.end_index is None:\n return base\n\n if expr.begin_index is not None:\n start_value = context.visitor.visit_and_materialise_single(expr.begin_index)\n else:\n start_value = UInt64Constant(value=0, source_location=expr.source_location)\n\n if expr.end_index is not None:\n stop_value = context.visitor.visit_and_materialise_single(expr.end_index)\n return Intrinsic(\n op=AVMOp.substring3,\n args=[base, start_value, stop_value],\n source_location=expr.source_location,\n )\n elif isinstance(start_value, UInt64Constant):\n # we can use extract without computing the length when the start index is\n # a constant value and the end index is None (ie end of array)\n return Intrinsic(\n op=AVMOp.extract,\n immediates=[start_value.value, 0],\n args=[base],\n source_location=expr.source_location,\n )\n else:\n base_length = assign_temp(\n context,\n source_location=expr.source_location,\n source=Intrinsic(op=AVMOp.len_, args=[base], source_location=expr.source_location),\n temp_description=\"base_length\",\n )\n return Intrinsic(\n op=AVMOp.substring3,\n args=[base, start_value, base_length],\n source_location=expr.source_location,\n )\n\n\ndef visit_bytes_intersection_slice_expression(\n context: IRFunctionBuildContext, expr: awst_nodes.IntersectionSliceExpression\n) -> ValueProvider:\n base = context.visitor.visit_and_materialise_single(expr.base)\n length = assign_intrinsic_op(\n context,\n target=\"length\",\n op=AVMOp.len_,\n args=[base],\n source_location=expr.source_location,\n )\n start = (\n UInt64Constant(value=0, source_location=expr.source_location)\n if expr.begin_index is None\n else get_bounded_value(\n context,\n value=expr.begin_index,\n length=length,\n source_location=expr.source_location,\n )\n )\n end = (\n length\n if expr.end_index is None\n else get_bounded_value(\n context,\n value=expr.end_index,\n length=length,\n source_location=expr.source_location,\n )\n )\n if _is_end_check_required(start_index=expr.begin_index, end_index=expr.end_index):\n end_before_start = assign_intrinsic_op(\n context,\n target=\"end_before_start\",\n op=AVMOp.lt,\n args=[end, start],\n source_location=expr.source_location,\n )\n end = assign_intrinsic_op(\n context,\n target=\"end\",\n op=AVMOp.select,\n args=[end, start, end_before_start],\n source_location=expr.source_location,\n return_type=IRType.uint64,\n )\n return Intrinsic(\n op=AVMOp.substring3,\n args=[base, start, end],\n source_location=expr.source_location,\n )\n\n\ndef _is_end_check_required(\n *,\n start_index: awst_nodes.Expression | int | None,\n end_index: awst_nodes.Expression | int | None,\n) -> bool:\n \"\"\"\n Returns false if we can statically determine the start is less than or equal to the end (or\n will be once it is bounded between 0 <= index <= len(target) )\n \"\"\"\n if start_index is None or end_index is None:\n return False\n\n match start_index:\n case awst_nodes.IntegerConstant(value=start_static):\n pass\n case int(start_static):\n pass\n case _:\n # Start is not statically known so a check is required\n return True\n\n match end_index:\n case awst_nodes.IntegerConstant(value=end_static):\n pass\n case int(end_static):\n pass\n case _:\n # End is not statically known, a check is required if start is not 0\n return start_static > 0\n # If start is negative\n if start_static < 0:\n # a check is required if end is more_negative, or not negative at all\n return end_static < start_static or end_static > 0\n # If end is negative (and start is not), a check is required\n if end_static < 0:\n return True\n # A check is required if start is greater than end\n return start_static > end_static\n\n\ndef get_bounded_value(\n context: IRFunctionBuildContext,\n *,\n value: awst_nodes.Expression | int,\n length: Value,\n source_location: SourceLocation,\n) -> Value:\n if isinstance(value, int) and value < 0:\n # abs(value) >= length\n is_out_of_bounds = assign_intrinsic_op(\n context,\n target=\"is_out_of_bounds\",\n op=AVMOp.gte,\n args=[abs(value), length],\n source_location=source_location,\n )\n # length if is_out_of_bounds else abs(value)\n bounded_offset = assign_intrinsic_op(\n context,\n op=AVMOp.select,\n args=[abs(value), length, is_out_of_bounds],\n source_location=source_location,\n target=\"bounded_offset\",\n return_type=IRType.uint64,\n )\n # length - bounded_offset\n bounded_index = assign_intrinsic_op(\n context,\n op=AVMOp.sub,\n args=[length, bounded_offset],\n target=\"bounded_index\",\n source_location=source_location,\n )\n return bounded_index\n if isinstance(value, int):\n unbounded: Value = UInt64Constant(value=value, source_location=source_location)\n else:\n unbounded = context.visitor.visit_and_materialise_single(value)\n\n # unbounded > length\n is_out_of_bounds = assign_intrinsic_op(\n context,\n target=\"is_out_of_bounds\",\n op=AVMOp.gte,\n args=[unbounded, length],\n source_location=source_location,\n )\n # length if is_out_of_bounds else unbounded\n bounded_index = assign_intrinsic_op(\n context,\n op=AVMOp.select,\n args=[unbounded, length, is_out_of_bounds],\n source_location=source_location,\n target=\"bounded_index\",\n return_type=IRType.uint64,\n )\n return bounded_index\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/builder\/bytes.py","language":"Python","license":"NOASSERTION","size":6766} {"code":"from collections.abc import Sequence\n\nimport attrs\n\nfrom puya import log\nfrom puya.awst import (\n nodes as awst_nodes,\n wtypes,\n)\nfrom puya.errors import CodeError\nfrom puya.ir.builder._tuple_util import build_tuple_item_names\nfrom puya.ir.builder._utils import assign_targets, new_register_version\nfrom puya.ir.context import IRFunctionBuildContext\nfrom puya.ir.models import InvokeSubroutine, Register, Subroutine, Value, ValueProvider, ValueTuple\nfrom puya.parse import SourceLocation\n\nlogger = log.get_logger(__name__)\n\n\ndef visit_subroutine_call_expression(\n context: IRFunctionBuildContext, expr: awst_nodes.SubroutineCallExpression\n) -> ValueProvider | None:\n target = context.resolve_subroutine(expr.target, expr.source_location)\n return _call_subroutine(context, target, expr.args, expr.source_location)\n\n\ndef visit_puya_lib_call_expression(\n context: IRFunctionBuildContext, call: awst_nodes.PuyaLibCall\n) -> ValueProvider | None:\n try:\n target = context.embedded_funcs_lookup[call.func.value.id]\n except KeyError:\n raise CodeError(f\"invalid puya_lib {call.func.name}\", call.source_location) from None\n return _call_subroutine(context, target, call.args, call.source_location)\n\n\ndef _call_subroutine(\n context: IRFunctionBuildContext,\n target: Subroutine,\n args: Sequence[awst_nodes.CallArg],\n call_location: SourceLocation,\n) -> ValueProvider | None:\n arg_lookup = _build_arg_lookup(context, args, call_location)\n\n resolved_args = []\n implicit_args = []\n for idx, param in enumerate(target.parameters):\n arg_val = arg_lookup.get(index=idx, param_name=param.name)\n resolved_args.append(arg_val)\n if param.implicit_return:\n if arg_val in implicit_args:\n logger.error(\n \"mutable values cannot be passed more than once to a subroutine\",\n location=arg_val.source_location,\n )\n implicit_args.append(arg_val)\n if not arg_lookup.is_empty:\n raise CodeError(\"function call arguments do not match signature\", call_location) from None\n invoke_expr = InvokeSubroutine(\n source_location=call_location, args=resolved_args, target=target\n )\n if not implicit_args:\n return invoke_expr\n\n return_values = context.visitor.materialise_value_provider(invoke_expr, target.short_name)\n while implicit_args:\n in_arg = implicit_args.pop()\n out_value = return_values.pop()\n if isinstance(in_arg, Register):\n out_arg = new_register_version(context, in_arg)\n assign_targets(\n context,\n source=out_value,\n targets=[out_arg],\n assignment_location=call_location,\n )\n\n return (\n ValueTuple(values=return_values, source_location=call_location) if return_values else None\n )\n\n\n@attrs.define\nclass _ArgLookup:\n _source_location: SourceLocation\n _positional_args: dict[int, Value] = attrs.field(factory=dict, init=False)\n _named_args: dict[str, Value] = attrs.field(factory=dict, init=False)\n _arg_idx: int = attrs.field(default=0, init=False)\n\n @property\n def is_empty(self) -> bool:\n return not self._named_args and not self._positional_args\n\n def add(self, name: str | None, value: Value) -> None:\n if name is None:\n self._positional_args[self._arg_idx] = value\n else:\n self._named_args[name] = value\n self._arg_idx += 1\n\n def get(self, index: int, param_name: str | None) -> Value:\n if param_name is not None:\n by_name = self._named_args.pop(param_name, None)\n if by_name is not None:\n return by_name\n try:\n return self._positional_args.pop(index)\n except KeyError:\n raise CodeError(\n \"function call arguments do not match signature\", self._source_location\n ) from None\n\n\ndef _build_arg_lookup(\n context: IRFunctionBuildContext,\n args: Sequence[awst_nodes.CallArg],\n call_location: SourceLocation,\n) -> _ArgLookup:\n lookup = _ArgLookup(call_location)\n for expr_arg in args:\n if not isinstance(expr_arg.value.wtype, wtypes.WTuple):\n value = context.visitor.visit_and_materialise_single(expr_arg.value)\n lookup.add(name=expr_arg.name, value=value)\n else:\n values = context.visitor.visit_and_materialise(expr_arg.value)\n if expr_arg.name is None:\n for tup_value in values:\n lookup.add(name=None, value=tup_value)\n else:\n item_names = build_tuple_item_names(\n base_name=expr_arg.name,\n wtype=expr_arg.value.wtype,\n source_location=call_location,\n )\n for tup_value, (tup_item_name, _) in zip(values, item_names, strict=True):\n lookup.add(name=tup_item_name, value=tup_value)\n\n return lookup\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/builder\/callsub.py","language":"Python","license":"NOASSERTION","size":5028} {"code":"from puya import log\nfrom puya.awst import (\n nodes as awst_nodes,\n wtypes,\n)\nfrom puya.errors import InternalError\nfrom puya.ir import intrinsic_factory\nfrom puya.ir.builder._tuple_util import build_tuple_registers\nfrom puya.ir.builder._utils import assign_targets, new_register_version\nfrom puya.ir.context import IRFunctionBuildContext\nfrom puya.ir.models import (\n BasicBlock,\n ConditionalBranch,\n Switch,\n Value,\n ValueProvider,\n ValueTuple,\n)\nfrom puya.ir.types_ import get_wtype_arity, wtype_to_ir_type\nfrom puya.parse import SourceLocation\nfrom puya.utils import lazy_setdefault\n\nlogger = log.get_logger(__name__)\n\n\ndef handle_if_else(context: IRFunctionBuildContext, stmt: awst_nodes.IfElse) -> None:\n if_body = context.block_builder.mkblock(stmt.if_branch, \"if_body\")\n else_body = None\n if stmt.else_branch:\n else_body = context.block_builder.mkblock(stmt.else_branch, \"else_body\")\n next_block = context.block_builder.mkblock(stmt.source_location, \"after_if_else\")\n\n process_conditional(\n context,\n stmt.condition,\n true=if_body,\n false=else_body or next_block,\n loc=stmt.source_location,\n )\n _branch(context, if_body, stmt.if_branch, next_block)\n if else_body:\n assert stmt.else_branch\n _branch(context, else_body, stmt.else_branch, next_block)\n # activate the \"next\" block if it is reachable, which might not be the case\n # if all paths within the \"if\" and \"else\" branches return early\n context.block_builder.try_activate_block(next_block)\n\n\ndef handle_switch(context: IRFunctionBuildContext, statement: awst_nodes.Switch) -> None:\n case_blocks = dict[Value, BasicBlock]()\n ir_blocks = dict[awst_nodes.Block | None, BasicBlock]()\n for value, block in statement.cases.items():\n ir_value = context.visitor.visit_and_materialise_single(value)\n if ir_value in case_blocks:\n logger.error(\"code block is unreachable\", location=block.source_location)\n else:\n case_blocks[ir_value] = lazy_setdefault(\n ir_blocks,\n block,\n lambda _: context.block_builder.mkblock(\n block, # noqa: B023\n f\"switch_case_{len(ir_blocks)}\",\n ),\n )\n default_block = lazy_setdefault(\n ir_blocks,\n statement.default_case,\n lambda b: context.block_builder.mkblock(\n b, \"switch_case_default\", fallback_location=statement.source_location\n ),\n )\n next_block = context.block_builder.mkblock(statement.source_location, \"switch_case_next\")\n\n switch_value = context.visitor.visit_and_materialise_single(statement.value)\n context.block_builder.terminate(\n Switch(\n value=switch_value,\n cases=case_blocks,\n default=default_block,\n source_location=statement.source_location,\n )\n )\n for block_, ir_block in ir_blocks.items():\n _branch(context, ir_block, block_, next_block)\n\n # activate the \"next\" block if it is reachable, which might not be the case\n # if all code paths within the cases return early\n context.block_builder.try_activate_block(next_block)\n\n\ndef _branch(\n context: IRFunctionBuildContext,\n ir_block: BasicBlock,\n ast_block: awst_nodes.Block | None,\n next_ir_block: BasicBlock,\n) -> None:\n context.block_builder.activate_block(ir_block)\n if ast_block is not None:\n ast_block.accept(context.visitor)\n context.block_builder.goto(next_ir_block)\n\n\ndef process_conditional(\n context: IRFunctionBuildContext,\n expr: awst_nodes.Expression,\n *,\n true: BasicBlock,\n false: BasicBlock,\n loc: SourceLocation,\n) -> None:\n if expr.wtype != wtypes.bool_wtype:\n raise InternalError(\n \"_process_conditional should only be used for boolean conditionals\", loc\n )\n match expr:\n case awst_nodes.BooleanBinaryOperation(\n op=bool_op, left=lhs, right=rhs, source_location=loc\n ):\n # Short circuit boolean binary operators in a conditional context.\n contd = context.block_builder.mkblock(loc, f\"{bool_op}_contd\")\n if bool_op == \"and\":\n process_conditional(context, lhs, true=contd, false=false, loc=loc)\n elif bool_op == \"or\":\n process_conditional(context, lhs, true=true, false=contd, loc=loc)\n else:\n raise InternalError(\n f\"Unhandled boolean operator for short circuiting: {bool_op}\", loc\n )\n context.block_builder.activate_block(contd)\n process_conditional(context, rhs, true=true, false=false, loc=loc)\n case awst_nodes.Not(expr=expr, source_location=loc):\n process_conditional(context, expr, true=false, false=true, loc=loc)\n case _:\n condition_value = context.visitor.visit_and_materialise_single(expr)\n context.block_builder.terminate(\n ConditionalBranch(\n condition=condition_value,\n non_zero=true,\n zero=false,\n source_location=loc,\n )\n )\n\n\ndef handle_while_loop(context: IRFunctionBuildContext, statement: awst_nodes.WhileLoop) -> None:\n top, next_block = context.block_builder.mkblocks(\n \"while_top\", \"after_while\", source_location=statement.source_location\n )\n body = context.block_builder.mkblock(statement.loop_body, \"while_body\")\n context.block_builder.goto(top)\n with context.block_builder.activate_open_block(top):\n process_conditional(\n context,\n statement.condition,\n true=body,\n false=next_block,\n loc=statement.source_location,\n )\n context.block_builder.activate_block(body)\n with context.block_builder.enter_loop(on_continue=top, on_break=next_block):\n statement.loop_body.accept(context.visitor)\n context.block_builder.goto(top)\n\n context.block_builder.activate_block(next_block)\n\n\ndef handle_conditional_expression(\n context: IRFunctionBuildContext, expr: awst_nodes.ConditionalExpression\n) -> ValueProvider:\n # if lhs and rhs are both guaranteed to not produce side effects, we can use a simple select op\n # TODO: expand detection of side-effect free to include \"pure\" ops\n if (\n get_wtype_arity(expr.wtype) == 1\n and isinstance(\n expr.true_expr, awst_nodes.VarExpression | awst_nodes.CompileTimeConstantExpression\n )\n and isinstance(\n expr.false_expr, awst_nodes.VarExpression | awst_nodes.CompileTimeConstantExpression\n )\n ):\n false_reg = context.visitor.visit_and_materialise_single(expr.false_expr)\n true_reg = context.visitor.visit_and_materialise_single(expr.true_expr)\n condition_value = context.visitor.visit_and_materialise_single(expr.condition)\n return intrinsic_factory.select(\n condition=condition_value,\n true=true_reg,\n false=false_reg,\n type_=wtype_to_ir_type(expr),\n source_location=expr.source_location,\n )\n true_block, false_block, merge_block = context.block_builder.mkblocks(\n \"ternary_true\", \"ternary_false\", \"ternary_merge\", source_location=expr.source_location\n )\n tmp_var_name = context.next_tmp_name(\"ternary_result\")\n true_registers = build_tuple_registers(context, tmp_var_name, expr.wtype, expr.source_location)\n\n process_conditional(\n context,\n expr.condition,\n true=true_block,\n false=false_block,\n loc=expr.source_location,\n )\n\n context.block_builder.activate_block(true_block)\n true_vp = context.visitor.visit_expr(expr.true_expr)\n assign_targets(\n context,\n source=true_vp,\n targets=true_registers,\n assignment_location=expr.true_expr.source_location,\n )\n context.block_builder.goto(merge_block)\n\n context.block_builder.activate_block(false_block)\n false_vp = context.visitor.visit_expr(expr.false_expr)\n assign_targets(\n context,\n source=false_vp,\n targets=[new_register_version(context, reg) for reg in true_registers],\n assignment_location=expr.false_expr.source_location,\n )\n context.block_builder.goto(merge_block)\n\n context.block_builder.activate_block(merge_block)\n result = [\n context.ssa.read_variable(variable=r.name, ir_type=r.ir_type, block=merge_block)\n for r in true_registers\n ]\n if len(result) == 1:\n return result[0]\n return ValueTuple(values=result, source_location=expr.source_location)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/builder\/flow_control.py","language":"Python","license":"NOASSERTION","size":8727} {"code":"import typing\n\nfrom puya import log\nfrom puya.awst import (\n nodes as awst_nodes,\n wtypes,\n)\nfrom puya.awst.nodes import Expression\nfrom puya.errors import CodeError, InternalError\nfrom puya.ir.avm_ops import AVMOp\nfrom puya.ir.builder import arc4\nfrom puya.ir.builder._tuple_util import build_tuple_registers, get_tuple_item_values\nfrom puya.ir.builder._utils import (\n assert_value,\n assign_intrinsic_op,\n assign_targets,\n assign_temp,\n)\nfrom puya.ir.context import IRFunctionBuildContext\nfrom puya.ir.models import (\n ConditionalBranch,\n GotoNth,\n Intrinsic,\n Register,\n UInt64Constant,\n Value,\n ValueProvider,\n)\nfrom puya.ir.types_ import IRType\nfrom puya.ir.utils import lvalue_items\nfrom puya.parse import SourceLocation\n\nlogger = log.get_logger(__name__)\n\n\nclass LoopVariables(typing.NamedTuple):\n item_registers: typing.Sequence[Register]\n index_: Register | None\n\n def refresh_assignment(self, context: IRFunctionBuildContext) -> \"LoopVariables\":\n item = [_refresh_mutated_variable(context, i) for i in self.item_registers]\n if self.index_ is None:\n index = None\n else:\n index = _refresh_mutated_variable(context, self.index_)\n return LoopVariables(item, index)\n\n\nclass LoopAssigner:\n def __init__(\n self, context: IRFunctionBuildContext, items: awst_nodes.Lvalue, *, has_enumerate: bool\n ):\n self._context: typing.Final = context\n self._items: typing.Final = items\n self.has_enumerate: typing.Final = has_enumerate\n\n def assign_user_loop_vars(\n self, item_provider: ValueProvider, index_provider: ValueProvider\n ) -> LoopVariables:\n registers = self._build_registers_from_lvalue(self._items)\n if not self.has_enumerate:\n index_register = None\n item_registers = registers\n else:\n (index_register, *item_registers) = registers\n assign_targets(\n self._context,\n source=item_provider,\n targets=item_registers,\n assignment_location=self._items.source_location,\n )\n if index_register:\n assign_targets(\n self._context,\n source=index_provider,\n targets=[index_register],\n assignment_location=self._items.source_location,\n )\n return LoopVariables(item_registers, index_register)\n\n def _build_registers_from_lvalue(self, target: awst_nodes.Lvalue) -> list[Register]:\n match target:\n case awst_nodes.VarExpression(name=var_name, source_location=var_loc, wtype=var_type):\n return build_tuple_registers(self._context, var_name, var_type, var_loc)\n case awst_nodes.TupleExpression() as tup_expr:\n tuple_items = lvalue_items(tup_expr)\n return [\n reg for item in tuple_items for reg in self._build_registers_from_lvalue(item)\n ]\n case _:\n raise CodeError(\n \"unsupported assignment target in loop\", self._items.source_location\n )\n\n\ndef handle_for_in_loop(context: IRFunctionBuildContext, statement: awst_nodes.ForInLoop) -> None:\n sequence = statement.sequence\n has_enumerate = False\n reverse_items = False\n reverse_index = False\n\n while True:\n match sequence:\n case awst_nodes.Enumeration():\n if has_enumerate:\n raise CodeError(\n \"Nested enumeration is not currently supported\", sequence.source_location\n )\n sequence = sequence.expr\n has_enumerate = True\n case awst_nodes.Reversed():\n sequence = sequence.expr\n reverse_items = not reverse_items\n if not has_enumerate:\n reverse_index = not reverse_index\n case _:\n break\n\n assign_user_loop_vars = LoopAssigner(\n context,\n items=statement.items,\n has_enumerate=has_enumerate,\n )\n\n match sequence:\n case awst_nodes.Range(\n start=range_start, stop=range_stop, step=range_step, source_location=range_loc\n ):\n _iterate_urange(\n context,\n loop_body=statement.loop_body,\n assigner=assign_user_loop_vars,\n statement_loc=statement.source_location,\n range_start=range_start,\n range_stop=range_stop,\n range_step=range_step,\n range_loc=range_loc,\n reverse_items=reverse_items,\n reverse_index=reverse_index,\n )\n case awst_nodes.Expression(wtype=wtypes.WTuple(types=item_types)) as tuple_expression:\n if not item_types:\n logger.debug(\"Skipping ForInStatement which iterates an empty sequence.\")\n else:\n _iterate_tuple(\n context,\n loop_body=statement.loop_body,\n assigner=assign_user_loop_vars,\n tuple_expr=tuple_expression,\n statement_loc=statement.source_location,\n reverse_index=reverse_index,\n reverse_items=reverse_items,\n )\n case awst_nodes.Expression(wtype=wtypes.bytes_wtype):\n bytes_value = context.visitor.visit_and_materialise_single(sequence)\n byte_length = assign_temp(\n context,\n temp_description=\"bytes_length\",\n source=Intrinsic(\n op=AVMOp.len_,\n args=[bytes_value],\n source_location=statement.source_location,\n ),\n source_location=statement.source_location,\n )\n\n def get_byte_at_index(index_register: Value) -> ValueProvider:\n return Intrinsic(\n op=AVMOp.extract3,\n args=[\n bytes_value,\n index_register,\n UInt64Constant(value=1, source_location=None),\n ],\n source_location=statement.items.source_location,\n )\n\n _iterate_indexable(\n context,\n loop_body=statement.loop_body,\n indexable_size=byte_length,\n get_value_at_index=get_byte_at_index,\n assigner=assign_user_loop_vars,\n statement_loc=statement.source_location,\n reverse_index=reverse_index,\n reverse_items=reverse_items,\n )\n case awst_nodes.Expression(wtype=wtypes.ARC4Array() as array_wtype):\n iterator = arc4.build_for_in_array(\n context,\n array_wtype,\n sequence,\n statement.source_location,\n )\n _iterate_indexable(\n context,\n loop_body=statement.loop_body,\n indexable_size=iterator.array_length,\n get_value_at_index=iterator.get_value_at_index,\n assigner=assign_user_loop_vars,\n statement_loc=statement.source_location,\n reverse_index=reverse_index,\n reverse_items=reverse_items,\n )\n case _:\n raise InternalError(\"Unsupported ForInLoop sequence\", statement.source_location)\n\n\ndef _iterate_urange(\n context: IRFunctionBuildContext,\n *,\n loop_body: awst_nodes.Block,\n assigner: LoopAssigner,\n statement_loc: SourceLocation,\n range_start: Expression,\n range_stop: Expression,\n range_step: Expression,\n range_loc: SourceLocation,\n reverse_items: bool,\n reverse_index: bool,\n) -> None:\n step = context.visitor.visit_and_materialise_single(range_step)\n stop = context.visitor.visit_and_materialise_single(range_stop)\n start = context.visitor.visit_and_materialise_single(range_start)\n assert_value(context, step, source_location=statement_loc, comment=\"Step cannot be zero\")\n\n if reverse_items or reverse_index:\n return _iterate_urange_with_reversal(\n context,\n loop_body=loop_body,\n assigner=assigner,\n statement_loc=statement_loc,\n start=start,\n stop=stop,\n step=step,\n range_loc=range_loc,\n reverse_items=reverse_items,\n reverse_index=reverse_index,\n )\n else:\n return _iterate_urange_simple(\n context,\n loop_body=loop_body,\n assigner=assigner,\n statement_loc=statement_loc,\n start=start,\n stop=stop,\n step=step,\n range_loc=range_loc,\n )\n\n\ndef _iterate_urange_simple(\n context: IRFunctionBuildContext,\n *,\n loop_body: awst_nodes.Block,\n assigner: LoopAssigner,\n statement_loc: SourceLocation,\n start: Value,\n stop: Value,\n step: Value,\n range_loc: SourceLocation,\n) -> None:\n body = context.block_builder.mkblock(loop_body, \"for_body\")\n header, footer, next_block = context.block_builder.mkblocks(\n \"for_header\", \"for_footer\", \"after_for\", source_location=statement_loc\n )\n\n loop_vars = assigner.assign_user_loop_vars(\n start, UInt64Constant(value=0, source_location=None)\n )\n context.block_builder.goto(header)\n with context.block_builder.activate_open_block(header):\n (current_range_item,), current_range_index = loop_vars.refresh_assignment(context)\n continue_looping = assign_intrinsic_op(\n context,\n target=\"continue_looping\",\n op=AVMOp.lt,\n args=[current_range_item, stop],\n source_location=range_loc,\n )\n context.block_builder.terminate(\n ConditionalBranch(\n condition=continue_looping,\n non_zero=body,\n zero=next_block,\n source_location=statement_loc,\n )\n )\n\n context.block_builder.activate_block(body)\n with context.block_builder.enter_loop(on_continue=footer, on_break=next_block):\n loop_body.accept(context.visitor)\n\n context.block_builder.goto(footer)\n if context.block_builder.try_activate_block(footer):\n assign_intrinsic_op(\n context,\n target=current_range_item,\n op=AVMOp.add,\n args=[current_range_item, step],\n source_location=range_loc,\n )\n if current_range_index:\n assign_intrinsic_op(\n context,\n target=current_range_index,\n op=AVMOp.add,\n args=[current_range_index, 1],\n source_location=range_loc,\n )\n context.block_builder.goto(header)\n\n context.block_builder.activate_block(next_block)\n\n\ndef _iterate_urange_with_reversal(\n context: IRFunctionBuildContext,\n *,\n loop_body: awst_nodes.Block,\n assigner: LoopAssigner,\n statement_loc: SourceLocation,\n start: Value,\n stop: Value,\n step: Value,\n range_loc: SourceLocation,\n reverse_items: bool,\n reverse_index: bool,\n) -> None:\n assert reverse_items or reverse_index\n body = context.block_builder.mkblock(loop_body, \"for_body\")\n header, footer, increment_block, next_block = context.block_builder.mkblocks(\n \"for_header\", \"for_footer\", \"for_increment\", \"after_for\", source_location=statement_loc\n )\n\n # The following code will result in underflow if we don't pre-check the urange\n # params\n should_loop = assign_intrinsic_op(\n context,\n target=\"should_loop\",\n op=AVMOp.lt,\n args=[start, stop],\n source_location=statement_loc,\n )\n context.block_builder.terminate(\n ConditionalBranch(\n condition=should_loop,\n non_zero=header,\n zero=next_block,\n source_location=statement_loc,\n )\n )\n\n context.block_builder.activate_block(header)\n # iteration_count = ((stop - 1) - start) \/\/ step + 1\n # => iteration_count - 1 = (stop - start - 1) \/\/ step\n range_length = assign_intrinsic_op(\n context,\n target=\"range_length\",\n op=AVMOp.sub,\n args=[stop, start],\n source_location=range_loc,\n )\n range_length_minus_one = assign_intrinsic_op(\n context,\n target=\"range_length_minus_one\",\n op=AVMOp.sub,\n args=[range_length, 1],\n source_location=range_loc,\n )\n iteration_count_minus_one = assign_intrinsic_op(\n context,\n target=\"iteration_count_minus_one\",\n op=AVMOp.div_floor,\n args=[range_length_minus_one, step],\n source_location=range_loc,\n )\n range_delta = assign_intrinsic_op(\n context,\n target=\"range_delta\",\n op=AVMOp.mul,\n args=[step, iteration_count_minus_one],\n source_location=range_loc,\n )\n max_range_item = assign_intrinsic_op(\n context,\n target=\"max_range_item\",\n op=AVMOp.add,\n args=[start, range_delta],\n source_location=range_loc,\n )\n loop_vars = assigner.assign_user_loop_vars(\n start if not reverse_items else max_range_item,\n (\n UInt64Constant(value=0, source_location=None)\n if not reverse_index\n else iteration_count_minus_one\n ),\n )\n context.block_builder.goto(body)\n\n with context.block_builder.activate_open_block(body):\n (current_range_item,), current_range_index = loop_vars.refresh_assignment(context)\n\n with context.block_builder.enter_loop(on_continue=footer, on_break=next_block):\n loop_body.accept(context.visitor)\n\n context.block_builder.goto(footer)\n if context.block_builder.try_activate_block(footer):\n continue_looping_op = Intrinsic(\n op=AVMOp.lt,\n args=(\n [current_range_item, max_range_item]\n if not reverse_items\n else [start, current_range_item]\n ),\n source_location=range_loc,\n )\n continue_looping = assign_temp(\n context,\n source=continue_looping_op,\n temp_description=\"continue_looping\",\n source_location=range_loc,\n )\n\n context.block_builder.terminate(\n ConditionalBranch(\n condition=continue_looping,\n non_zero=increment_block,\n zero=next_block,\n source_location=statement_loc,\n )\n )\n\n context.block_builder.activate_block(increment_block)\n assign_intrinsic_op(\n context,\n target=current_range_item,\n op=AVMOp.add if not reverse_items else AVMOp.sub,\n args=[current_range_item, step],\n source_location=range_loc,\n )\n if current_range_index:\n assign_intrinsic_op(\n context,\n target=current_range_index,\n op=AVMOp.add if not reverse_index else AVMOp.sub,\n args=[current_range_index, 1],\n source_location=range_loc,\n )\n context.block_builder.goto(body)\n\n context.block_builder.activate_block(next_block)\n\n\ndef _iterate_indexable(\n context: IRFunctionBuildContext,\n *,\n loop_body: awst_nodes.Block,\n assigner: LoopAssigner,\n statement_loc: SourceLocation,\n indexable_size: Value,\n get_value_at_index: typing.Callable[[Value], ValueProvider],\n reverse_items: bool,\n reverse_index: bool,\n) -> None:\n body = context.block_builder.mkblock(loop_body, \"for_body\")\n header, footer, next_block = context.block_builder.mkblocks(\n \"for_header\", \"for_footer\", \"after_for\", source_location=statement_loc\n )\n\n index_internal = assign_temp(\n context,\n source=UInt64Constant(value=0, source_location=None),\n temp_description=\"item_index_internal\",\n source_location=None,\n )\n reverse_index_internal = assign_temp(\n context,\n source=indexable_size,\n temp_description=\"reverse_index_internal\",\n source_location=None,\n )\n context.block_builder.goto(header)\n\n with context.block_builder.activate_open_block(header):\n current_index_internal = _refresh_mutated_variable(context, index_internal)\n if not (reverse_items or reverse_index):\n continue_looping = assign_intrinsic_op(\n context,\n target=\"continue_looping\",\n op=AVMOp.lt,\n args=[current_index_internal, indexable_size],\n source_location=statement_loc,\n )\n else:\n continue_looping = assign_intrinsic_op(\n context,\n target=\"continue_looping\",\n op=AVMOp.gt,\n args=[_refresh_mutated_variable(context, reverse_index_internal), 0],\n source_location=statement_loc,\n )\n context.block_builder.terminate(\n ConditionalBranch(\n condition=continue_looping,\n non_zero=body,\n zero=next_block,\n source_location=statement_loc,\n )\n )\n\n context.block_builder.activate_block(body)\n if reverse_items or reverse_index:\n reverse_index_internal = assign_intrinsic_op(\n context,\n target=reverse_index_internal,\n op=AVMOp.sub,\n args=[_refresh_mutated_variable(context, reverse_index_internal), 1],\n source_location=None,\n )\n assigner.assign_user_loop_vars(\n get_value_at_index(\n reverse_index_internal if reverse_items else current_index_internal\n ),\n reverse_index_internal if reverse_index else current_index_internal,\n )\n with context.block_builder.enter_loop(on_continue=footer, on_break=next_block):\n loop_body.accept(context.visitor)\n context.block_builder.goto(footer)\n\n if context.block_builder.try_activate_block(footer):\n if not (reverse_items and reverse_index):\n assign_intrinsic_op(\n context,\n target=index_internal,\n op=AVMOp.add,\n args=[current_index_internal, 1],\n source_location=None,\n )\n context.block_builder.goto(header)\n\n context.block_builder.activate_block(next_block)\n\n\ndef _iterate_tuple(\n context: IRFunctionBuildContext,\n *,\n loop_body: awst_nodes.Block,\n assigner: LoopAssigner,\n tuple_expr: awst_nodes.Expression,\n statement_loc: SourceLocation,\n reverse_index: bool,\n reverse_items: bool,\n) -> None:\n tuple_values = context.visitor.visit_and_materialise(tuple_expr)\n assert isinstance(tuple_expr.wtype, wtypes.WTuple), \"tuple_expr wtype must be WTuple\"\n tuple_wtype = tuple_expr.wtype\n max_index = len(tuple_wtype.types) - 1\n loop_counter_name = context.next_tmp_name(\"loop_counter\")\n\n def assign_counter_and_user_vars(loop_count: int) -> Register:\n counter_reg = context.ssa.new_register(loop_counter_name, IRType.uint64, None)\n assign_targets(\n context,\n source=UInt64Constant(value=loop_count, source_location=None),\n targets=[counter_reg],\n assignment_location=None,\n )\n item_index = loop_count if not reverse_items else (max_index - loop_count)\n item_reg, index_reg = assigner.assign_user_loop_vars(\n get_tuple_item_values(\n tuple_values=tuple_values,\n tuple_wtype=tuple_wtype,\n index=item_index,\n target_wtype=tuple_wtype.types[item_index],\n source_location=statement_loc,\n ),\n UInt64Constant(\n value=loop_count if not reverse_index else (max_index - loop_count),\n source_location=None,\n ),\n )\n if index_reg and not reverse_index:\n return index_reg\n else:\n return counter_reg\n\n # construct basic blocks\n body = context.block_builder.mkblock(loop_body, \"for_body\")\n footer, next_block = context.block_builder.mkblocks(\n \"for_footer\", \"after_for\", source_location=statement_loc\n )\n headers = {\n idx: context.block_builder.mkblock(statement_loc, f\"for_header_{idx}\")\n for idx in range(1, len(tuple_wtype.types))\n }\n\n # first item - assigned in current block\n loop_counter = assign_counter_and_user_vars(0)\n\n # body\n context.block_builder.goto(body)\n with context.block_builder.activate_open_block(body):\n current_loop_counter = _refresh_mutated_variable(context, loop_counter)\n with context.block_builder.enter_loop(on_continue=footer, on_break=next_block):\n loop_body.accept(context.visitor)\n\n # footer + follow-up headers, iff the loop body doesn't exit unconditionally on first item\n context.block_builder.goto(footer)\n if context.block_builder.try_activate_block(footer):\n # footer\n context.block_builder.terminate(\n GotoNth(\n value=current_loop_counter,\n blocks=list(headers.values()),\n default=next_block,\n source_location=statement_loc,\n )\n )\n\n # headers for remaining items\n for idx, header in headers.items():\n context.block_builder.activate_block(header)\n assign_counter_and_user_vars(idx)\n context.block_builder.goto(body)\n\n context.block_builder.activate_block(next_block)\n\n\ndef _refresh_mutated_variable(context: IRFunctionBuildContext, reg: Register) -> Register:\n \"\"\"\n Given a register pointing to an underlying root operand (ie name) that is mutated,\n do an SSA read in the current block.\n\n This is *only* required when there is control flow involved in the generated IR,\n if it's only the builder that needs to loop then it should usually have an updated\n reference to the most recent assigned register which will still be valid because it's\n within the same block.\n \"\"\"\n return context.ssa.read_variable(reg.name, reg.ir_type, context.block_builder.active_block)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/builder\/iteration.py","language":"Python","license":"NOASSERTION","size":22778} {"code":"import typing\nfrom collections.abc import Mapping, Sequence\n\nimport attrs\n\nimport puya.awst.txn_fields\nfrom puya import log\nfrom puya.awst import (\n nodes as awst_nodes,\n wtypes,\n)\nfrom puya.awst.function_traverser import FunctionTraverser\nfrom puya.awst.to_code_visitor import ToCodeVisitor\nfrom puya.awst.wtypes import WInnerTransactionFields\nfrom puya.errors import CodeError, InternalError\nfrom puya.ir.avm_ops import AVMOp\nfrom puya.ir.builder._tuple_util import build_tuple_item_names\nfrom puya.ir.builder._utils import assign, assign_intrinsic_op\nfrom puya.ir.builder.blocks import BlocksBuilder\nfrom puya.ir.context import IRFunctionBuildContext\nfrom puya.ir.models import (\n ConditionalBranch,\n InnerTransactionField,\n Intrinsic,\n ITxnConstant,\n Register,\n UInt64Constant,\n Value,\n ValueProvider,\n ValueTuple,\n)\nfrom puya.ir.ssa import BraunSSA\nfrom puya.ir.types_ import IRType, wtype_to_ir_type\nfrom puya.ir.utils import format_tuple_index\nfrom puya.parse import SourceLocation\nfrom puya.utils import StableSet, positive_index\n\nlogger = log.get_logger(__name__)\n\n_INNER_TRANSACTION_NON_ARRAY_FIELDS = [f for f in puya.awst.txn_fields.TxnField if not f.is_array]\n\n\n@attrs.frozen(kw_only=True)\nclass CreateInnerTransactionFieldData:\n var_name: str\n field: puya.awst.txn_fields.TxnField\n field_counts: set[int] = attrs.field(factory=set)\n \"\"\"The observed number of values for this field\n For non-array fields this will be either 0 or 1\n For array fields this will be 0 -> N\n Capturing these ranges allows generating much simpler IR\n \"\"\"\n field_count_register_name: str\n\n @property\n def value_registers(self) -> dict[int, str]:\n return {idx: self.get_value_register_name(idx) for idx in range(max(self.field_counts))}\n\n def get_value_register_name(self, index: int) -> str:\n return f\"{self.var_name}%%param_{self.field.immediate}_idx_{index}\"\n\n\n@attrs.frozen(kw_only=True)\nclass CreateInnerTransactionData:\n var_name: str\n fields: dict[puya.awst.txn_fields.TxnField, CreateInnerTransactionFieldData] = attrs.field(\n factory=dict, init=False\n )\n\n def get_or_add_field_data(\n self, field: puya.awst.txn_fields.TxnField\n ) -> CreateInnerTransactionFieldData:\n try:\n field_data = self.fields[field]\n except KeyError:\n field_data = self.fields[field] = CreateInnerTransactionFieldData(\n var_name=self.var_name,\n field=field,\n field_count_register_name=f\"{self.var_name}%%{field.immediate}_length\",\n )\n return field_data\n\n\nclass InnerTransactionBuilder:\n def __init__(self, context: IRFunctionBuildContext):\n self.context = context\n self._inner_txn_fields_data = dict[str, CreateInnerTransactionData]()\n self._create_itxn_counter = iter(range(2**64 - 1))\n\n @property\n def ssa(self) -> BraunSSA:\n return self.context.block_builder.ssa\n\n @property\n def block_builder(self) -> BlocksBuilder:\n return self.context.block_builder\n\n def handle_inner_transaction_field_assignments(\n self, stmt: awst_nodes.AssignmentStatement\n ) -> bool:\n # awst_nodes.CreateInnerTransaction is used to create a set of fields used in an inner txn\n # When lowering this to IR field values and sizes are stored to local registers using\n # the top level variable name as a prefix.\n # For unused fields the size is 0\n # For array fields the size goes up to the length of the array\n # Other fields will have a size of 1\n #\n # Then itxn field sets are referenced the values are read using normal SSA functions\n # this allows for complex use cases such as branches and loops to still function\n\n value = stmt.value\n source_location = stmt.source_location\n target = stmt.target\n match value:\n case awst_nodes.CreateInnerTransaction(fields=fields):\n ((var_name, var_loc),) = _get_assignment_target_local_names(target, 1)\n self._set_inner_transaction_fields(var_name, fields, var_loc)\n return True\n case awst_nodes.Copy(\n value=awst_nodes.Expression(wtype=wtypes.WInnerTransactionFields()) as copy_source\n ):\n ((var_name, var_loc),) = _get_assignment_target_local_names(target, 1)\n src_var_name = self._resolve_inner_txn_params_var_name(copy_source)\n self._copy_inner_transaction_fields(var_name, src_var_name, var_loc)\n return True\n case awst_nodes.TupleExpression(items=tuple_items) as tuple_source if any(\n isinstance(t, WInnerTransactionFields) for t in tuple_source.wtype.types\n ):\n names = _get_assignment_target_local_names(target, len(tuple_items))\n for (item_name, item_loc), item_value in zip(names, tuple_items, strict=True):\n match item_value:\n case awst_nodes.CreateInnerTransaction(fields=fields):\n self._set_inner_transaction_fields(item_name, fields, item_loc)\n case awst_nodes.Copy(\n value=awst_nodes.Expression(\n wtype=wtypes.WInnerTransactionFields()\n ) as copy_source\n ):\n src_var_name = self._resolve_inner_txn_params_var_name(copy_source)\n self._copy_inner_transaction_fields(item_name, src_var_name, item_loc)\n case awst_nodes.Expression(wtype=wtypes.WInnerTransactionFields()):\n raise CodeError(\n \"Unexpected Inner Transaction encountered in tuple\", item_loc\n )\n case _:\n value_provider = self.context.visitor.visit_expr(item_value)\n assign(\n self.context,\n value_provider,\n name=item_name,\n register_location=item_loc,\n assignment_location=source_location,\n )\n return True\n case awst_nodes.Expression(wtype=wtypes.WInnerTransactionFields()):\n raise CodeError(\n \"Inner Transaction params can only be reassigned using copy()\",\n source_location,\n )\n case _:\n return False\n\n def _visit_submit_expr(self, expr: awst_nodes.Expression) -> Sequence[Value]:\n value_provider = self.context.visitor.visit_expr(expr)\n match value_provider:\n case ValueTuple(values=values):\n return values\n case Value() as value:\n return (value,)\n raise InternalError(\n \"Unexpected result for SubmitInnerTransaction expr\", expr.source_location\n )\n\n def add_inner_transaction_submit_result_assignments(\n self,\n targets: Sequence[Value],\n source_expr: awst_nodes.Expression,\n ass_loc: SourceLocation | None,\n ) -> None:\n \"\"\"Performs special handling for inner transaction related assignments\"\"\"\n # awst_nodes.SubmitInnerTransaction is used to submit itxn field sets as an inner\n # transaction group\n # Then all non aray fields are assigned to local registers and cached\n # This allows these fields to be read later even if additional itxn submissions have been\n # performed.\n # Array fields can not be cached in the same way currently, due to the lack of an\n # efficient array type.\n\n # targets are the assignment results, which will all be registers here,\n # the only case they aren't registers is when assigning to storage, which will\n # never be supported for itxn's because they're ephemeral\n itx_targets = [\n t for t in targets if isinstance(t, Register) and t.ir_type == IRType.itxn_group_idx\n ]\n source_actions = SourceActionExtractor.visit(source_expr)\n if len(itx_targets) != len(source_actions):\n raise CodeError(\"unsupported inner transaction assignment\", ass_loc)\n for itxn_target, source_action in zip(itx_targets, source_actions, strict=True):\n match source_action:\n case _CopySource(var_name=src_var_name):\n self._copy_submit_inner_transaction_fields(itxn_target.name, src_var_name)\n case _AssignSubmit(is_last=is_last):\n self._assign_submit_inner_transaction_fields(itxn_target, is_last=is_last)\n case unexpected:\n typing.assert_never(unexpected)\n\n def handle_update_inner_transaction(self, call: awst_nodes.UpdateInnerTransaction) -> None:\n var_name = self._resolve_inner_txn_params_var_name(call.itxn)\n self._set_inner_transaction_fields(\n var_name, call.fields, call.source_location, update=True\n )\n\n def handle_inner_transaction_field(\n self, itxn_field: awst_nodes.InnerTransactionField\n ) -> ValueProvider:\n src_loc = itxn_field.source_location\n field = itxn_field.field\n if field.is_array != bool(itxn_field.array_index):\n raise InternalError(\n \"inconsistent array_index for inner transaction field\",\n src_loc,\n )\n\n itxn = self.context.visitor.visit_expr(itxn_field.itxn)\n if not isinstance(itxn, Register | ITxnConstant):\n itxn_field_desc = {itxn_field.itxn.accept(ToCodeVisitor())}\n raise CodeError(\n f\"Could not resolve inner transaction group index for {itxn_field_desc}\",\n src_loc,\n )\n\n # use cached field if available\n if isinstance(itxn, Register):\n field_var_name = _get_txn_field_var_name(itxn.name, field.immediate)\n if self.ssa.has_version(field_var_name):\n return self.ssa.read_variable(\n field_var_name, wtype_to_ir_type(field.wtype), self.block_builder.active_block\n )\n\n match itxn:\n # use is_last register if it is defined\n case Register(name=itxn_name) if self.ssa.has_version(_get_txn_is_last(itxn_name)):\n is_last_in_group: Value = self.ssa.read_variable(\n _get_txn_is_last(itxn_name),\n IRType.bool,\n self.block_builder.active_block,\n )\n # otherwise infer based on itxn expr\n case _:\n is_last_in_group = UInt64Constant(\n value=int(_is_last_itxn(itxn_field.itxn)),\n ir_type=IRType.bool,\n source_location=src_loc,\n )\n\n return InnerTransactionField(\n group_index=itxn,\n is_last_in_group=is_last_in_group,\n array_index=(\n self.context.visitor.visit_and_materialise_single(itxn_field.array_index)\n if itxn_field.array_index\n else None\n ),\n field=field.immediate,\n type=wtype_to_ir_type(field.wtype),\n source_location=src_loc,\n )\n\n def handle_submit_inner_transaction(\n self, submit: awst_nodes.SubmitInnerTransaction\n ) -> Sequence[ITxnConstant]:\n src_loc = submit.source_location\n\n self.block_builder.add(\n Intrinsic(\n op=AVMOp.itxn_begin,\n source_location=src_loc,\n )\n )\n\n group_indexes = []\n for group_index, param in enumerate(submit.itxns):\n submit_var_loc = param.source_location\n if group_index > 0:\n self.block_builder.add(\n Intrinsic(\n op=AVMOp.itxn_next,\n source_location=submit_var_loc,\n )\n )\n param_var_name = self._resolve_inner_txn_params_var_name(param)\n next_txn = self.block_builder.mkblock(submit_var_loc, \"next_txn\")\n param_data = self._inner_txn_fields_data[param_var_name]\n\n # with the current implementation, reversing the order itxn_field is called\n # results in less stack manipulations as most values are naturally in the\n # required order when stack allocation occurs\n for field, field_data in reversed(param_data.fields.items()):\n field_value_counts = sorted(field_data.field_counts)\n if not field_value_counts or field_value_counts == [0]:\n # nothing to do\n continue\n\n min_num_values, *remaining_values = field_value_counts\n # values 0 -> min_num_values do not need to test\n # values min_num_values -> max_num_values need to check if they are set\n next_field = self.block_builder.mkblock(submit_var_loc, \"next_field\")\n self._set_field_values(field_data, 0, min_num_values)\n\n if remaining_values:\n last_num_values = min_num_values\n for next_num_values in remaining_values:\n set_fields_blk = self.block_builder.mkblock(\n submit_var_loc,\n f\"set_{field.immediate}_{last_num_values}_to_{next_num_values - 1}\",\n )\n self.block_builder.terminate(\n ConditionalBranch(\n condition=self._get_is_field_count_gte(\n field_data, next_num_values\n ),\n non_zero=set_fields_blk,\n zero=next_field,\n source_location=submit_var_loc,\n )\n )\n self.block_builder.activate_block(set_fields_blk)\n self._set_field_values(field_data, last_num_values, next_num_values)\n last_num_values = next_num_values\n\n self.block_builder.goto(next_field)\n self.block_builder.activate_block(next_field)\n\n group_indexes.append(\n ITxnConstant(\n value=group_index,\n source_location=submit_var_loc,\n ir_type=IRType.itxn_group_idx,\n )\n )\n\n self.block_builder.goto(next_txn)\n self.block_builder.activate_block(next_txn)\n\n self.block_builder.add(\n Intrinsic(\n op=AVMOp.itxn_submit,\n source_location=src_loc,\n )\n )\n\n return group_indexes\n\n def _assign_submit_inner_transaction_fields(\n self,\n target: Register,\n *,\n is_last: bool,\n ) -> None:\n var_name = target.name\n is_last_in_group = assign(\n self.context,\n source=UInt64Constant(\n value=int(is_last),\n ir_type=IRType.bool,\n source_location=None,\n ),\n name=_get_txn_is_last(var_name),\n register_location=None,\n assignment_location=None,\n )\n for field in _INNER_TRANSACTION_NON_ARRAY_FIELDS:\n field_reg = _get_txn_field_var_name(var_name, field.immediate)\n assign(\n context=self.context,\n source=InnerTransactionField(\n field=field.immediate,\n group_index=target,\n is_last_in_group=is_last_in_group,\n type=wtype_to_ir_type(field.wtype),\n array_index=None,\n source_location=None,\n ),\n name=field_reg,\n register_location=None,\n assignment_location=None,\n )\n\n def _copy_submit_inner_transaction_fields(self, dest_var_name: str, src_var_name: str) -> None:\n active_block = self.context.block_builder.active_block\n for field in _INNER_TRANSACTION_NON_ARRAY_FIELDS:\n src_field = _get_txn_field_var_name(src_var_name, field.immediate)\n dest_field = _get_txn_field_var_name(dest_var_name, field.immediate)\n assign(\n context=self.context,\n source=self.context.ssa.read_variable(\n src_field, wtype_to_ir_type(field.wtype), active_block\n ),\n name=dest_field,\n register_location=None,\n assignment_location=None,\n )\n\n def _set_field_values(\n self,\n field_data: CreateInnerTransactionFieldData,\n idx_from: int,\n idx_to: int,\n ) -> None:\n field = field_data.field\n field_ir_type = wtype_to_ir_type(field.wtype)\n for idx in range(idx_from, idx_to):\n field_value = self.ssa.read_variable(\n field_data.get_value_register_name(idx),\n field_ir_type,\n self.block_builder.active_block,\n )\n self.block_builder.add(\n Intrinsic(\n op=AVMOp.itxn_field,\n source_location=None,\n immediates=[field.immediate],\n args=[field_value],\n )\n )\n\n def _get_is_field_count_gte(\n self, field_data: CreateInnerTransactionFieldData, count: int\n ) -> Register:\n field = field_data.field\n len_register = self.ssa.read_variable(\n field_data.field_count_register_name,\n IRType.uint64,\n self.block_builder.active_block,\n )\n\n is_field_count_gte = assign_intrinsic_op(\n self.context,\n target=f\"is_{field.immediate}_count_gte_{count}\",\n op=AVMOp.gte,\n args=[len_register, count],\n source_location=None,\n )\n return is_field_count_gte\n\n def _set_inner_transaction_fields(\n self,\n var_name: str,\n inner_txn_fields: Mapping[puya.awst.txn_fields.TxnField, awst_nodes.Expression],\n var_loc: SourceLocation,\n *,\n update: bool = False,\n ) -> None:\n param_data = self._inner_txn_fields_data.setdefault(\n var_name, CreateInnerTransactionData(var_name=var_name)\n )\n # assign a unique constant to var_name, not used for anything directly, but prevents\n # an undefined variable warning\n assign(\n context=self.context,\n source=ITxnConstant(\n value=next(self._create_itxn_counter),\n source_location=var_loc,\n ir_type=IRType.itxn_field_set,\n ),\n name=var_name,\n assignment_location=var_loc,\n )\n fields = StableSet.from_iter(inner_txn_fields)\n if not update:\n # add missing fields to end\n for field in puya.awst.txn_fields.TxnField:\n if field.is_inner_param and field not in fields:\n fields.add(field)\n for field in fields:\n field_data = param_data.get_or_add_field_data(field)\n arg_expr = inner_txn_fields.get(field)\n values: Sequence[ValueProvider] = []\n count_loc = arg_expr.source_location if arg_expr else var_loc\n if arg_expr:\n match self.context.visitor.visit_expr(arg_expr):\n case ValueTuple(values=values):\n pass\n case ValueProvider() as vp:\n values = [vp]\n\n field_data.field_counts.add(len(values))\n for idx, value in enumerate(values):\n assign(\n context=self.context,\n source=value,\n name=field_data.get_value_register_name(idx),\n register_location=var_loc,\n assignment_location=value.source_location,\n )\n assign(\n context=self.context,\n source=UInt64Constant(\n value=len(values),\n source_location=count_loc,\n ),\n name=field_data.field_count_register_name,\n register_location=var_loc,\n assignment_location=count_loc,\n )\n\n def _copy_inner_transaction_fields(\n self, dest_var_name: str, src_var_name: str, var_loc: SourceLocation\n ) -> None:\n src_params_data = self._inner_txn_fields_data[src_var_name]\n dest_params_data = self._inner_txn_fields_data.setdefault(\n dest_var_name, CreateInnerTransactionData(var_name=dest_var_name)\n )\n for field in puya.awst.txn_fields.TxnField:\n if not field.is_inner_param:\n continue\n src_field_data = src_params_data.get_or_add_field_data(field)\n\n dest_field_data = dest_params_data.get_or_add_field_data(field)\n dest_field_data.field_counts.update(src_field_data.field_counts)\n for idx, src_field_register in src_field_data.value_registers.items():\n dest_field_register = dest_field_data.get_value_register_name(idx)\n assign(\n context=self.context,\n source=self.ssa.read_variable(\n src_field_register,\n wtype_to_ir_type(field.wtype),\n self.block_builder.active_block,\n ),\n name=dest_field_register,\n assignment_location=var_loc,\n )\n assign(\n context=self.context,\n source=self.ssa.read_variable(\n src_field_data.field_count_register_name,\n IRType.uint64,\n self.block_builder.active_block,\n ),\n name=dest_field_data.field_count_register_name,\n assignment_location=var_loc,\n )\n\n def _resolve_inner_txn_params_var_name(self, params: awst_nodes.Expression) -> str:\n match params:\n case awst_nodes.CreateInnerTransaction() as itxn:\n var_name = self.context.next_tmp_name(description=\"inner_txn_params\")\n self._set_inner_transaction_fields(\n var_name=var_name, inner_txn_fields=itxn.fields, var_loc=itxn.source_location\n )\n case awst_nodes.VarExpression(name=var_name):\n pass\n case awst_nodes.TupleItemExpression(\n base=awst_nodes.VarExpression(name=name, wtype=wtypes.WTuple() as base_wtype),\n index=index,\n ):\n return format_tuple_index(base_wtype, name, index)\n case awst_nodes.Copy(value=value):\n return self._resolve_inner_txn_params_var_name(value)\n case _:\n raise InternalError(\n \"Could not resolve var_name for inner transaction params\",\n params.source_location,\n )\n return var_name\n\n\ndef _get_assignment_target_local_names(\n target: awst_nodes.Expression, expected_number: int\n) -> Sequence[tuple[str, SourceLocation]]:\n match target:\n case awst_nodes.VarExpression(name=var_name) if expected_number == 1:\n return [(var_name, target.source_location)]\n case awst_nodes.VarExpression(name=var_name, wtype=wtypes.WTuple() as var_wtype):\n return [\n (format_tuple_index(var_wtype, var_name, idx), target.source_location)\n for idx in range(expected_number)\n ]\n case awst_nodes.TupleExpression(items=items) if expected_number == len(items) and all(\n isinstance(i, awst_nodes.VarExpression) for i in items\n ):\n items = typing.cast(Sequence[awst_nodes.VarExpression], items)\n return [(expr.name, expr.source_location) for expr in items]\n case awst_nodes.TupleItemExpression(\n base=awst_nodes.TupleExpression(wtype=tuple_wtype) as base, index=index\n ):\n tuple_names = _get_assignment_target_local_names(base, len(tuple_wtype.types))\n return [tuple_names[index]]\n case awst_nodes.FieldExpression(\n base=awst_nodes.TupleExpression(wtype=tuple_wtype) as base,\n name=name,\n source_location=name_loc,\n ):\n tuple_names = _get_assignment_target_local_names(base, len(tuple_wtype.types))\n index = tuple_wtype.name_to_index(name, name_loc)\n return [tuple_names[index]]\n raise CodeError(\n \"Inner Transactions can only be assigned to local variables\",\n target.source_location,\n )\n\n\n@attrs.frozen\nclass _CopySource:\n var_name: str\n\n\n@attrs.frozen\nclass _AssignSubmit:\n index: int\n is_last: bool\n\n\n_SourceAction = _CopySource | _AssignSubmit\n\n\nclass SourceActionExtractor(FunctionTraverser):\n def __init__(self) -> None:\n self._actions = list[_SourceAction]()\n\n @classmethod\n def visit(cls, node: awst_nodes.Expression) -> list[_SourceAction]:\n visitor = cls()\n node.accept(visitor)\n return visitor._actions # noqa: SLF001\n\n def visit_submit_inner_transaction(self, call: awst_nodes.SubmitInnerTransaction) -> None:\n itxns = len(call.itxns)\n self._actions.extend(\n _AssignSubmit(index=idx, is_last=idx == itxns - 1) for idx in range(itxns)\n )\n\n def visit_var_expression(self, expr: awst_nodes.VarExpression) -> None:\n self._actions.extend(\n [\n _CopySource(var_name=name)\n for name, ir_type in build_tuple_item_names(\n expr.name, expr.wtype, expr.source_location\n )\n if ir_type == IRType.itxn_group_idx\n ]\n )\n\n def visit_inner_transaction_field(self, itxn_field: awst_nodes.InnerTransactionField) -> None:\n # this will consume any referenced inner transaction, so don't need to traverse it\n pass\n\n def visit_tuple_item_expression(self, expr: awst_nodes.TupleItemExpression) -> None:\n start_len = len(self._actions)\n super().visit_tuple_item_expression(expr)\n added = self._actions[start_len:]\n # only keep the relevant action\n if isinstance(expr.wtype, wtypes.WInnerTransaction):\n self._actions[start_len:] = [added[expr.index]]\n\n def visit_slice_expression(self, expr: awst_nodes.SliceExpression) -> None:\n start_len = len(self._actions)\n super().visit_slice_expression(expr)\n added = self._actions[start_len:]\n if not added or not isinstance(expr.base.wtype, wtypes.WTuple):\n return\n # determine constant indexes\n tuple_size = len(added)\n begin_index = 0 if expr.begin_index is None else _get_uint64_const(expr.begin_index)\n if begin_index is None:\n return\n begin_index = positive_index(begin_index, added)\n end_index = tuple_size if expr.end_index is None else _get_uint64_const(expr.end_index)\n if end_index is None:\n return\n end_index = positive_index(end_index, added)\n\n # include relevant items from sliced tuple\n self._actions[start_len:] = [\n added[idx]\n for idx in range(begin_index, end_index)\n if isinstance(expr.base.wtype.types[idx], wtypes.WInnerTransaction)\n ]\n\n\ndef _get_uint64_const(expr: awst_nodes.Expression) -> int | None:\n if isinstance(expr, awst_nodes.IntegerConstant) and expr.wtype == wtypes.uint64_wtype:\n return expr.value\n return None\n\n\ndef _is_last_itxn(expr: awst_nodes.Expression) -> bool:\n # is last itxn if expr is a submit expr of size 1 OR\n if not isinstance(expr, awst_nodes.TupleItemExpression | awst_nodes.FieldExpression):\n return _is_submit_expr_of_size(expr, 1)\n\n # if expr is a tuple item expression with an index into the last item of a submit expr\n base = expr.base\n if not isinstance(base.wtype, wtypes.WTuple):\n return False\n\n index = (\n expr.index\n if isinstance(expr, awst_nodes.TupleItemExpression)\n else base.wtype.name_to_index(expr.name, expr.source_location)\n )\n tuple_size = len(base.wtype.types)\n if index == -1 or (index + 1) == tuple_size:\n return _is_submit_expr_of_size(base, tuple_size)\n else:\n return False\n\n\ndef _is_submit_expr_of_size(expr: awst_nodes.Expression, expected_group_size: int) -> bool:\n match expr:\n case awst_nodes.SubmitInnerTransaction(itxns=itxns) if len(itxns) == expected_group_size:\n return True\n case awst_nodes.SingleEvaluation(source=source):\n return _is_submit_expr_of_size(source, expected_group_size)\n case _:\n return False\n\n\ndef _get_txn_field_var_name(var_name: str, field: str) -> str:\n return f\"{var_name}.{field}\"\n\n\ndef _get_txn_is_last(var_name: str) -> str:\n return f\"{var_name}._is_last\"\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/builder\/itxn.py","language":"Python","license":"NOASSERTION","size":29467} {"code":"import typing\nfrom collections.abc import Iterator, Sequence\n\nimport attrs\n\nimport puya.awst.visitors\nimport puya.ir.builder.storage\nfrom puya import algo_constants, log, utils\nfrom puya.avm import AVMType\nfrom puya.awst import (\n nodes as awst_nodes,\n wtypes,\n)\nfrom puya.awst.nodes import BigUIntBinaryOperator, UInt64BinaryOperator\nfrom puya.awst.to_code_visitor import ToCodeVisitor\nfrom puya.awst.txn_fields import TxnField\nfrom puya.awst.wtypes import WInnerTransaction, WInnerTransactionFields\nfrom puya.errors import CodeError, InternalError\nfrom puya.ir.avm_ops import AVMOp\nfrom puya.ir.builder import arc4, flow_control, storage\nfrom puya.ir.builder._tuple_util import get_tuple_item_values\nfrom puya.ir.builder._utils import (\n OpFactory,\n assert_value,\n assign,\n assign_intrinsic_op,\n assign_targets,\n assign_temp,\n extract_const_int,\n get_implicit_return_is_original,\n get_implicit_return_out,\n mktemp,\n)\nfrom puya.ir.builder.arc4 import ARC4_FALSE, ARC4_TRUE\nfrom puya.ir.builder.assignment import (\n handle_assignment,\n handle_assignment_expr,\n)\nfrom puya.ir.builder.bytes import (\n visit_bytes_intersection_slice_expression,\n visit_bytes_slice_expression,\n)\nfrom puya.ir.builder.callsub import (\n visit_puya_lib_call_expression,\n visit_subroutine_call_expression,\n)\nfrom puya.ir.builder.iteration import handle_for_in_loop\nfrom puya.ir.builder.itxn import InnerTransactionBuilder\nfrom puya.ir.context import IRBuildContext\nfrom puya.ir.models import (\n AddressConstant,\n BigUIntConstant,\n BytesConstant,\n CompiledContractReference,\n CompiledLogicSigReference,\n Fail,\n Intrinsic,\n InvokeSubroutine,\n MethodConstant,\n Op,\n ProgramExit,\n Subroutine,\n SubroutineReturn,\n TemplateVar,\n UInt64Constant,\n Value,\n ValueProvider,\n ValueTuple,\n)\nfrom puya.ir.types_ import (\n AVMBytesEncoding,\n IRType,\n bytes_enc_to_avm_bytes_enc,\n wtype_to_ir_type,\n wtype_to_ir_types,\n)\nfrom puya.ir.utils import format_tuple_index\nfrom puya.parse import SourceLocation\n\nTExpression: typing.TypeAlias = ValueProvider | None\nTStatement: typing.TypeAlias = None\n\nlogger = log.get_logger(__name__)\n\n\nclass FunctionIRBuilder(\n puya.awst.visitors.ExpressionVisitor[TExpression],\n puya.awst.visitors.StatementVisitor[TStatement],\n):\n def __init__(\n self, context: IRBuildContext, function: awst_nodes.Function, subroutine: Subroutine\n ):\n self.context = context.for_function(function, subroutine, self)\n self._itxn = InnerTransactionBuilder(self.context)\n self._single_eval_cache = dict[awst_nodes.SingleEvaluation, TExpression]()\n self._visited_exprs = dict[tuple[int, awst_nodes.Expression], TExpression]()\n\n @classmethod\n def build_body(\n cls,\n ctx: IRBuildContext,\n function: awst_nodes.Function,\n subroutine: Subroutine,\n ) -> None:\n logger.debug(f\"Building IR for function {function.full_name}\")\n builder = cls(ctx, function, subroutine)\n func_ctx = builder.context\n with func_ctx.log_exceptions():\n block_builder = func_ctx.block_builder\n for p in subroutine.parameters:\n if p.implicit_return:\n assign(\n func_ctx,\n UInt64Constant(value=1, ir_type=IRType.bool, source_location=None),\n name=get_implicit_return_is_original(p.name),\n assignment_location=None,\n )\n assign(\n func_ctx,\n p,\n name=get_implicit_return_out(p.name),\n assignment_location=None,\n )\n function.body.accept(builder)\n final_block = block_builder.active_block\n if not final_block.terminated:\n if function.return_type != wtypes.void_wtype:\n raise CodeError(\"not all paths return a value\", function.body.source_location)\n block_builder.terminate(\n SubroutineReturn(\n result=[\n block_builder.ssa.read_variable(\n get_implicit_return_out(p.name), p.ir_type, final_block\n )\n for p in subroutine.parameters\n if p.implicit_return\n ],\n source_location=None,\n )\n )\n subroutine.body = block_builder.finalise()\n subroutine.validate_with_ssa()\n\n def visit_copy(self, expr: awst_nodes.Copy) -> TExpression:\n # For reference types, we need to clone the data\n # For value types, we can just visit the expression and the resulting read\n # will effectively be a copy. We assign the copy to a new register in case it is\n # mutated.\n match expr.value.wtype:\n case wtypes.ARC4Type(immutable=False):\n # Arc4 encoded types are value types\n original_value = self.visit_and_materialise_single(expr.value)\n return assign_temp(\n temp_description=\"copy\",\n source=original_value,\n source_location=expr.source_location,\n context=self.context,\n )\n raise InternalError(\n f\"Invalid source wtype for Copy {expr.value.wtype}\", expr.source_location\n )\n\n def visit_arc4_decode(self, expr: awst_nodes.ARC4Decode) -> TExpression:\n return arc4.decode_expr(self.context, expr)\n\n def visit_arc4_encode(self, expr: awst_nodes.ARC4Encode) -> TExpression:\n return arc4.encode_expr(self.context, expr)\n\n def visit_compiled_contract(self, expr: awst_nodes.CompiledContract) -> TExpression:\n prefix = self.context.options.template_vars_prefix if expr.prefix is None else expr.prefix\n template_variables = {\n prefix + k: self.visit_and_materialise_single(v)\n for k, v in expr.template_variables.items()\n }\n # TODO: remove implicit coupling\n # the coupling here is between the order of values in the ValueTuple\n # and the structure of the high level python type\n # once we support nested tuples, this coupling can be removed\n # and instead support names on WTuple, then each value can be accessed and lowered\n # via a FieldExpression\n program_pages = [\n CompiledContractReference(\n artifact=expr.contract,\n field=field,\n program_page=page,\n ir_type=IRType.bytes,\n source_location=expr.source_location,\n template_variables=template_variables,\n )\n for field in (\n TxnField.ApprovalProgramPages,\n TxnField.ClearStateProgramPages,\n )\n for page in (0, 1)\n ]\n return ValueTuple(\n values=program_pages\n + [\n (\n self.visit_and_materialise_single(expr.allocation_overrides[field])\n if field in expr.allocation_overrides\n else CompiledContractReference(\n artifact=expr.contract,\n field=field,\n ir_type=IRType.uint64,\n source_location=expr.source_location,\n template_variables=template_variables,\n )\n )\n for field in (\n TxnField.ExtraProgramPages,\n TxnField.GlobalNumUint,\n TxnField.GlobalNumByteSlice,\n TxnField.LocalNumUint,\n TxnField.LocalNumByteSlice,\n )\n ],\n source_location=expr.source_location,\n )\n\n def visit_compiled_logicsig(self, expr: awst_nodes.CompiledLogicSig) -> TExpression:\n prefix = self.context.options.template_vars_prefix if expr.prefix is None else expr.prefix\n template_variables = {\n prefix + k: self.visit_and_materialise_single(v)\n for k, v in expr.template_variables.items()\n }\n return ValueTuple(\n values=[\n CompiledLogicSigReference(\n artifact=expr.logic_sig,\n ir_type=IRType.bytes,\n source_location=expr.source_location,\n template_variables=template_variables,\n )\n ],\n source_location=expr.source_location,\n )\n\n def visit_assignment_statement(self, stmt: awst_nodes.AssignmentStatement) -> TStatement:\n if not self._itxn.handle_inner_transaction_field_assignments(stmt):\n targets = handle_assignment_expr(\n self.context,\n target=stmt.target,\n value=stmt.value,\n assignment_location=stmt.source_location,\n )\n self._itxn.add_inner_transaction_submit_result_assignments(\n targets, stmt.value, stmt.source_location\n )\n return None\n\n def visit_assignment_expression(self, expr: awst_nodes.AssignmentExpression) -> TExpression:\n result = handle_assignment_expr(\n self.context,\n target=expr.target,\n value=expr.value,\n assignment_location=expr.source_location,\n )\n if not result:\n # HOW DID YOU GET HERE\n raise CodeError(\"Assignment expression did not return a result\", expr.source_location)\n if len(result) == 1:\n return result[0]\n else:\n return ValueTuple(expr.source_location, list(result))\n\n def visit_biguint_postfix_unary_operation(\n self, expr: awst_nodes.BigUIntPostfixUnaryOperation\n ) -> TExpression:\n target_value = self.visit_and_materialise_single(expr.target)\n rhs = BigUIntConstant(value=1, source_location=expr.source_location)\n match expr.op:\n case awst_nodes.BigUIntPostfixUnaryOperator.increment:\n binary_op = awst_nodes.BigUIntBinaryOperator.add\n case awst_nodes.BigUIntPostfixUnaryOperator.decrement:\n binary_op = awst_nodes.BigUIntBinaryOperator.sub\n case never:\n typing.assert_never(never)\n\n new_value = create_biguint_binary_op(binary_op, target_value, rhs, expr.source_location)\n\n handle_assignment(\n self.context,\n target=expr.target,\n value=new_value,\n is_nested_update=False,\n assignment_location=expr.source_location,\n )\n return target_value\n\n def visit_uint64_postfix_unary_operation(\n self, expr: awst_nodes.UInt64PostfixUnaryOperation\n ) -> TExpression:\n target_value = self.visit_and_materialise_single(expr.target)\n rhs = UInt64Constant(value=1, source_location=expr.source_location)\n match expr.op:\n case awst_nodes.UInt64PostfixUnaryOperator.increment:\n binary_op = awst_nodes.UInt64BinaryOperator.add\n case awst_nodes.UInt64PostfixUnaryOperator.decrement:\n binary_op = awst_nodes.UInt64BinaryOperator.sub\n case never:\n typing.assert_never(never)\n\n new_value = create_uint64_binary_op(binary_op, target_value, rhs, expr.source_location)\n\n handle_assignment(\n self.context,\n target=expr.target,\n value=new_value,\n is_nested_update=False,\n assignment_location=expr.source_location,\n )\n return target_value\n\n def visit_uint64_binary_operation(self, expr: awst_nodes.UInt64BinaryOperation) -> TExpression:\n left = self.visit_and_materialise_single(expr.left)\n right = self.visit_and_materialise_single(expr.right)\n return create_uint64_binary_op(expr.op, left, right, expr.source_location)\n\n def visit_biguint_binary_operation(\n self, expr: awst_nodes.BigUIntBinaryOperation\n ) -> TExpression:\n left = self.visit_and_materialise_single(expr.left)\n right = self.visit_and_materialise_single(expr.right)\n return create_biguint_binary_op(expr.op, left, right, expr.source_location)\n\n def visit_uint64_unary_operation(self, expr: awst_nodes.UInt64UnaryOperation) -> TExpression:\n return Intrinsic(\n op=AVMOp(expr.op),\n args=[self.visit_and_materialise_single(expr.expr)],\n source_location=expr.source_location,\n )\n\n def visit_bytes_unary_operation(self, expr: awst_nodes.BytesUnaryOperation) -> TExpression:\n return Intrinsic(\n op=AVMOp(f\"b{expr.op}\"),\n args=[self.visit_and_materialise_single(expr.expr)],\n source_location=expr.source_location,\n )\n\n def visit_integer_constant(self, expr: awst_nodes.IntegerConstant) -> TExpression:\n match expr.wtype:\n case wtypes.uint64_wtype:\n if expr.value < 0 or expr.value.bit_length() > 64:\n raise CodeError(f\"invalid {expr.wtype} value\", expr.source_location)\n\n return UInt64Constant(\n value=expr.value,\n source_location=expr.source_location,\n teal_alias=expr.teal_alias,\n )\n case wtypes.biguint_wtype:\n if expr.value < 0 or expr.value.bit_length() > algo_constants.MAX_BIGUINT_BITS:\n raise CodeError(f\"invalid {expr.wtype} value\", expr.source_location)\n\n return BigUIntConstant(value=expr.value, source_location=expr.source_location)\n case wtypes.ARC4UIntN(n=bit_size):\n num_bytes = bit_size \/\/ 8\n try:\n arc4_result = expr.value.to_bytes(num_bytes, \"big\", signed=False)\n except OverflowError:\n raise CodeError(f\"invalid {expr.wtype} value\", expr.source_location) from None\n return BytesConstant(\n value=arc4_result,\n encoding=AVMBytesEncoding.base16,\n source_location=expr.source_location,\n )\n case _:\n raise InternalError(\n f\"Unhandled wtype {expr.wtype} for integer constant {expr.value}\",\n expr.source_location,\n )\n\n def visit_decimal_constant(self, expr: awst_nodes.DecimalConstant) -> TExpression:\n match expr.wtype:\n case wtypes.ARC4UFixedNxM(n=bit_size, m=precision):\n num_bytes = bit_size \/\/ 8\n sign, digits, exponent = expr.value.as_tuple()\n adjusted_int = int(\"\".join(map(str, digits)))\n if (\n sign != 0 # negative\n or not isinstance(exponent, int) # infinite\n or -exponent > precision # too precise\n or adjusted_int.bit_length() > bit_size # too big\n ):\n raise CodeError(f\"invalid {expr.wtype} value\", expr.source_location)\n return BytesConstant(\n source_location=expr.source_location,\n encoding=AVMBytesEncoding.base16,\n value=adjusted_int.to_bytes(num_bytes, \"big\", signed=False),\n )\n case _:\n raise InternalError(\n f\"Unhandled wtype {expr.wtype} for decimal constant {expr.value}\",\n expr.source_location,\n )\n\n def visit_bool_constant(self, expr: awst_nodes.BoolConstant) -> TExpression:\n match expr.wtype:\n case wtypes.bool_wtype:\n return UInt64Constant(\n value=int(expr.value),\n ir_type=IRType.bool,\n source_location=expr.source_location,\n )\n case wtypes.arc4_bool_wtype:\n return BytesConstant(\n value=(ARC4_TRUE if expr.value else ARC4_FALSE),\n encoding=AVMBytesEncoding.base16,\n ir_type=IRType.bytes,\n source_location=expr.source_location,\n )\n case _:\n raise InternalError(\n f\"Unexpected wtype {expr.wtype} for BoolConstant\", expr.source_location\n )\n\n def visit_bytes_constant(self, expr: awst_nodes.BytesConstant) -> BytesConstant:\n if len(expr.value) > algo_constants.MAX_BYTES_LENGTH:\n raise CodeError(f\"invalid {expr.wtype} value\", expr.source_location)\n return BytesConstant(\n value=expr.value,\n encoding=bytes_enc_to_avm_bytes_enc(expr.encoding),\n ir_type=wtype_to_ir_type(expr),\n source_location=expr.source_location,\n )\n\n def visit_string_constant(self, expr: awst_nodes.StringConstant) -> BytesConstant:\n try:\n value = expr.value.encode(\"utf8\")\n except UnicodeError:\n value = None\n if value is None:\n raise CodeError(f\"invalid {expr.wtype} value\", expr.source_location)\n\n match expr.wtype:\n case wtypes.string_wtype:\n encoding = AVMBytesEncoding.utf8\n case wtypes.arc4_string_alias:\n encoding = AVMBytesEncoding.base16\n value = len(value).to_bytes(2) + value\n case _:\n raise InternalError(\n f\"Unexpected wtype {expr.wtype} for StringConstant\", expr.source_location\n )\n\n if len(value) > algo_constants.MAX_BYTES_LENGTH:\n raise CodeError(f\"invalid {expr.wtype} value\", expr.source_location)\n\n return BytesConstant(\n value=value,\n encoding=encoding,\n source_location=expr.source_location,\n )\n\n @typing.override\n def visit_void_constant(self, expr: awst_nodes.VoidConstant) -> TExpression:\n return None\n\n def visit_address_constant(self, expr: awst_nodes.AddressConstant) -> TExpression:\n if not utils.valid_address(expr.value):\n # TODO: should this be here, or on IR model? there's pros and cons to each\n raise CodeError(\"invalid Algorand address\", expr.source_location)\n return AddressConstant(\n value=expr.value,\n source_location=expr.source_location,\n )\n\n def visit_numeric_comparison_expression(\n self, expr: awst_nodes.NumericComparisonExpression\n ) -> TExpression:\n left = self.visit_and_materialise_single(expr.lhs)\n right = self.visit_and_materialise_single(expr.rhs)\n if left.atype != right.atype:\n raise InternalError(\n \"Numeric comparison between different numeric types\", expr.source_location\n )\n op_code = expr.operator.value\n if left.atype == AVMType.bytes:\n op_code = \"b\" + op_code\n\n try:\n avm_op = AVMOp(op_code)\n except ValueError as ex:\n raise InternalError(\n f\"Unmapped numeric comparison operator {expr.operator}\", expr.source_location\n ) from ex\n\n return Intrinsic(\n op=avm_op,\n args=[left, right],\n source_location=expr.source_location,\n )\n\n def visit_checked_maybe(self, expr: awst_nodes.CheckedMaybe) -> TExpression:\n value, check = self.visit_and_materialise(expr.expr, (\"value\", \"check\"))\n assert_value(\n self.context,\n check,\n comment=expr.comment,\n source_location=expr.source_location,\n )\n return value\n\n def _expand_tuple_var(self, name: str, wtype: wtypes.WTuple) -> Iterator[Value]:\n for idx, wt in enumerate(wtype.types):\n item_name = format_tuple_index(wtype, name, idx)\n if isinstance(wt, wtypes.WTuple):\n yield from self._expand_tuple_var(item_name, wt)\n else:\n yield self.context.ssa.read_variable(\n variable=item_name,\n ir_type=wtype_to_ir_type(wt),\n block=self.context.block_builder.active_block,\n )\n\n def visit_var_expression(self, expr: awst_nodes.VarExpression) -> TExpression:\n if isinstance(expr.wtype, wtypes.WTuple):\n values = tuple(self._expand_tuple_var(expr.name, expr.wtype))\n return ValueTuple(values=values, source_location=expr.source_location)\n ir_type = wtype_to_ir_type(expr)\n variable = self.context.ssa.read_variable(\n expr.name, ir_type, self.context.block_builder.active_block\n )\n variable = attrs.evolve(variable, source_location=expr.source_location)\n return variable\n\n def _add_assert(\n self,\n condition_expr: awst_nodes.Expression | None,\n error_message: str | None,\n loc: SourceLocation,\n ) -> Intrinsic | None:\n condition_value = (\n self.visit_and_materialise_single(condition_expr) if condition_expr else None\n )\n if isinstance(condition_value, UInt64Constant):\n if condition_value.value:\n logger.warning(\"assertion is always true, ignoring\", location=loc)\n return None\n else:\n condition_value = None\n if condition_value is None:\n self.context.block_builder.terminate(\n Fail(source_location=loc, error_message=error_message)\n )\n return None\n else:\n return Intrinsic(\n op=AVMOp(\"assert\"),\n source_location=loc,\n args=[condition_value],\n error_message=error_message,\n )\n\n def visit_intrinsic_call(self, call: awst_nodes.IntrinsicCall) -> TExpression:\n match call.op_code:\n case \"err\":\n return self._add_assert(\n condition_expr=None, error_message=None, loc=call.source_location\n )\n case \"return\":\n assert not call.immediates, f\"return intrinsic had immediates: {call.immediates}\"\n (arg_expr,) = call.stack_args\n exit_value = self.visit_and_materialise_single(arg_expr)\n self.context.block_builder.terminate(\n ProgramExit(source_location=call.source_location, result=exit_value)\n )\n return None\n case \"assert\":\n (condition_expr,) = call.stack_args\n return self._add_assert(\n condition_expr=condition_expr, error_message=None, loc=call.source_location\n )\n case _:\n args = [self.visit_and_materialise_single(arg) for arg in call.stack_args]\n return Intrinsic(\n op=AVMOp(call.op_code),\n source_location=call.source_location,\n args=args,\n immediates=list(call.immediates),\n types=wtype_to_ir_types(call.wtype),\n )\n\n def visit_group_transaction_reference(\n self, ref: awst_nodes.GroupTransactionReference\n ) -> TExpression:\n index = self.visit_and_materialise_single(ref.index, \"gtxn_idx\")\n if (txn_type := ref.wtype.transaction_type) is not None:\n actual_type = assign_intrinsic_op(\n self.context,\n target=\"gtxn_type\",\n op=AVMOp.gtxns,\n immediates=[\"TypeEnum\"],\n args=[index],\n source_location=ref.source_location,\n )\n type_constant = UInt64Constant(\n value=txn_type.value, teal_alias=txn_type.name, source_location=ref.source_location\n )\n type_matches = assign_intrinsic_op(\n self.context,\n target=\"gtxn_type_matches\",\n op=AVMOp.eq,\n args=[actual_type, type_constant],\n source_location=ref.source_location,\n )\n assert_value(\n self.context,\n type_matches,\n comment=f\"transaction type is {txn_type.name}\",\n source_location=ref.source_location,\n )\n return index\n\n def visit_create_inner_transaction(self, call: awst_nodes.CreateInnerTransaction) -> None:\n # for semantic compatibility, this is an error, since we don't evaluate the args\n # here (there would be no point, if we hit this node on its own and not as part\n # of a submit or an assigment, it does nothing)\n logger.error(\n \"statement has no effect, did you forget to submit?\", location=call.source_location\n )\n\n def visit_submit_inner_transaction(\n self, submit: awst_nodes.SubmitInnerTransaction\n ) -> TExpression:\n result = self._itxn.handle_submit_inner_transaction(submit)\n if len(result) == 1:\n return result[0]\n return ValueTuple(\n values=list(result),\n source_location=submit.source_location,\n )\n\n def visit_update_inner_transaction(self, call: awst_nodes.UpdateInnerTransaction) -> None:\n self._itxn.handle_update_inner_transaction(call)\n\n def visit_inner_transaction_field(\n self, itxn_field: awst_nodes.InnerTransactionField\n ) -> TExpression:\n return self._itxn.handle_inner_transaction_field(itxn_field)\n\n def visit_method_constant(self, expr: awst_nodes.MethodConstant) -> TExpression:\n return MethodConstant(value=expr.value, source_location=expr.source_location)\n\n def visit_tuple_expression(self, expr: awst_nodes.TupleExpression) -> TExpression:\n items = list[Value]()\n for item in expr.items:\n nested_values = self.visit_and_materialise(item)\n items.extend(nested_values)\n return ValueTuple(\n source_location=expr.source_location,\n values=items,\n )\n\n def visit_tuple_item_expression(self, expr: awst_nodes.TupleItemExpression) -> TExpression:\n if isinstance(expr.base.wtype, wtypes.WTuple):\n tup = self.visit_and_materialise(expr.base)\n return get_tuple_item_values(\n tuple_values=tup,\n tuple_wtype=expr.base.wtype,\n index=expr.index,\n target_wtype=expr.wtype,\n source_location=expr.source_location,\n )\n elif isinstance(expr.base.wtype, wtypes.ARC4Tuple):\n base = self.visit_and_materialise_single(expr.base)\n return arc4.arc4_tuple_index(\n self.context,\n base=base,\n index=expr.index,\n wtype=expr.base.wtype,\n source_location=expr.source_location,\n )\n else:\n raise InternalError(\n f\"Tuple indexing operation IR lowering\"\n f\" not implemented for base type {expr.base.wtype.name}\",\n expr.source_location,\n )\n\n def visit_field_expression(self, expr: awst_nodes.FieldExpression) -> TExpression:\n if isinstance(expr.base.wtype, wtypes.WStructType):\n raise NotImplementedError\n if isinstance(expr.base.wtype, wtypes.WTuple):\n index = expr.base.wtype.name_to_index(expr.name, expr.source_location)\n tup = self.visit_and_materialise(expr.base)\n return get_tuple_item_values(\n tuple_values=tup,\n tuple_wtype=expr.base.wtype,\n index=index,\n target_wtype=expr.wtype,\n source_location=expr.source_location,\n )\n if isinstance(expr.base.wtype, wtypes.ARC4Struct):\n base = self.visit_and_materialise_single(expr.base)\n index = expr.base.wtype.names.index(expr.name)\n return arc4.arc4_tuple_index(\n self.context,\n base=base,\n index=index,\n wtype=expr.base.wtype,\n source_location=expr.source_location,\n )\n else:\n raise InternalError(\n f\"Field access IR lowering\"\n f\" not implemented for base type {expr.base.wtype.name}\",\n expr.source_location,\n )\n\n def visit_intersection_slice_expression(\n self, expr: awst_nodes.IntersectionSliceExpression\n ) -> TExpression:\n if isinstance(expr.base.wtype, wtypes.WTuple):\n return self._visit_tuple_slice(expr, expr.base.wtype)\n elif expr.base.wtype == wtypes.bytes_wtype:\n return visit_bytes_intersection_slice_expression(self.context, expr)\n else:\n raise InternalError(\n f\"IntersectionSlice operation IR lowering not implemented for {expr.wtype.name}\",\n expr.source_location,\n )\n\n def visit_slice_expression(self, expr: awst_nodes.SliceExpression) -> TExpression:\n \"\"\"Slices an enumerable type.\"\"\"\n if isinstance(expr.base.wtype, wtypes.WTuple):\n return self._visit_tuple_slice(expr, expr.base.wtype)\n elif expr.base.wtype == wtypes.bytes_wtype:\n return visit_bytes_slice_expression(self.context, expr)\n else:\n raise InternalError(\n f\"Slice operation IR lowering not implemented for {expr.wtype.name}\",\n expr.source_location,\n )\n\n def _visit_tuple_slice(\n self,\n expr: awst_nodes.SliceExpression | awst_nodes.IntersectionSliceExpression,\n base_wtype: wtypes.WTuple,\n ) -> TExpression:\n tup = self.visit_and_materialise(expr.base)\n start_i = extract_const_int(expr.begin_index) or 0\n end_i = extract_const_int(expr.end_index)\n return get_tuple_item_values(\n tuple_values=tup,\n tuple_wtype=base_wtype,\n index=(start_i, end_i),\n target_wtype=expr.wtype,\n source_location=expr.source_location,\n )\n\n def visit_index_expression(self, expr: awst_nodes.IndexExpression) -> TExpression:\n index = self.visit_and_materialise_single(expr.index)\n base = self.visit_and_materialise_single(expr.base)\n\n if expr.base.wtype == wtypes.bytes_wtype:\n # note: the below works because Bytes is immutable, so this index expression\n # can never appear as an assignment target\n if isinstance(index, UInt64Constant) and index.value <= 255:\n return Intrinsic(\n op=AVMOp.extract,\n args=[base],\n immediates=[index.value, 1],\n source_location=expr.source_location,\n )\n else:\n return Intrinsic(\n op=AVMOp.extract3,\n args=[\n base,\n index,\n UInt64Constant(value=1, source_location=expr.source_location),\n ],\n source_location=expr.source_location,\n )\n elif isinstance(expr.base.wtype, wtypes.WArray):\n raise NotImplementedError\n elif isinstance(expr.base.wtype, wtypes.ARC4StaticArray | wtypes.ARC4DynamicArray):\n return arc4.arc4_array_index(\n self.context,\n array_wtype=expr.base.wtype,\n array=base,\n index=index,\n source_location=expr.source_location,\n )\n else:\n raise InternalError(\n f\"Indexing operation IR lowering not implemented for {expr.wtype.name}\",\n expr.source_location,\n )\n\n def visit_conditional_expression(self, expr: awst_nodes.ConditionalExpression) -> TExpression:\n return flow_control.handle_conditional_expression(self.context, expr)\n\n def visit_single_evaluation(self, expr: awst_nodes.SingleEvaluation) -> TExpression:\n try:\n return self._single_eval_cache[expr]\n except KeyError:\n pass\n source = expr.source.accept(self)\n if not (source and source.types):\n result: TExpression = None\n else:\n values = self.materialise_value_provider(source, description=\"awst_tmp\")\n if len(values) == 1:\n (result,) = values\n else:\n result = ValueTuple(values=values, source_location=expr.source_location)\n self._single_eval_cache[expr] = result\n return result\n\n def visit_app_state_expression(self, expr: awst_nodes.AppStateExpression) -> TExpression:\n return storage.visit_app_state_expression(self.context, expr)\n\n def visit_app_account_state_expression(\n self, expr: awst_nodes.AppAccountStateExpression\n ) -> TExpression:\n return storage.visit_app_account_state_expression(self.context, expr)\n\n def visit_box_value_expression(self, expr: awst_nodes.BoxValueExpression) -> TExpression:\n return puya.ir.builder.storage.visit_box_value(self.context, expr)\n\n def visit_state_get_ex(self, expr: awst_nodes.StateGetEx) -> TExpression:\n return storage.visit_state_get_ex(self.context, expr)\n\n def visit_state_delete(self, statement: awst_nodes.StateDelete) -> TExpression:\n return storage.visit_state_delete(self.context, statement)\n\n def visit_state_get(self, expr: awst_nodes.StateGet) -> TExpression:\n return storage.visit_state_get(self.context, expr)\n\n def visit_state_exists(self, expr: awst_nodes.StateExists) -> TExpression:\n return storage.visit_state_exists(self.context, expr)\n\n def visit_new_array(self, expr: awst_nodes.NewArray) -> TExpression:\n match expr.wtype:\n case wtypes.ARC4Array():\n return arc4.encode_arc4_array(self.context, expr)\n case wtypes.WArray():\n raise NotImplementedError\n case _:\n typing.assert_never(expr.wtype)\n\n def visit_bytes_comparison_expression(\n self, expr: awst_nodes.BytesComparisonExpression\n ) -> TExpression:\n left = self.visit_and_materialise_single(expr.lhs)\n right = self.visit_and_materialise_single(expr.rhs)\n op_code = expr.operator.value\n try:\n avm_op = AVMOp(op_code)\n except ValueError as ex:\n raise InternalError(\n f\"Unmapped bytes comparison operator {expr.operator}\", expr.source_location\n ) from ex\n\n return Intrinsic(\n op=avm_op,\n args=[left, right],\n source_location=expr.source_location,\n )\n\n def visit_subroutine_call_expression(\n self, expr: awst_nodes.SubroutineCallExpression\n ) -> TExpression:\n return visit_subroutine_call_expression(self.context, expr)\n\n def visit_puya_lib_call(self, call: awst_nodes.PuyaLibCall) -> TExpression:\n return visit_puya_lib_call_expression(self.context, call)\n\n def visit_bytes_binary_operation(self, expr: awst_nodes.BytesBinaryOperation) -> TExpression:\n left = self.visit_and_materialise_single(expr.left)\n right = self.visit_and_materialise_single(expr.right)\n return create_bytes_binary_op(expr.op, left, right, expr.source_location)\n\n def visit_boolean_binary_operation(\n self, expr: awst_nodes.BooleanBinaryOperation\n ) -> TExpression:\n if not isinstance(expr.right, awst_nodes.VarExpression | awst_nodes.BoolConstant):\n true_block, false_block, merge_block = self.context.block_builder.mkblocks(\n \"bool_true\", \"bool_false\", \"bool_merge\", source_location=expr.source_location\n )\n tmp_name = self.context.next_tmp_name(f\"{expr.op}_result\")\n\n flow_control.process_conditional(\n self.context, expr, true=true_block, false=false_block, loc=expr.source_location\n )\n self.context.block_builder.activate_block(true_block)\n assign(\n self.context,\n UInt64Constant(value=1, ir_type=IRType.bool, source_location=None),\n name=tmp_name,\n assignment_location=None,\n )\n self.context.block_builder.goto(merge_block)\n\n self.context.block_builder.activate_block(false_block)\n assign(\n self.context,\n UInt64Constant(value=0, ir_type=IRType.bool, source_location=None),\n name=tmp_name,\n assignment_location=None,\n )\n self.context.block_builder.goto(merge_block)\n self.context.block_builder.activate_block(merge_block)\n return self.context.ssa.read_variable(\n variable=tmp_name, ir_type=IRType.bool, block=merge_block\n )\n\n left = self.visit_and_materialise_single(expr.left)\n right = self.visit_and_materialise_single(expr.right)\n match expr.op:\n case \"and\":\n op = AVMOp.and_\n case \"or\":\n op = AVMOp.or_\n case _:\n raise InternalError(\n f\"Unexpected\/unimplemented boolean operator in IR builder: {expr.op}\",\n expr.source_location,\n )\n return Intrinsic(\n op=op,\n args=[left, right],\n source_location=expr.source_location,\n )\n\n def visit_not_expression(self, expr: awst_nodes.Not) -> TExpression:\n negated = self.visit_and_materialise_single(expr.expr)\n return Intrinsic(\n op=AVMOp(\"!\"),\n args=[negated],\n source_location=expr.source_location,\n )\n\n def visit_reinterpret_cast(self, expr: awst_nodes.ReinterpretCast) -> TExpression:\n # should be a no-op for us, but we validate the cast here too\n source = self.visit_expr(expr.expr)\n (inner_ir_type,) = source.types\n outer_ir_type = wtype_to_ir_type(expr)\n # don't need to do anything further if ir types are the same\n if inner_ir_type == outer_ir_type:\n return source\n inner_avm_type = inner_ir_type.avm_type\n outer_avm_type = outer_ir_type.avm_type\n if inner_avm_type != outer_avm_type:\n raise InternalError(\n f\"Tried to reinterpret {expr.expr.wtype} as {expr.wtype},\"\n \" but resulting AVM types are incompatible:\"\n f\" {inner_avm_type} and {outer_avm_type}, respectively\",\n expr.source_location,\n )\n target = mktemp(\n self.context,\n outer_ir_type,\n description=f\"reinterpret_{outer_ir_type.name}\",\n source_location=expr.source_location,\n )\n assign_targets(\n self.context,\n source=source,\n targets=[target],\n assignment_location=expr.source_location,\n )\n return target\n\n def visit_block(self, block: awst_nodes.Block) -> TStatement:\n if block.label:\n ir_block = self.context.block_builder.mkblock(block)\n self.context.block_builder.goto(ir_block)\n self.context.block_builder.activate_block(ir_block)\n\n for stmt in block.body:\n stmt.accept(self)\n\n def visit_goto(self, statement: awst_nodes.Goto) -> TStatement:\n self.context.block_builder.goto_label(statement.target, statement.source_location)\n\n def visit_if_else(self, stmt: awst_nodes.IfElse) -> TStatement:\n flow_control.handle_if_else(self.context, stmt)\n\n def visit_switch(self, statement: awst_nodes.Switch) -> TStatement:\n flow_control.handle_switch(self.context, statement)\n\n def visit_while_loop(self, statement: awst_nodes.WhileLoop) -> TStatement:\n flow_control.handle_while_loop(self.context, statement)\n\n def visit_loop_exit(self, statement: awst_nodes.LoopExit) -> TStatement:\n self.context.block_builder.loop_break(statement.source_location)\n\n def visit_return_statement(self, statement: awst_nodes.ReturnStatement) -> TStatement:\n if statement.value is not None:\n result = list(self.visit_and_materialise(statement.value))\n else:\n result = []\n\n for param in self.context.subroutine.parameters:\n if param.implicit_return:\n result.append(\n self.context.ssa.read_variable(\n param.name,\n param.ir_type,\n self.context.block_builder.active_block,\n )\n )\n return_types = [r.ir_type for r in result]\n if return_types != self.context.subroutine.returns:\n raise CodeError(\n f\"invalid return type {return_types}, expected {self.context.subroutine.returns}\",\n statement.source_location,\n )\n self.context.block_builder.terminate(\n SubroutineReturn(\n source_location=statement.source_location,\n result=result,\n )\n )\n\n def visit_assert_expression(self, expr: awst_nodes.AssertExpression) -> TStatement:\n op = self._add_assert(\n condition_expr=expr.condition,\n error_message=expr.error_message,\n loc=expr.source_location,\n )\n if op:\n self.context.block_builder.add(op)\n\n def visit_template_var(self, expr: awst_nodes.TemplateVar) -> TExpression:\n return TemplateVar(\n name=expr.name,\n ir_type=wtype_to_ir_type(expr.wtype),\n source_location=expr.source_location,\n )\n\n def visit_loop_continue(self, statement: awst_nodes.LoopContinue) -> TStatement:\n self.context.block_builder.loop_continue(statement.source_location)\n\n def visit_expression_statement(self, statement: awst_nodes.ExpressionStatement) -> TStatement:\n # NOTE: popping of ignored return values should happen at code gen time\n result = self._visit_and_check_for_double_eval(statement.expr)\n if result is None:\n wtype = statement.expr.wtype\n match wtype:\n case wtypes.void_wtype:\n pass\n case _ if (isinstance(wtype, WInnerTransaction | WInnerTransactionFields)):\n # inner transaction wtypes aren't true expressions\n pass\n case _:\n raise InternalError(\n f\"Expression statement with type {statement.expr.wtype} \"\n f\"generated no result\",\n statement.source_location,\n )\n elif isinstance(result, Op):\n self.context.block_builder.add(result)\n # If we get a Value (e.g. a Register or some such) it's something that's being\n # discarded effectively.\n # The frontend should have already warned about this\n\n def visit_uint64_augmented_assignment(\n self, statement: awst_nodes.UInt64AugmentedAssignment\n ) -> TStatement:\n target_value = self.visit_and_materialise_single(statement.target)\n rhs = self.visit_and_materialise_single(statement.value)\n expr = create_uint64_binary_op(statement.op, target_value, rhs, statement.source_location)\n\n handle_assignment(\n self.context,\n target=statement.target,\n value=expr,\n is_nested_update=False,\n assignment_location=statement.source_location,\n )\n\n def visit_biguint_augmented_assignment(\n self, statement: awst_nodes.BigUIntAugmentedAssignment\n ) -> TStatement:\n target_value = self.visit_and_materialise_single(statement.target)\n rhs = self.visit_and_materialise_single(statement.value)\n expr = create_biguint_binary_op(statement.op, target_value, rhs, statement.source_location)\n\n handle_assignment(\n self.context,\n target=statement.target,\n value=expr,\n is_nested_update=False,\n assignment_location=statement.source_location,\n )\n\n def visit_bytes_augmented_assignment(\n self, statement: awst_nodes.BytesAugmentedAssignment\n ) -> TStatement:\n if statement.target.wtype == wtypes.arc4_string_alias:\n value: ValueProvider = arc4.concat_values(\n self.context, statement.target, statement.value, statement.source_location\n )\n else:\n target_value = self.visit_and_materialise_single(statement.target)\n rhs = self.visit_and_materialise_single(statement.value)\n value = create_bytes_binary_op(\n statement.op, target_value, rhs, statement.source_location\n )\n\n handle_assignment(\n self.context,\n target=statement.target,\n value=value,\n is_nested_update=False,\n assignment_location=statement.source_location,\n )\n\n def visit_enumeration(self, expr: awst_nodes.Enumeration) -> TStatement:\n raise CodeError(\"Nested enumeration is not currently supported\", expr.source_location)\n\n def visit_reversed(self, expr: awst_nodes.Reversed) -> TExpression:\n raise CodeError(\"Reversed is not valid outside of an enumeration\", expr.source_location)\n\n def visit_for_in_loop(self, statement: awst_nodes.ForInLoop) -> TStatement:\n handle_for_in_loop(self.context, statement)\n\n def visit_new_struct(self, expr: awst_nodes.NewStruct) -> TExpression:\n match expr.wtype:\n case wtypes.WStructType():\n raise NotImplementedError\n case wtypes.ARC4Struct() as arc4_struct_wtype:\n return arc4.encode_arc4_struct(self.context, expr, arc4_struct_wtype)\n case _:\n typing.assert_never(expr.wtype)\n\n def visit_array_pop(self, expr: awst_nodes.ArrayPop) -> TExpression:\n source_location = expr.source_location\n match expr.base.wtype:\n case wtypes.ARC4DynamicArray() as array_wtype:\n return arc4.pop_arc4_array(self.context, expr, array_wtype)\n case _:\n raise InternalError(\n f\"Unsupported target for array pop: {expr.base.wtype}\", source_location\n )\n\n def visit_array_concat(self, expr: awst_nodes.ArrayConcat) -> TExpression:\n return arc4.concat_values(\n self.context,\n left_expr=expr.left,\n right_expr=expr.right,\n source_location=expr.source_location,\n )\n\n def visit_array_extend(self, expr: awst_nodes.ArrayExtend) -> TExpression:\n concat_result = arc4.concat_values(\n self.context,\n left_expr=expr.base,\n right_expr=expr.other,\n source_location=expr.source_location,\n )\n return arc4.handle_arc4_assign(\n self.context,\n target=expr.base,\n value=concat_result,\n is_nested_update=True,\n source_location=expr.source_location,\n )\n\n def visit_arc4_router(self, expr: awst_nodes.ARC4Router) -> TExpression:\n root = self.context.root\n if not isinstance(root, awst_nodes.Contract):\n raise CodeError(\n \"cannot create ARC4 router outside of a contract\", expr.source_location\n )\n\n return InvokeSubroutine(\n target=self.context.routers[root.id],\n args=[],\n source_location=expr.source_location,\n )\n\n def visit_emit(self, expr: awst_nodes.Emit) -> TExpression:\n factory = OpFactory(self.context, expr.source_location)\n value = self.context.visitor.visit_and_materialise_single(expr.value)\n prefix = MethodConstant(value=expr.signature, source_location=expr.source_location)\n event = factory.concat(prefix, value, \"event\")\n\n self.context.block_builder.add(\n Intrinsic(\n op=AVMOp(\"log\"),\n args=[event],\n source_location=expr.source_location,\n )\n )\n return None\n\n def visit_range(self, node: awst_nodes.Range) -> TExpression:\n raise CodeError(\"unexpected range location\", node.source_location)\n\n def visit_and_materialise_single(\n self, expr: awst_nodes.Expression, temp_description: str = \"tmp\"\n ) -> Value:\n \"\"\"Translate an AWST Expression into a single Value\"\"\"\n values = self.visit_and_materialise(expr, temp_description=temp_description)\n try:\n (value,) = values\n except ValueError as ex:\n raise InternalError(\n \"visit_and_materialise_single should not be used when\"\n f\" an expression could be multi-valued, expression was: {expr}\",\n expr.source_location,\n ) from ex\n return value\n\n def visit_and_materialise(\n self, expr: awst_nodes.Expression, temp_description: str | Sequence[str] = \"tmp\"\n ) -> Sequence[Value]:\n value_seq_or_provider = self._visit_and_check_for_double_eval(\n expr, materialise_as=temp_description\n )\n if value_seq_or_provider is None:\n raise InternalError(\n \"No value produced by expression IR conversion\", expr.source_location\n )\n return self.materialise_value_provider(value_seq_or_provider, description=temp_description)\n\n def visit_expr(self, expr: awst_nodes.Expression) -> ValueProvider:\n \"\"\"Visit the expression and ensure result is not None\"\"\"\n value_seq_or_provider = self._visit_and_check_for_double_eval(expr)\n if value_seq_or_provider is None:\n raise InternalError(\n \"No value produced by expression IR conversion\", expr.source_location\n )\n return value_seq_or_provider\n\n def _visit_and_check_for_double_eval(\n self, expr: awst_nodes.Expression, *, materialise_as: str | Sequence[str] | None = None\n ) -> ValueProvider | None:\n # explicit SingleEvaluation nodes already handle this\n if isinstance(expr, awst_nodes.SingleEvaluation):\n return expr.accept(self)\n # include the expression in the key to ensure the lifetime of the\n # expression is as long as the cache.\n # Temporary nodes may end up with the same id if nothing is referencing them\n # e.g. such as used in _update_implicit_out_var\n expr_id = id(expr), expr\n try:\n result = self._visited_exprs[expr_id]\n except KeyError:\n pass\n else:\n if isinstance(result, ValueProvider) and not isinstance(result, ValueTuple | Value):\n raise InternalError(\n \"double evaluation of expression without materialization\", expr.source_location\n )\n expr_str = expr.accept(ToCodeVisitor())\n logger.debug(\n f\"encountered already materialized expression ({expr_str}),\"\n f\" reusing result: {result!s}\",\n location=expr.source_location,\n )\n return result\n source = expr.accept(self)\n if materialise_as is None or not (source and source.types):\n result = source\n else:\n values = self.materialise_value_provider(source, description=materialise_as)\n if len(values) == 1:\n (result,) = values\n else:\n result = ValueTuple(values=values, source_location=expr.source_location)\n self._visited_exprs[expr_id] = result\n return result\n\n def materialise_value_provider(\n self, provider: ValueProvider, description: str | Sequence[str]\n ) -> list[Value]:\n \"\"\"\n Given a ValueProvider with arity of N, return a Value sequence of length N.\n\n Anything which is already a Value is passed through without change.\n\n Otherwise, the result is assigned to a temporary register, which is returned\n \"\"\"\n if isinstance(provider, Value):\n return [provider]\n\n if isinstance(provider, ValueTuple):\n return list(provider.values)\n\n ir_types = provider.types\n if not ir_types:\n raise InternalError(\n \"Attempted to assign from expression that has no result\", provider.source_location\n )\n\n if isinstance(description, str):\n temp_description: Sequence[str] = [description] * len(ir_types)\n else:\n temp_description = description\n targets = [\n mktemp(self.context, ir_type, provider.source_location, description=descr)\n for ir_type, descr in zip(ir_types, temp_description, strict=True)\n ]\n assign_targets(\n context=self.context,\n source=provider,\n targets=targets,\n # TODO: should this be the source location of the site forcing materialisation?\n assignment_location=provider.source_location,\n )\n return list[Value](targets)\n\n\ndef create_uint64_binary_op(\n op: UInt64BinaryOperator, left: Value, right: Value, source_location: SourceLocation\n) -> Intrinsic:\n avm_op: AVMOp\n match op:\n case UInt64BinaryOperator.floor_div:\n avm_op = AVMOp.div_floor\n case UInt64BinaryOperator.pow:\n avm_op = AVMOp.exp\n case UInt64BinaryOperator.lshift:\n avm_op = AVMOp.shl\n case UInt64BinaryOperator.rshift:\n avm_op = AVMOp.shr\n case _:\n try:\n avm_op = AVMOp(op.value)\n except ValueError as ex:\n raise InternalError(\n f\"Unhandled uint64 binary operator: {op}\", source_location\n ) from ex\n return Intrinsic(op=avm_op, args=[left, right], source_location=source_location)\n\n\ndef create_biguint_binary_op(\n op: BigUIntBinaryOperator, left: Value, right: Value, source_location: SourceLocation\n) -> Intrinsic:\n avm_op: AVMOp\n match op:\n case BigUIntBinaryOperator.floor_div:\n avm_op = AVMOp.div_floor_bytes\n case _:\n try:\n avm_op = AVMOp(\"b\" + op.value)\n except ValueError as ex:\n raise InternalError(\n f\"Unhandled uint64 binary operator: {op}\", source_location\n ) from ex\n return Intrinsic(\n op=avm_op, args=[left, right], types=(IRType.biguint,), source_location=source_location\n )\n\n\ndef create_bytes_binary_op(\n op: awst_nodes.BytesBinaryOperator, lhs: Value, rhs: Value, source_location: SourceLocation\n) -> ValueProvider:\n match op:\n case awst_nodes.BytesBinaryOperator.add:\n return Intrinsic(\n op=AVMOp.concat,\n args=[lhs, rhs],\n source_location=source_location,\n )\n case awst_nodes.BytesBinaryOperator.bit_and:\n return Intrinsic(\n op=AVMOp.bitwise_and_bytes,\n args=[lhs, rhs],\n source_location=source_location,\n )\n case awst_nodes.BytesBinaryOperator.bit_or:\n return Intrinsic(\n op=AVMOp.bitwise_or_bytes,\n args=[lhs, rhs],\n source_location=source_location,\n )\n case awst_nodes.BytesBinaryOperator.bit_xor:\n return Intrinsic(\n op=AVMOp.bitwise_xor_bytes,\n args=[lhs, rhs],\n source_location=source_location,\n )\n raise InternalError(\"Unsupported BytesBinaryOperator: \" + op)\n\n\ndef get_comparison_op_for_wtype(\n numeric_comparison_equivalent: awst_nodes.NumericComparison, wtype: wtypes.WType\n) -> AVMOp:\n match wtype:\n case wtypes.biguint_wtype:\n return AVMOp(\"b\" + numeric_comparison_equivalent)\n case wtypes.uint64_wtype:\n return AVMOp(numeric_comparison_equivalent)\n case wtypes.bytes_wtype:\n match numeric_comparison_equivalent:\n case awst_nodes.NumericComparison.eq:\n return AVMOp.eq\n case awst_nodes.NumericComparison.ne:\n return AVMOp.neq\n raise InternalError(\n f\"unsupported operation of {numeric_comparison_equivalent} on type of {wtype}\"\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/builder\/main.py","language":"Python","license":"NOASSERTION","size":56636} {"code":"import typing\n\nfrom puya.avm import AVMType\nfrom puya.awst import (\n nodes as awst_nodes,\n wtypes,\n)\nfrom puya.ir import intrinsic_factory\nfrom puya.ir.avm_ops import AVMOp\nfrom puya.ir.builder._utils import assert_value, assign_targets, mktemp\nfrom puya.ir.context import IRFunctionBuildContext\nfrom puya.ir.models import Intrinsic, UInt64Constant, Value, ValueProvider, ValueTuple\nfrom puya.ir.types_ import IRType, wtype_to_ir_type\nfrom puya.parse import SourceLocation\n\n\ndef visit_app_state_expression(\n context: IRFunctionBuildContext, expr: awst_nodes.AppStateExpression\n) -> ValueProvider:\n maybe_value, exists = _build_state_get_ex(context, expr, expr.source_location)\n # TODO: add specific (unsafe) optimisation flag to allow skipping this check\n assert_value(\n context,\n value=exists,\n comment=expr.exists_assertion_message or \"state exists\",\n source_location=expr.source_location,\n )\n return maybe_value\n\n\ndef visit_app_account_state_expression(\n context: IRFunctionBuildContext, expr: awst_nodes.AppAccountStateExpression\n) -> ValueProvider:\n maybe_value, exists = _build_state_get_ex(context, expr, expr.source_location)\n # TODO: add specific (unsafe) optimisation flag to allow skipping this check\n assert_value(\n context,\n value=exists,\n comment=expr.exists_assertion_message or \"state exists for account\",\n source_location=expr.source_location,\n )\n return maybe_value\n\n\ndef visit_box_value(\n context: IRFunctionBuildContext, expr: awst_nodes.BoxValueExpression\n) -> ValueProvider:\n maybe_value, exists = _build_state_get_ex(context, expr, expr.source_location)\n # TODO: add specific (unsafe) optimisation flag to allow skipping this check\n assert_value(\n context,\n value=exists,\n comment=expr.exists_assertion_message or \"box exists\",\n source_location=expr.source_location,\n )\n return maybe_value\n\n\ndef visit_state_exists(\n context: IRFunctionBuildContext, expr: awst_nodes.StateExists\n) -> ValueProvider:\n _, exists = _build_state_get_ex(\n context, expr.field, expr.source_location, for_existence_check=True\n )\n return exists\n\n\ndef visit_state_get(context: IRFunctionBuildContext, expr: awst_nodes.StateGet) -> ValueProvider:\n default = context.visitor.visit_and_materialise_single(expr.default)\n maybe_value, exists = _build_state_get_ex(context, expr.field, expr.source_location)\n return intrinsic_factory.select(\n condition=exists,\n true=maybe_value,\n false=default,\n type_=wtype_to_ir_type(expr.wtype),\n source_location=expr.source_location,\n )\n\n\ndef visit_state_get_ex(\n context: IRFunctionBuildContext, expr: awst_nodes.StateGetEx\n) -> ValueProvider:\n return ValueTuple(\n values=list(_build_state_get_ex(context, expr.field, expr.source_location)),\n source_location=expr.source_location,\n )\n\n\ndef visit_state_delete(\n context: IRFunctionBuildContext, statement: awst_nodes.StateDelete\n) -> ValueProvider | None:\n match statement.field:\n case awst_nodes.BoxValueExpression(key=awst_key):\n op = AVMOp.box_del\n awst_account = None\n case awst_nodes.AppStateExpression(key=awst_key):\n op = AVMOp.app_global_del\n awst_account = None\n case awst_nodes.AppAccountStateExpression(key=awst_key, account=awst_account):\n op = AVMOp.app_local_del\n case _:\n typing.assert_never(statement.field)\n\n args = []\n if awst_account is not None:\n account_value = context.visitor.visit_and_materialise_single(awst_account)\n args.append(account_value)\n key_value = context.visitor.visit_and_materialise_single(awst_key)\n args.append(key_value)\n\n context.block_builder.add(\n Intrinsic(op=op, args=args, source_location=statement.source_location)\n )\n return None\n\n\ndef _build_state_get_ex(\n context: IRFunctionBuildContext,\n expr: (\n awst_nodes.AppAccountStateExpression\n | awst_nodes.AppStateExpression\n | awst_nodes.BoxValueExpression\n ),\n source_location: SourceLocation,\n *,\n for_existence_check: bool = False,\n) -> tuple[Value, Value]:\n key = context.visitor.visit_and_materialise_single(expr.key)\n args: list[Value]\n true_value_ir_type = get_ex_value_ir_type = wtype_to_ir_type(expr.wtype)\n convert_op: AVMOp | None = None\n if isinstance(expr, awst_nodes.AppStateExpression):\n current_app_offset = UInt64Constant(value=0, source_location=expr.source_location)\n args = [current_app_offset, key]\n op = AVMOp.app_global_get_ex\n elif isinstance(expr, awst_nodes.AppAccountStateExpression):\n current_app_offset = UInt64Constant(value=0, source_location=expr.source_location)\n op = AVMOp.app_local_get_ex\n account = context.visitor.visit_and_materialise_single(expr.account)\n args = [account, current_app_offset, key]\n else:\n args = [key]\n if for_existence_check:\n get_ex_value_ir_type = IRType.uint64\n op = AVMOp.box_len\n else:\n op = AVMOp.box_get\n match wtypes.persistable_stack_type(expr.wtype, source_location):\n case AVMType.uint64:\n get_ex_value_ir_type = IRType.bytes\n convert_op = AVMOp.btoi\n case AVMType.bytes:\n pass\n case invalid:\n typing.assert_never(invalid)\n get_ex = Intrinsic(\n op=op,\n args=args,\n types=[get_ex_value_ir_type, IRType.bool],\n source_location=source_location,\n )\n value_tmp, did_exist_tmp = context.visitor.materialise_value_provider(\n get_ex, (\"maybe_value\", \"maybe_exists\")\n )\n if convert_op is None:\n return value_tmp, did_exist_tmp\n convert = Intrinsic(op=convert_op, args=[value_tmp], source_location=source_location)\n value_tmp_converted = mktemp(\n context,\n ir_type=true_value_ir_type,\n description=\"maybe_value_converted\",\n source_location=expr.source_location,\n )\n\n assign_targets(\n context, source=convert, targets=[value_tmp_converted], assignment_location=source_location\n )\n return value_tmp_converted, did_exist_tmp\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/builder\/storage.py","language":"Python","license":"NOASSERTION","size":6336} {"code":"import contextlib\nimport itertools\nimport typing\nfrom collections import defaultdict\nfrom collections.abc import Iterator, Mapping\nfrom functools import cached_property\n\nimport attrs\n\nimport puya.awst.nodes as awst_nodes\nfrom puya.context import CompileContext\nfrom puya.errors import CodeError, log_exceptions\nfrom puya.ir.builder.blocks import BlocksBuilder\nfrom puya.ir.models import Subroutine\nfrom puya.ir.ssa import BraunSSA\nfrom puya.parse import SourceLocation\nfrom puya.program_refs import ContractReference\nfrom puya.utils import attrs_extend\n\nif typing.TYPE_CHECKING:\n from puya.ir.builder.main import FunctionIRBuilder\n\nTMP_VAR_INDICATOR = \"%\"\n\n\n@attrs.frozen(kw_only=True)\nclass IRBuildContext(CompileContext):\n awst: awst_nodes.AWST\n subroutines: dict[awst_nodes.Function, Subroutine]\n embedded_funcs_lookup: Mapping[str, Subroutine]\n root: awst_nodes.Contract | awst_nodes.LogicSignature | None = None\n routers: dict[ContractReference, Subroutine] = attrs.field(factory=dict)\n\n @cached_property\n def _awst_lookup(self) -> Mapping[str, awst_nodes.RootNode]:\n return {node.id: node for node in self.awst}\n\n def for_root(self, root: awst_nodes.Contract | awst_nodes.LogicSignature) -> typing.Self:\n return attrs.evolve(\n self,\n root=root,\n # copy subroutines so that contract specific subroutines do not pollute other passes\n subroutines=self.subroutines.copy(),\n )\n\n def for_function(\n self, function: awst_nodes.Function, subroutine: Subroutine, visitor: \"FunctionIRBuilder\"\n ) -> \"IRFunctionBuildContext\":\n return attrs_extend(\n IRFunctionBuildContext, self, visitor=visitor, function=function, subroutine=subroutine\n )\n\n def resolve_function_reference(\n self,\n target: awst_nodes.SubroutineTarget,\n source_location: SourceLocation,\n caller: awst_nodes.Function,\n ) -> awst_nodes.Function:\n if isinstance(target, awst_nodes.SubroutineID):\n func: awst_nodes.Node | None = self._awst_lookup.get(target.target)\n else:\n contract = self.root\n if not (\n isinstance(contract, awst_nodes.Contract)\n and isinstance(caller, awst_nodes.ContractMethod)\n ):\n raise CodeError(\n \"call to contract method from outside of contract class\",\n source_location,\n )\n match target:\n case awst_nodes.InstanceMethodTarget(member_name=member_name):\n func = contract.resolve_contract_method(member_name)\n case awst_nodes.ContractMethodTarget(cref=start_at, member_name=member_name):\n func = contract.resolve_contract_method(\n member_name, source_location, start=start_at\n )\n case awst_nodes.InstanceSuperMethodTarget(member_name=member_name):\n func = contract.resolve_contract_method(\n member_name, source_location, start=caller.cref, skip=True\n )\n case unexpected:\n typing.assert_never(unexpected)\n if func is None:\n raise CodeError(f\"unable to resolve function reference {target}\", source_location)\n if not isinstance(func, awst_nodes.Function):\n raise CodeError(\n f\"function reference {target} resolved to non-function {func}\", source_location\n )\n return func\n\n @property\n def default_fallback(self) -> SourceLocation | None:\n if self.root:\n return self.root.source_location\n return None\n\n @contextlib.contextmanager\n def log_exceptions(self, fallback_location: SourceLocation | None = None) -> Iterator[None]:\n with log_exceptions(fallback_location or self.default_fallback):\n yield\n\n\n@attrs.frozen(kw_only=True)\nclass IRFunctionBuildContext(IRBuildContext):\n \"\"\"Context when building from an awst Function node\"\"\"\n\n function: awst_nodes.Function\n subroutine: Subroutine\n visitor: \"FunctionIRBuilder\"\n block_builder: BlocksBuilder = attrs.field()\n _tmp_counters: defaultdict[str, Iterator[int]] = attrs.field(\n factory=lambda: defaultdict(itertools.count)\n )\n\n @property\n def ssa(self) -> BraunSSA:\n return self.block_builder.ssa\n\n @block_builder.default\n def _block_builder_factory(self) -> BlocksBuilder:\n return BlocksBuilder(self.subroutine.parameters, self.function.source_location)\n\n def next_tmp_name(self, description: str) -> str:\n counter_value = next(self._tmp_counters[description])\n return f\"{description}{TMP_VAR_INDICATOR}{counter_value}\"\n\n @property\n def default_fallback(self) -> SourceLocation | None:\n return self.function.source_location\n\n def resolve_subroutine(\n self,\n target: awst_nodes.SubroutineTarget,\n source_location: SourceLocation,\n *,\n caller: awst_nodes.Function | None = None,\n ) -> Subroutine:\n func = self.resolve_function_reference(\n target=target, source_location=source_location, caller=caller or self.function\n )\n return self.subroutines[func]\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/context.py","language":"Python","license":"NOASSERTION","size":5307} {"code":"","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/destructure\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"import itertools\nimport typing\nimport typing as t\nfrom collections.abc import Iterable\n\nimport attrs\n\nfrom puya import log\nfrom puya.avm import AVMType\nfrom puya.ir import models\nfrom puya.ir.types_ import IRType\nfrom puya.ir.visitor_mem_replacer import MemoryReplacer\nfrom puya.ir.vla import VariableLifetimeAnalysis\nfrom puya.options import LocalsCoalescingStrategy\nfrom puya.utils import StableSet\n\nlogger = log.get_logger(__name__)\n\n\n@attrs.define\nclass MemoryReplacerWithRedundantAssignmentRemoval(MemoryReplacer):\n def visit_assignment(self, op: models.Assignment) -> models.Assignment | None:\n ass = super().visit_assignment(op)\n if ass is None or ass.targets == (ass.source,):\n return None\n return ass\n\n\nclass CoalesceGroupStrategy(t.Protocol):\n def get_group_key(self, reg: models.Register) -> object: ...\n\n def determine_group_replacement(self, regs: Iterable[models.Register]) -> models.Register: ...\n\n\ndef coalesce_registers(group_strategy: CoalesceGroupStrategy, sub: models.Subroutine) -> int:\n \"\"\"\n A local can be merged with another local if they are never live at the same time.\n\n For each local that is being defined, check to see what the live-out locals are.\n\n It can be merged with another local set if:\n - This local is not in the \"live-out\" of any local in set\n - The \"live-out\" of this local does not intersect the local set\n \"\"\"\n vla = VariableLifetimeAnalysis.analyze(sub)\n\n # TODO: this uses a basic definition of interference by looking at live-ranges,\n # a better option is to continue with https:\/\/inria.hal.science\/inria-00349925v1\/document\n # which has already been partially implemented (phase 1 + 4 have been, anyway)\n\n variables_live_at_definition = dict[models.Register, StableSet[models.Register]]()\n for param in sub.parameters:\n variables_live_at_definition[param] = StableSet.from_iter(sub.parameters)\n for block in sub.body:\n for op in block.ops:\n match op:\n case models.Assignment(targets=targets):\n op_live_out = vla.get_live_out_variables(op)\n for defined_reg in targets:\n live_set = variables_live_at_definition.setdefault(\n defined_reg, StableSet()\n )\n live_set |= op_live_out\n\n coalescable_groups_by_key = dict[\n object, list[tuple[StableSet[models.Register], StableSet[models.Register]]]\n ]()\n for defined_reg, live_set in variables_live_at_definition.items():\n coalescable_groups = coalescable_groups_by_key.setdefault(\n group_strategy.get_group_key(defined_reg), []\n )\n for coalescable_register_set, combined_live_out in coalescable_groups:\n # conditions:\n # 1) this register\/variable must not be \"alive\" _after_ the\n # definition of any other variable in this set\n # 2) no register already in the set should be live out at the\n # definition of this register\n # regardless of the order the definitions are processed in, this guarantees that:\n # for all A and B in coalescable_register_set such that A != B:\n # A is not live-out whenever B is assigned\n # AND B is not live-out whenever A is assigned\n if defined_reg not in combined_live_out and live_set.isdisjoint(\n coalescable_register_set\n ):\n coalescable_register_set.add(defined_reg)\n combined_live_out |= live_set\n break\n else:\n coalescable_groups.append((StableSet(defined_reg), StableSet.from_iter(live_set)))\n\n replacements = dict[models.Register, models.Register]()\n for group in coalescable_groups_by_key.values():\n for coalescable_register_set, _ in group:\n if len(coalescable_register_set) < 2:\n continue\n replacement = group_strategy.determine_group_replacement(coalescable_register_set)\n find = coalescable_register_set - {replacement}\n\n logger.debug(f\"Coalescing {replacement} with [{', '.join(map(str, find))}]\")\n replacements.update({to_find: replacement for to_find in find})\n total_replacements = MemoryReplacerWithRedundantAssignmentRemoval.apply(\n sub.body, replacements=replacements\n )\n return total_replacements\n\n\nclass RootOperandGrouping(CoalesceGroupStrategy):\n def __init__(self, isolate: frozenset[models.Register] | None = None) -> None:\n self._isolate = isolate or frozenset()\n\n def get_group_key(self, reg: models.Register) -> object:\n if reg in self._isolate:\n return reg\n return reg.name, reg.ir_type\n\n def determine_group_replacement(self, regs: Iterable[models.Register]) -> models.Register:\n return min(regs, key=lambda r: r.version)\n\n\nclass AggressiveGrouping(CoalesceGroupStrategy):\n def __init__(self, sub: models.Subroutine) -> None:\n self._params = frozenset(sub.parameters)\n self._counter = itertools.count()\n\n def get_group_key(self, reg: models.Register) -> object:\n if reg in self._params:\n return reg\n else:\n return reg.atype\n\n def determine_group_replacement(self, regs: Iterable[models.Register]) -> models.Register:\n next_id = next(self._counter)\n (atype,) = {r.atype for r in regs}\n match atype:\n case AVMType.uint64:\n ir_type = IRType.uint64\n case AVMType.bytes:\n ir_type = IRType.bytes\n case _:\n typing.assert_never(atype)\n return models.Register(\n name=\"\",\n version=next_id,\n ir_type=ir_type,\n source_location=None,\n )\n\n\ndef coalesce_locals(subroutine: models.Subroutine, strategy: LocalsCoalescingStrategy) -> None:\n match strategy:\n case LocalsCoalescingStrategy.root_operand:\n group_strategy: CoalesceGroupStrategy = RootOperandGrouping()\n case LocalsCoalescingStrategy.root_operand_excluding_args:\n group_strategy = RootOperandGrouping(isolate=frozenset(subroutine.parameters))\n case LocalsCoalescingStrategy.aggressive:\n group_strategy = AggressiveGrouping(subroutine)\n logger.debug(\n f\"Coalescing local variables in {subroutine.id}\"\n f\" using strategy {type(group_strategy).__name__}\"\n )\n replacements = coalesce_registers(group_strategy, subroutine)\n logger.debug(f\"Coalescing resulted in {replacements} replacement\/s\")\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/destructure\/coalesce_locals.py","language":"Python","license":"NOASSERTION","size":6658} {"code":"import attrs\n\nfrom puya import log\nfrom puya.context import CompileContext\nfrom puya.ir import models\nfrom puya.ir.destructure.coalesce_locals import coalesce_locals\nfrom puya.ir.destructure.optimize import post_ssa_optimizer\nfrom puya.ir.destructure.parcopy import sequentialize_parallel_copies\nfrom puya.ir.destructure.remove_phi import convert_to_cssa, destructure_cssa\n\nlogger = log.get_logger(__name__)\n\n\ndef destructure_ssa(context: CompileContext, program: models.Program) -> None:\n for subroutine in program.all_subroutines:\n logger.debug(f\"Performing SSA IR destructuring for {subroutine.id}\")\n convert_to_cssa(subroutine)\n subroutine.validate_with_ssa()\n destructure_cssa(subroutine)\n coalesce_locals(subroutine, context.options.locals_coalescing_strategy)\n sequentialize_parallel_copies(subroutine)\n post_ssa_optimizer(subroutine, context.options.optimization_level)\n attrs.validate(subroutine)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/destructure\/main.py","language":"Python","license":"NOASSERTION","size":965} {"code":"import contextlib\nimport itertools\n\nfrom puya import log\nfrom puya.ir import models\nfrom puya.ir.optimize.collapse_blocks import BlockReferenceReplacer\nfrom puya.utils import unique\n\nlogger = log.get_logger(__name__)\n\n\ndef post_ssa_optimizer(sub: models.Subroutine, optimization_level: int) -> None:\n logger.debug(f\"Performing post-SSA optimizations at level {optimization_level}\")\n if optimization_level >= 1:\n _remove_linear_jumps(sub)\n if optimization_level >= 2:\n _block_deduplication(sub)\n\n\ndef _remove_linear_jumps(subroutine: models.Subroutine) -> None:\n # P = {p0, p1, ..., pn} -> {j} -> {t}\n # remove {j} from subroutine\n # point P at t:\n # update references within P from j to t\n # ensure P are all in predecessors of t\n # This exists here and not in main IR optimization loop because we only want to do it for\n # blocks that are _truly_ empty, not ones that contain phi-node magic that results in copies\n # build a map of any blocks that are just an unconditional branch to their targets\n jumps = dict[models.BasicBlock, models.BasicBlock]()\n for block in subroutine.body.copy():\n match block:\n case models.BasicBlock(\n ops=[], terminator=models.Goto(target=target)\n ) if target is not block:\n jumps[block] = target\n logger.debug(f\"Removing jump block {block}\")\n with contextlib.suppress(ValueError):\n target.predecessors.remove(block)\n subroutine.body.remove(block)\n\n # now back-propagate any chains\n replacements = dict[models.BasicBlock, models.BasicBlock]()\n for src, target in jumps.items():\n while True:\n try:\n target = jumps[target]\n except KeyError:\n break\n logger.debug(f\"branching to {src} will be replaced with {target}\")\n replacements[src] = target\n BlockReferenceReplacer.apply(find=src, replacement=target, blocks=subroutine.body)\n for pred in src.predecessors:\n if pred not in target.predecessors:\n target.predecessors.append(pred)\n\n\ndef _block_deduplication(subroutine: models.Subroutine) -> None:\n seen = dict[tuple[object, ...], models.BasicBlock]()\n for block in subroutine.body.copy():\n all_ops = tuple(op.freeze() for op in block.all_ops)\n if existing := seen.get(all_ops):\n logger.debug(\n f\"Removing duplicated block {block} and updating references to {existing}\"\n )\n BlockReferenceReplacer.apply(find=block, replacement=existing, blocks=subroutine.body)\n subroutine.body.remove(block)\n existing.predecessors = unique(\n itertools.chain(existing.predecessors, block.predecessors)\n )\n else:\n seen[all_ops] = block\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/destructure\/optimize.py","language":"Python","license":"NOASSERTION","size":2880} {"code":"import itertools\nfrom collections.abc import Callable, Iterable\n\nfrom puya import log\nfrom puya.ir import models\nfrom puya.ir.context import TMP_VAR_INDICATOR\n\nlogger = log.get_logger(__name__)\n\n\ndef sequentialize_parallel_copies(sub: models.Subroutine) -> None:\n logger.debug(f\"Sequentializing parallel copies in {sub.id}\")\n our_tmp_prefix = f\"parcopy{TMP_VAR_INDICATOR}\"\n max_tmp_id = max(\n (\n int(r.name.split(TMP_VAR_INDICATOR)[1])\n for r in sub.get_assigned_registers()\n if r.name.startswith(our_tmp_prefix)\n ),\n default=-1,\n )\n next_tmp_id = itertools.count(max_tmp_id + 1)\n\n def make_temp(x: models.Value | models.Register) -> models.Register:\n return models.Register(\n ir_type=x.ir_type,\n name=f\"{our_tmp_prefix}{next(next_tmp_id)}\",\n version=0,\n source_location=x.source_location,\n )\n\n for block in sub.body:\n ops = list[models.Op]()\n for op in block.ops:\n match op:\n case models.Assignment(targets=targets, source=models.ValueTuple(values=sources)):\n seqd = _sequentialize(zip(targets, sources, strict=True), mktmp=make_temp)\n for dst, src in seqd:\n assert isinstance(dst, models.Register) # TODO: this is bad\n ops.append(\n models.Assignment(\n targets=[dst],\n source=src,\n source_location=op.source_location,\n )\n )\n case _:\n ops.append(op)\n block.ops = ops\n\n\ndef _sequentialize[T](\n copies: Iterable[tuple[T, T]],\n mktmp: Callable[[T], T],\n *,\n filter_dup_dests: bool = True,\n allow_fan_out: bool = True,\n) -> list[tuple[T, T]]:\n # If filter_dup_dests is True, consider pairs ordered, and if multiple\n # pairs have the same dest var, the last one takes effect. Otherwise,\n # such duplicate dest vars is an error.\n if filter_dup_dests:\n # If there're multiple assignments to the same var, keep only the latest\n copies = list(dict(copies).items())\n\n ready = []\n to_do = []\n pred = {}\n loc = dict[T, T | None]()\n res = []\n\n for b, _ in copies:\n loc[b] = None\n\n for b, a in copies:\n loc[a] = a\n pred[b] = a\n\n # Extra check\n if not filter_dup_dests and b in to_do:\n raise ValueError(f\"Conflicting assignments to destination {b}, latest: {(b, a)}\")\n\n to_do.append(b)\n\n for b, _ in copies:\n if loc[b] is None:\n ready.append(b)\n\n logger.debug(\"loc: %s\", \"{\" + \", \".join(f\"{k}={v}\" for k, v in loc.items()) + \"}\")\n logger.debug(\"pred: %s\", \"{\" + \", \".join(f\"{k}={v}\" for k, v in pred.items()) + \"}\")\n logger.debug(\"ready: %s\", \", \".join(map(str, ready)))\n logger.debug(\"to_do: %s\", \", \".join(map(str, to_do)))\n\n while to_do:\n while ready:\n b = ready.pop()\n logger.debug(\"* avail %s\", b)\n if b not in pred:\n continue\n a = pred[b]\n c = loc[a]\n assert c is not None\n # print(\"%s <- %s\" % (b, a))\n res.append((b, c))\n\n # Addition by Paul Sokolovsky to handle fan-out case (when same\n # source is assigned to multiple destinations).\n if allow_fan_out and c in to_do:\n to_do.remove(c)\n\n loc[a] = b\n if a == c:\n ready.append(a)\n\n # Addition to handle fan-out.\n if allow_fan_out and not to_do:\n break\n\n b = to_do.pop()\n logger.debug(\"* to_do %s\", b)\n if b != loc[pred[b]]:\n tmp = mktmp(b)\n # print(\"%s <- %s\" % (b, a))\n res.append((tmp, b))\n loc[b] = tmp\n ready.append(b)\n\n return res\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/destructure\/parcopy.py","language":"Python","license":"NOASSERTION","size":3997} {"code":"from puya import log\nfrom puya.ir import models\nfrom puya.ir.visitor_mem_replacer import MemoryReplacer\n\nlogger = log.get_logger(__name__)\n\n\ndef convert_to_cssa(sub: models.Subroutine) -> None:\n logger.debug(\"Converting to CSSA\")\n max_versions = dict[str, int]()\n for reg in sub.get_assigned_registers():\n max_versions[reg.name] = max(max_versions.get(reg.name, 0), reg.version)\n\n def make_prime(mem: models.Register) -> models.Register:\n max_versions[mem.name] += 1\n return models.Register(\n source_location=mem.source_location,\n ir_type=mem.ir_type,\n name=mem.name,\n version=max_versions[mem.name],\n )\n\n block_exit_copies = dict[models.BasicBlock, list[tuple[models.Register, models.Register]]]()\n for phi_block in sub.body:\n prime_phis = list[models.Phi]()\n prime_copies = list[tuple[models.Register, models.Register]]()\n for phi in phi_block.phis:\n if not phi.args:\n phi_block.ops.insert(\n 0,\n models.Assignment(\n targets=[phi.register],\n source=models.Undefined(\n ir_type=phi.ir_type, source_location=phi.source_location\n ),\n source_location=phi.source_location,\n ),\n )\n else:\n prime_args = list[models.PhiArgument]()\n for phi_arg in phi.args:\n prime_arg_reg = make_prime(phi_arg.value)\n prime_arg = models.PhiArgument(\n value=prime_arg_reg,\n through=phi_arg.through,\n )\n prime_args.append(prime_arg)\n # insert copy to prime arg at end of predecessor\n block_exit_copies.setdefault(phi_arg.through, []).append(\n (prime_arg_reg, phi_arg.value)\n )\n phi_prime = models.Phi(register=make_prime(phi.register), args=prime_args)\n prime_phis.append(phi_prime)\n prime_copies.append((phi.register, phi_prime.register))\n phi_block.phis = prime_phis\n if prime_copies:\n phi_block.ops.insert(0, _make_copy_assignment(prime_copies))\n\n for block, copies in block_exit_copies.items():\n block.ops.append(_make_copy_assignment(copies))\n\n\ndef _make_copy_assignment(\n copies: list[tuple[models.Register, models.Register]],\n) -> models.Assignment:\n if len(copies) == 1:\n ((dst, src),) = copies\n targets = [dst]\n source: models.ValueProvider = src\n else:\n targets_tup, sources_tup = zip(*copies, strict=True)\n targets = list(targets_tup)\n sources_list = list(sources_tup)\n source = models.ValueTuple(source_location=None, values=sources_list)\n return models.Assignment(\n targets=targets,\n source=source,\n source_location=None,\n )\n\n\ndef destructure_cssa(sub: models.Subroutine) -> None:\n logger.debug(\"Removing Phi nodes\")\n # Once the sub is in CSSA, destructuring is trivial.\n # All variables involved in a Phi can be given the same name, and the Phi can be removed.\n replacements = dict[models.Register, models.Register]()\n for block in sub.body:\n phis = block.phis\n block.phis = []\n replacements.update({arg.value: phi.register for phi in phis for arg in phi.args})\n MemoryReplacer.apply(sub.body, replacements=replacements)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/destructure\/remove_phi.py","language":"Python","license":"NOASSERTION","size":3583} {"code":"from puya.ir.avm_ops import AVMOp\nfrom puya.ir.models import Intrinsic, Value\nfrom puya.ir.types_ import IRType\nfrom puya.parse import SourceLocation\n\n\ndef select(\n *, condition: Value, false: Value, true: Value, type_: IRType, source_location: SourceLocation\n) -> Intrinsic:\n return Intrinsic(\n op=AVMOp.select,\n args=[\n false,\n true,\n condition,\n ],\n types=[type_],\n source_location=source_location,\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/intrinsic_factory.py","language":"Python","license":"NOASSERTION","size":482} {"code":"import contextlib\nimport copy\nimport typing\nfrom collections import defaultdict\nfrom collections.abc import Collection, Iterator\nfrom pathlib import Path\n\nfrom immutabledict import immutabledict\n\nfrom puya import artifact_metadata, log\nfrom puya.avm import AVMType\nfrom puya.awst import nodes as awst_nodes\nfrom puya.awst.awst_traverser import AWSTTraverser\nfrom puya.awst.function_traverser import FunctionTraverser\nfrom puya.awst.serialize import awst_from_json\nfrom puya.context import CompileContext\nfrom puya.ir import arc4_router\nfrom puya.ir._contract_metadata import build_contract_metadata\nfrom puya.ir._utils import make_subroutine\nfrom puya.ir.arc4_router import AWSTContractMethodSignature\nfrom puya.ir.builder.main import FunctionIRBuilder\nfrom puya.ir.context import IRBuildContext\nfrom puya.ir.models import Contract, LogicSignature, ModuleArtifact, Program, Subroutine\nfrom puya.ir.optimize.dead_code_elimination import remove_unused_subroutines\nfrom puya.ir.types_ import wtype_to_ir_type\nfrom puya.program_refs import ProgramKind\nfrom puya.utils import StableSet, attrs_extend, coalesce, set_add, set_remove\n\nlogger = log.get_logger(__name__)\n\n\nCalleesLookup: typing.TypeAlias = defaultdict[awst_nodes.Function, set[awst_nodes.Function]]\n_EMBEDDED_LIB = Path(__file__).parent \/ \"_puya_lib.awst.json\"\n\n\ndef awst_to_ir(context: CompileContext, awst: awst_nodes.AWST) -> Iterator[ModuleArtifact]:\n compilation_set = _CompilationSetCollector.collect(context, awst)\n\n ir_ctx = _build_subroutines(context, awst)\n\n for node in compilation_set:\n artifact_ctx = ir_ctx.for_root(node)\n with artifact_ctx.log_exceptions():\n if isinstance(node, awst_nodes.LogicSignature):\n yield _build_logic_sig_ir(artifact_ctx, node)\n else:\n yield _build_contract_ir(artifact_ctx, node)\n\n\ndef _build_subroutines(ctx: CompileContext, awst: awst_nodes.AWST) -> IRBuildContext:\n embedded_awst = awst_from_json(_EMBEDDED_LIB.read_text())\n embedded_subroutines = {\n node: make_subroutine(node, allow_implicits=False)\n for node in embedded_awst\n if isinstance(node, awst_nodes.Subroutine)\n }\n user_subroutines = {\n node: make_subroutine(node, allow_implicits=True)\n for node in awst\n if isinstance(node, awst_nodes.Subroutine)\n }\n ir_ctx = attrs_extend(\n IRBuildContext,\n ctx,\n subroutines={**embedded_subroutines, **user_subroutines},\n awst=[*embedded_awst, *awst],\n embedded_funcs_lookup={func.id: sub for func, sub in embedded_subroutines.items()},\n )\n for func, sub in ir_ctx.subroutines.items():\n FunctionIRBuilder.build_body(ir_ctx, function=func, subroutine=sub)\n return ir_ctx\n\n\nclass _CompilationSetCollector(AWSTTraverser):\n def __init__(self, awst: awst_nodes.AWST, *, explicit_compilation_set: StableSet[str]) -> None:\n super().__init__()\n self._remaining_explicit_set: typing.Final = explicit_compilation_set\n self.compilation_set: typing.Final = dict[\n str, awst_nodes.Contract | awst_nodes.LogicSignature\n ]()\n self._nodes_by_id: typing.Final = immutabledict[str, awst_nodes.RootNode](\n {n.id: n for n in awst}\n )\n\n @property\n def unresolved_explict_ids(self) -> Collection[str]:\n return self._remaining_explicit_set\n\n @classmethod\n def collect(\n cls, context: CompileContext, awst: awst_nodes.AWST\n ) -> Collection[awst_nodes.Contract | awst_nodes.LogicSignature]:\n collector = cls(\n awst, explicit_compilation_set=StableSet.from_iter(context.compilation_set)\n )\n for node in awst:\n node.accept(collector)\n for unresolved_id in collector.unresolved_explict_ids:\n logger.error(f\"unable to resolve compilation artifact '{unresolved_id}'\")\n return collector.compilation_set.values()\n\n def visit_compiled_contract(self, compiled_contract: awst_nodes.CompiledContract) -> None:\n super().visit_compiled_contract(compiled_contract)\n node = self._nodes_by_id.get(compiled_contract.contract)\n match node:\n case awst_nodes.Contract() as contract:\n self._visit_contract_or_lsig(contract, reference=True)\n case None:\n logger.error(\n \"unable to resolve contract reference\",\n location=compiled_contract.source_location,\n )\n case _:\n logger.error(\n \"reference is not a contract\", location=compiled_contract.source_location\n )\n\n def visit_compiled_logicsig(self, compiled_lsig: awst_nodes.CompiledLogicSig) -> None:\n super().visit_compiled_logicsig(compiled_lsig)\n node = self._nodes_by_id.get(compiled_lsig.logic_sig)\n match node:\n case awst_nodes.LogicSignature() as lsig:\n self._visit_contract_or_lsig(lsig, reference=True)\n case None:\n logger.error(\n \"unable to resolve logic signature reference\",\n location=compiled_lsig.source_location,\n )\n case _:\n logger.error(\n \"reference is not a logic signature\", location=compiled_lsig.source_location\n )\n\n def visit_contract(self, contract: awst_nodes.Contract) -> None:\n return self._visit_contract_or_lsig(contract)\n\n def visit_logic_signature(self, lsig: awst_nodes.LogicSignature) -> None:\n return self._visit_contract_or_lsig(lsig)\n\n def _visit_contract_or_lsig(\n self,\n node: awst_nodes.Contract | awst_nodes.LogicSignature,\n *,\n reference: bool = False,\n ) -> None:\n if node.id in self.compilation_set:\n return # already visited\n direct = set_remove(self._remaining_explicit_set, node.id)\n if direct or reference:\n self.compilation_set[node.id] = node\n match node:\n case awst_nodes.Contract():\n super().visit_contract(node)\n case awst_nodes.LogicSignature():\n super().visit_logic_signature(node)\n case unexpected:\n typing.assert_never(unexpected)\n\n\ndef _build_logic_sig_ir(\n ctx: IRBuildContext, logic_sig: awst_nodes.LogicSignature\n) -> LogicSignature:\n metadata = artifact_metadata.LogicSignatureMetaData(\n ref=logic_sig.id,\n description=logic_sig.docstring,\n name=logic_sig.short_name,\n )\n\n avm_version = coalesce(logic_sig.avm_version, ctx.options.target_avm_version)\n sig_ir = _make_program(\n ctx, logic_sig.program, kind=ProgramKind.logic_signature, avm_version=avm_version\n )\n return LogicSignature(\n program=sig_ir, metadata=metadata, source_location=logic_sig.source_location\n )\n\n\ndef _build_contract_ir(ctx: IRBuildContext, contract: awst_nodes.Contract) -> Contract:\n metadata, arc4_methods = build_contract_metadata(ctx, contract)\n routing_data = {\n md: AWSTContractMethodSignature(\n target=awst_nodes.ContractMethodTarget(cref=cm.cref, member_name=cm.member_name),\n return_type=cm.return_type,\n parameter_types=[a.wtype for a in cm.args],\n )\n for cm, md in arc4_methods.items()\n }\n arc4_router_awst = arc4_router.create_abi_router(contract, routing_data)\n ctx.routers[contract.id] = ctx.subroutines[arc4_router_awst] = make_subroutine(\n arc4_router_awst, allow_implicits=False\n )\n\n # Build callees list, excluding calls from router.\n # Used to if a function should implicitly return mutable reference parameters.\n callees = SubroutineCollector.collect(\n ctx, contract.approval_program, contract.clear_program, *arc4_methods\n )\n\n # construct unique Subroutine objects for each function\n # that was referenced through either entry point\n for method in contract.methods:\n # ABI methods which are only called by the ABI router in the approval_program do not need\n # to implicitly return anything as we know our router is not interested in anything but the\n # explicit return value.\n allow_implicits = bool(callees[method])\n # make the emtpy subroutine, because functions reference other functions\n func_ir = make_subroutine(method, allow_implicits=allow_implicits)\n ctx.subroutines[method] = func_ir\n\n # now construct the subroutine IR\n for func, sub in ctx.subroutines.items():\n if not sub.body: # in case something is pre-built (ie from embedded lib)\n FunctionIRBuilder.build_body(ctx, function=func, subroutine=sub)\n\n avm_version = coalesce(contract.avm_version, ctx.options.target_avm_version)\n approval_ir = _make_program(\n ctx, contract.approval_program, kind=ProgramKind.approval, avm_version=avm_version\n )\n clear_state_ir = _make_program(\n ctx, contract.clear_program, kind=ProgramKind.clear_state, avm_version=avm_version\n )\n return Contract(\n approval_program=approval_ir,\n clear_program=clear_state_ir,\n metadata=metadata,\n source_location=contract.source_location,\n )\n\n\ndef _make_program(\n ctx: IRBuildContext,\n main: awst_nodes.Function,\n *,\n kind: ProgramKind,\n avm_version: int,\n) -> Program:\n assert not main.args, \"main method should not have args\"\n return_type = wtype_to_ir_type(main.return_type)\n assert return_type.avm_type == AVMType.uint64, \"main method should return uint64 backed type\"\n main_sub = Subroutine(\n id=main.full_name,\n short_name=main.short_name,\n parameters=[],\n returns=[return_type],\n body=[],\n inline=False,\n source_location=main.source_location,\n )\n FunctionIRBuilder.build_body(ctx, function=main, subroutine=main_sub)\n program = Program(\n kind=kind,\n main=main_sub,\n subroutines=tuple(ctx.subroutines.values()),\n avm_version=avm_version,\n )\n remove_unused_subroutines(program)\n program = copy.deepcopy(program)\n return program\n\n\nclass SubroutineCollector(FunctionTraverser):\n def __init__(self, context: IRBuildContext, callees: CalleesLookup) -> None:\n self.context = context\n self._seen = StableSet[awst_nodes.Function]()\n self.callees = callees\n self._func_stack = list[awst_nodes.Function]()\n\n @classmethod\n def collect(cls, context: IRBuildContext, *entry_points: awst_nodes.Function) -> CalleesLookup:\n callees = CalleesLookup(set)\n collector = cls(context, callees)\n for start in entry_points:\n with collector._enter_func(start): # noqa: SLF001\n start.body.accept(collector)\n return callees\n\n @typing.override\n def visit_subroutine_call_expression(self, expr: awst_nodes.SubroutineCallExpression) -> None:\n super().visit_subroutine_call_expression(expr)\n callee = self._func_stack[-1]\n func = self.context.resolve_function_reference(\n expr.target, expr.source_location, caller=callee\n )\n self.callees[func].add(callee)\n if set_add(self._seen, func):\n with self._enter_func(func):\n func.body.accept(self)\n\n @contextlib.contextmanager\n def _enter_func(self, func: awst_nodes.Function) -> Iterator[None]:\n self._func_stack.append(func)\n try:\n yield\n finally:\n self._func_stack.pop()\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/main.py","language":"Python","license":"NOASSERTION","size":11574} {"code":"import abc\nimport typing\nimport typing as t\nfrom collections.abc import Iterable, Iterator, Mapping, Sequence, Set\n\nimport attrs\nfrom immutabledict import immutabledict\n\nfrom puya import log\nfrom puya.artifact_metadata import ContractMetaData, LogicSignatureMetaData\nfrom puya.avm import AVMType\nfrom puya.awst.txn_fields import TxnField\nfrom puya.errors import CodeError, InternalError\nfrom puya.ir.avm_ops import AVMOp\nfrom puya.ir.avm_ops_models import ImmediateKind, OpSignature, StackType, Variant\nfrom puya.ir.types_ import AVMBytesEncoding, IRType, stack_type_to_avm_type, stack_type_to_ir_type\nfrom puya.ir.visitor import IRVisitor\nfrom puya.parse import SourceLocation\nfrom puya.program_refs import (\n ContractReference,\n LogicSigReference,\n ProgramKind,\n)\nfrom puya.utils import unique\n\nlogger = log.get_logger(__name__)\n\nT = t.TypeVar(\"T\")\n\n\nclass Context(t.Protocol):\n source_location: SourceLocation | None\n\n\nclass IRVisitable(Context, abc.ABC):\n @abc.abstractmethod\n def accept(self, visitor: IRVisitor[T]) -> T: ...\n\n def __str__(self) -> str:\n from puya.ir.to_text_visitor import ToTextVisitor\n\n return self.accept(ToTextVisitor())\n\n\nclass _Freezable(abc.ABC):\n def freeze(self) -> object:\n data = self._frozen_data()\n hash(data) # check we can hash\n if data is self:\n return data\n return self.__class__, data\n\n @abc.abstractmethod\n def _frozen_data(self) -> object: ...\n\n\n# NOTE! we don't want structural equality in the IR, everything needs to have eq=False\n# the workaround to do this (trivial in Python to extend a decorator) AND have mypy\n# not complain is ... well, see for yourself:\n# https:\/\/www.attrs.org\/en\/stable\/extending.html#wrapping-the-decorator\n@attrs.define(eq=False)\nclass ValueProvider(IRVisitable, _Freezable, abc.ABC):\n \"\"\"A node that provides\/produces a value\"\"\"\n\n source_location: SourceLocation | None = attrs.field(eq=False)\n\n @property\n @abc.abstractmethod\n def types(self) -> Sequence[IRType]: ...\n\n @property\n @t.final\n def atypes(self) -> Sequence[AVMType]:\n return tuple(t.avm_type for t in self.types)\n\n\n@attrs.frozen\nclass Value(ValueProvider, abc.ABC):\n \"\"\"Base class for value types.\n\n This is anything that *is* a value, so excludes\n value *producers* such as subroutine invocations\n \"\"\"\n\n ir_type: IRType = attrs.field(repr=lambda x: x.name)\n\n @property\n @t.final\n def atype(self) -> typing.Literal[AVMType.uint64, AVMType.bytes]:\n return self.ir_type.avm_type\n\n @property\n def types(self) -> Sequence[IRType]:\n return (self.ir_type,)\n\n def _frozen_data(self) -> object:\n return self\n\n\n@attrs.frozen\nclass Undefined(Value):\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_undefined(self)\n\n\nclass Constant(Value, abc.ABC):\n \"\"\"Base class for value constants - any value that is known at compile time\"\"\"\n\n\n@attrs.define(eq=False)\nclass Op(IRVisitable, _Freezable, abc.ABC):\n \"\"\"Base class for non-control-flow, non-phi operations\n\n This is anything other than a Phi can appear inside a BasicBlock before the terminal ControlOp.\n \"\"\"\n\n\n@attrs.define(eq=False)\nclass ControlOp(IRVisitable, _Freezable, abc.ABC):\n \"\"\"Base class for control-flow operations\n\n These appear in a BasicBlock as the terminal node.\n \"\"\"\n\n source_location: SourceLocation | None\n\n @abc.abstractmethod\n def targets(self) -> Sequence[\"BasicBlock\"]:\n \"\"\"For graph traversal - result could be empty if it's the end of the current graph\"\"\"\n\n @property\n def unique_targets(self) -> list[\"BasicBlock\"]:\n return unique(self.targets())\n\n\n@attrs.frozen\nclass Register(Value):\n \"\"\"A register is an abstraction of \"local variable storage\".\n\n This could be mapped to either value on the stack or a scratch slot during code generation.\n \"\"\"\n\n name: str\n version: int\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_register(self)\n\n @property\n def local_id(self) -> str:\n return f\"{self.name}#{self.version}\"\n\n\n@attrs.define(eq=False)\nclass PhiArgument(IRVisitable):\n value: Register\n through: \"BasicBlock\"\n source_location: None = attrs.field(default=None, init=False)\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_phi_argument(self)\n\n\n@attrs.define(eq=False)\nclass Phi(IRVisitable, _Freezable):\n \"\"\"Phi nodes are oracles that, given a list of other variables, always produce the\n one that has been defined in the control flow thus far.\n\n The term phi node comes from the literature on Static Single Assignment\n \"\"\"\n\n register: Register\n args: list[PhiArgument] = attrs.field(factory=list)\n source_location: None = attrs.field(default=None, init=False)\n\n @property\n def ir_type(self) -> IRType:\n return self.register.ir_type\n\n @property\n def atype(self) -> AVMType:\n return self.ir_type.avm_type\n\n @property\n def non_self_args(self) -> Sequence[PhiArgument]:\n return tuple(a for a in self.args if a.value != self.register)\n\n def _frozen_data(self) -> object:\n return (\n self.register.freeze(),\n tuple((arg.through.id, arg.value.freeze()) for arg in self.args),\n )\n\n @args.validator\n def check_args(self, _attribute: object, args: Sequence[PhiArgument]) -> None:\n bad_args = [\n arg for arg in args if arg.value.ir_type.maybe_avm_type != self.ir_type.maybe_avm_type\n ]\n if bad_args:\n raise InternalError(\n f\"Phi node (register={self.register}) received arguments with unexpected type(s):\"\n f\" {', '.join(map(str, bad_args))}, \"\n )\n seen_blocks = set[BasicBlock]()\n for arg in args:\n if arg.through in seen_blocks:\n raise InternalError(f\"Duplicate source to phi node: {arg.through}\")\n seen_blocks.add(arg.through)\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_phi(self)\n\n\n@attrs.frozen(kw_only=True)\nclass UInt64Constant(Constant):\n value: int\n ir_type: IRType = attrs.field(default=IRType.uint64)\n teal_alias: str | None = None\n\n @ir_type.validator\n def _validate_ir_type(self, _attribute: object, ir_type: IRType) -> None:\n if ir_type.maybe_avm_type is not AVMType.uint64:\n raise InternalError(\n f\"Invalid type for UInt64Constant: {ir_type}\", self.source_location\n )\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_uint64_constant(self)\n\n\n@attrs.frozen(kw_only=True)\nclass ITxnConstant(Constant):\n value: int\n ir_type: IRType = attrs.field()\n\n @ir_type.validator\n def _validate_ir_type(self, _attribute: object, ir_type: IRType) -> None:\n if ir_type not in (IRType.itxn_group_idx, IRType.itxn_field_set):\n raise InternalError(f\"invalid type for ITxnConstant: {ir_type}\", self.source_location)\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_itxn_constant(self)\n\n\n@attrs.frozen\nclass BigUIntConstant(Constant):\n value: int\n ir_type: IRType = attrs.field(default=IRType.biguint, init=False)\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_biguint_constant(self)\n\n\n@attrs.frozen\nclass TemplateVar(Value):\n name: str\n ir_type: IRType\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_template_var(self)\n\n\n@attrs.frozen(kw_only=True)\nclass BytesConstant(Constant):\n \"\"\"Constant for types that are logically bytes\"\"\"\n\n ir_type: IRType = attrs.field(default=IRType.bytes)\n\n encoding: AVMBytesEncoding\n value: bytes\n\n @ir_type.validator\n def _validate_ir_type(self, _attribute: object, ir_type: IRType) -> None:\n if ir_type.maybe_avm_type is not AVMType.bytes:\n raise InternalError(f\"invalid type for BytesConstant: {ir_type}\", self.source_location)\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_bytes_constant(self)\n\n\n@attrs.define\nclass CompiledContractReference(Value):\n artifact: ContractReference\n field: TxnField\n template_variables: Mapping[str, Value] = attrs.field(converter=immutabledict)\n \"\"\"\n template variable keys here are fully qualified with their appropriate prefix\n \"\"\"\n source_location: SourceLocation | None = attrs.field(eq=False)\n program_page: int | None = None # used for approval and clear_state fields\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_compiled_contract_reference(self)\n\n\n@attrs.define\nclass CompiledLogicSigReference(Value):\n artifact: LogicSigReference\n template_variables: Mapping[str, Value] = attrs.field(converter=immutabledict)\n source_location: SourceLocation | None = attrs.field(eq=False)\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_compiled_logicsig_reference(self)\n\n\n@attrs.frozen\nclass AddressConstant(Constant):\n \"\"\"Constant for address literals\"\"\"\n\n ir_type: IRType = attrs.field(default=IRType.bytes, init=False)\n value: str = attrs.field()\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_address_constant(self)\n\n\n@attrs.frozen\nclass MethodConstant(Constant):\n \"\"\"Constant for method literals\"\"\"\n\n ir_type: IRType = attrs.field(default=IRType.bytes, init=False)\n value: str\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_method_constant(self)\n\n\n@attrs.define(eq=False)\nclass InnerTransactionField(ValueProvider):\n field: str\n group_index: Value\n is_last_in_group: Value\n array_index: Value | None\n type: IRType\n\n def _frozen_data(self) -> object:\n return self.field, self.group_index, self.is_last_in_group, self.array_index, self.type\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_inner_transaction_field(self)\n\n @property\n def types(self) -> Sequence[IRType]:\n return (self.type,)\n\n\n@attrs.define(eq=False)\nclass Intrinsic(Op, ValueProvider):\n \"\"\"Any TEAL op (or pseudo-op) that doesn't interrupt control flow, in the \"basic block\" sense.\n\n refs:\n - https:\/\/developer.algorand.org\/docs\/get-details\/dapps\/avm\/teal\/opcodes\/\n - https:\/\/developer.algorand.org\/docs\/get-details\/dapps\/avm\/teal\/specification\/#assembler-syntax\n \"\"\"\n\n op: AVMOp\n # TODO: consider treating ops with no args (only immediates) as Value types\n # e.g. `txn NumAppArgs` or `txna ApplicationArgs 0`\n immediates: list[str | int] = attrs.field(factory=list)\n args: list[Value] = attrs.field(factory=list)\n error_message: str | None = None\n \"\"\"If the program fails at this op, error_message will be displayed as the reason\"\"\"\n _types: Sequence[IRType] = attrs.field(converter=tuple[IRType, ...])\n\n @_types.default\n def _default_types(self) -> tuple[IRType, ...]:\n types = list[IRType]()\n for stack_type in self.op_signature.returns:\n ir_type = stack_type_to_ir_type(stack_type)\n if ir_type is None:\n raise InternalError(\n f\"Intrinsic op {self.op.name} requires return type information\",\n self.source_location,\n )\n types.append(ir_type)\n return tuple(types)\n\n def _frozen_data(self) -> object:\n return self.op, tuple(self.immediates), tuple(self.args), self.error_message\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_intrinsic_op(self)\n\n @property\n def types(self) -> Sequence[IRType]:\n return self._types\n\n @property\n def op_signature(self) -> OpSignature:\n return self.op_variant.signature\n\n @property\n def op_variant(self) -> Variant:\n return self.op.get_variant(self.immediates)\n\n @_types.validator\n def _validate_types(self, _attribute: object, types: Sequence[IRType]) -> None:\n self._check_stack_types(\"return\", self.op_signature.returns, types)\n\n @args.validator\n def _validate_args(self, _attribute: object, args: list[Value]) -> None:\n arg_types = [a.ir_type for a in args]\n self._check_stack_types(\"argument\", self.op_signature.args, arg_types)\n\n @immediates.validator\n def _validate_immediates(self, _attribute: object, immediates: list[int | str]) -> None:\n if len(self.op.immediate_types) != len(immediates):\n logger.error(\"Incorrect number of immediates\", location=self.source_location)\n return\n for imm_type, imm in zip(self.op.immediate_types, immediates, strict=True):\n match imm_type:\n case ImmediateKind.uint8:\n if not isinstance(imm, int) or not (0 <= imm <= 255):\n logger.critical(\n \"Invalid immediate, expected value between 0 and 255\",\n location=self.source_location,\n )\n case ImmediateKind.arg_enum:\n if not isinstance(imm, str):\n logger.critical(\n \"Invalid immediate, expected enum value\",\n location=self.source_location,\n )\n case _:\n typing.assert_never(imm_type)\n\n def _check_stack_types(\n self,\n context: str,\n expected_types: Sequence[StackType],\n source_types: Sequence[IRType],\n ) -> None:\n target_types = [stack_type_to_avm_type(a) for a in expected_types]\n if len(target_types) != len(source_types) or not all(\n tt & st.avm_type for tt, st in zip(target_types, source_types, strict=True)\n ):\n logger.error(\n (\n f\"Incompatible {context} types on Intrinsic\"\n f\"({self.op} {' '.join(map(str, self.immediates))}): \"\n f\" received = ({', '.join(map(str, source_types))}),\"\n f\" expected = ({', '.join(map(str, target_types))})\"\n ),\n location=self.source_location,\n )\n\n\n@attrs.define(eq=False)\nclass InvokeSubroutine(Op, ValueProvider):\n \"\"\"Subroutine invocation\n\n opcode: callsub\"\"\"\n\n target: \"Subroutine\"\n # TODO: validation for args\n args: list[Value]\n\n def _frozen_data(self) -> object:\n return self.target.id, tuple(self.args)\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_invoke_subroutine(self)\n\n @property\n def types(self) -> Sequence[IRType]:\n return self.target.returns\n\n\n@attrs.define(eq=False)\nclass ValueTuple(ValueProvider):\n values: Sequence[Value]\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_value_tuple(self)\n\n @property\n def types(self) -> Sequence[IRType]:\n return [val.ir_type for val in self.values]\n\n def _frozen_data(self) -> object:\n return tuple(self.values)\n\n\n@attrs.define(eq=False)\nclass Assignment(Op):\n \"\"\"\n Assignment of either a value or the result of something that produces a value to register(s)\n \"\"\"\n\n source_location: SourceLocation | None\n targets: Sequence[Register] = attrs.field(\n validator=[attrs.validators.min_len(1)], converter=tuple[Register, ...]\n )\n source: ValueProvider = attrs.field()\n\n def _frozen_data(self) -> object:\n return tuple(self.targets), self.source.freeze()\n\n @source.validator\n def _check_types(self, _attribute: object, source: ValueProvider) -> None:\n target_ir_types = [target.ir_type for target in self.targets]\n source_ir_types = list(source.types)\n if target_ir_types != source_ir_types:\n # TODO: need to update some optimiser code and\/or\n # introduce ReinterpretCast ValueProvider\n # here before we can remove this fallback to AVMType here\n target_atypes = [tt.maybe_avm_type for tt in target_ir_types]\n source_atypes = [st.maybe_avm_type for st in source_ir_types]\n if target_atypes != source_atypes:\n raise CodeError(\n f\"Incompatible types on assignment:\"\n f\" source = ({', '.join(map(str, source_ir_types))}),\"\n f\" target = ({', '.join(map(str, target_ir_types))})\",\n self.source_location,\n )\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_assignment(self)\n\n\n@attrs.define(eq=False, str=False, kw_only=True)\nclass BasicBlock(Context):\n \"\"\"IR basic block.\n\n Contains a sequence of operations and ends with a terminating ControlOp.\n Only the last op can be a 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 Subroutine or program main.\n\n Ops that may terminate the program due to a panic or similar aren't treated as exits.\n \"\"\"\n\n source_location: SourceLocation # the location that caused the block to be constructed\n phis: list[Phi] = attrs.field(factory=list)\n ops: list[Op] = attrs.field(factory=list)\n terminator: ControlOp | None = attrs.field(default=None)\n predecessors: \"list[BasicBlock]\" = attrs.field(factory=list)\n id: int | None = None\n label: str | None = None\n comment: str | None = None\n\n @phis.validator\n def _check_phis(self, _attribute: object, phis: list[Phi]) -> None:\n for phi in phis:\n attrs.validate(phi)\n\n @ops.validator\n def _check_ops(self, _attribute: object, ops: list[Op]) -> None:\n for op in ops:\n attrs.validate(op)\n\n @terminator.validator\n def _check_terminator(self, _attribute: object, terminator: ControlOp | None) -> None:\n if terminator is not None:\n attrs.validate(terminator)\n\n @property\n def terminated(self) -> bool:\n return self.terminator is not None\n\n @property\n def successors(self) -> \"Sequence[BasicBlock]\":\n if self.terminator is None:\n return ()\n return self.terminator.unique_targets\n\n @property\n def is_empty(self) -> bool:\n return not (self.phis or self.ops or self.terminator)\n\n @property\n def all_ops(self) -> Iterator[Phi | Op | ControlOp]:\n yield from self.phis.copy()\n yield from self.ops.copy() # copy in case ops is modified\n if self.terminator is not None:\n yield self.terminator\n\n def get_assigned_registers(self) -> Iterator[Register]:\n for phi in self.phis:\n yield phi.register\n for op in self.ops:\n if isinstance(op, Assignment):\n yield from op.targets\n\n def __str__(self) -> str:\n return f\"block@{self.id}\"\n\n\n@attrs.define(eq=False, kw_only=True)\nclass ConditionalBranch(ControlOp):\n \"\"\"Branch based on zero-ness\n\n opcode: bz+b or bnz+b\n \"\"\"\n\n condition: Value = attrs.field()\n non_zero: BasicBlock\n zero: BasicBlock\n\n def _frozen_data(self) -> object:\n return self.condition.freeze(), self.non_zero.id, self.zero.id\n\n @condition.validator\n def check(self, _attribute: object, result: Value) -> None:\n if result.atype != AVMType.uint64:\n raise CodeError(\n \"Branch condition can only be uint64 backed value\", self.source_location\n )\n\n def targets(self) -> Sequence[BasicBlock]:\n return self.zero, self.non_zero\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_conditional_branch(self)\n\n\n@attrs.define(eq=False)\nclass Goto(ControlOp):\n \"\"\"Unconditional jump\n\n opcode: b\n \"\"\"\n\n target: BasicBlock\n\n def _frozen_data(self) -> object:\n return self.target.id\n\n def targets(self) -> Sequence[BasicBlock]:\n return (self.target,)\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_goto(self)\n\n\n@attrs.define(eq=False)\nclass GotoNth(ControlOp):\n \"\"\"Jump to the nth block in a list where n is defined by a UInt16 Value.\n Jumps to the default if n is larger than the number of blocks\n\n opcode: switch+b\"\"\"\n\n value: Value\n blocks: list[BasicBlock] = attrs.field()\n default: BasicBlock\n\n def _frozen_data(self) -> object:\n return self.value, tuple(b.id for b in self.blocks), self.default.id\n\n def targets(self) -> Sequence[BasicBlock]:\n return *self.blocks, self.default\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_goto_nth(self)\n\n\n@attrs.define(eq=False)\nclass Switch(ControlOp):\n \"\"\"Jump based on comparison between a value and a fixed list of other values.\n If no match is found, jumps to \"default\". This default option doesn't exist in\n the underlying op code, but we need it to make this truly terminate the basic block\n it's in, otherwise it'd violate certain CFG constraints.\n\n opcode: match+b\n \"\"\"\n\n value: Value\n cases: dict[Value, BasicBlock] = attrs.field()\n default: BasicBlock\n\n @cases.validator\n def _check_cases(self, _attribute: object, cases: dict[Value, BasicBlock]) -> None:\n if any(case.atype != self.value.atype for case in cases):\n raise CodeError(\n \"Switch cases types mismatch with value to match\", self.source_location\n )\n\n def _frozen_data(self) -> object:\n return (\n self.value,\n tuple((v, b.id) for v, b in self.cases.items()),\n self.default.id,\n )\n\n def targets(self) -> Sequence[BasicBlock]:\n return *self.cases.values(), self.default\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_switch(self)\n\n\n@attrs.define(eq=False)\nclass SubroutineReturn(ControlOp):\n \"\"\"Return from within a subroutine\n\n opcode: retsub\n \"\"\"\n\n result: list[Value]\n\n def _frozen_data(self) -> object:\n return tuple(self.result)\n\n def targets(self) -> Sequence[BasicBlock]:\n return ()\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_subroutine_return(self)\n\n\n@attrs.define(eq=False)\nclass ProgramExit(ControlOp):\n \"\"\"Return from and exit the program immediately\n\n opcode: return\n \"\"\"\n\n result: Value = attrs.field()\n\n @result.validator\n def check(self, _attribute: object, result: Value) -> None:\n if result.atype != AVMType.uint64:\n raise CodeError(\"Can only exit with uint64 backed value\", self.source_location)\n\n def _frozen_data(self) -> object:\n return self.result\n\n def targets(self) -> Sequence[BasicBlock]:\n return ()\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_program_exit(self)\n\n\n@attrs.define(eq=False)\nclass Fail(ControlOp):\n \"\"\"Exits immediately with a failure condition.\n\n assert statements with a compile time constant that is false\n should be translated to this node type in order to become ControlOp\n\n\n opcode: err\n \"\"\"\n\n error_message: str | None\n\n def targets(self) -> Sequence[BasicBlock]:\n return ()\n\n def accept(self, visitor: IRVisitor[T]) -> T:\n return visitor.visit_fail(self)\n\n def _frozen_data(self) -> object:\n return self.error_message\n\n\n@attrs.frozen\nclass Parameter(Register):\n implicit_return: bool\n\n\n@attrs.define(eq=False, kw_only=True)\nclass Subroutine(Context):\n id: str\n short_name: str\n # source_location might be None if it was synthesized e.g. ARC4 approval method\n source_location: SourceLocation | None\n parameters: Sequence[Parameter]\n _returns: Sequence[IRType]\n body: list[BasicBlock] = attrs.field()\n inline: bool | None\n\n @property\n def returns(self) -> list[IRType]:\n return [*self._returns, *(p.ir_type for p in self.parameters if p.implicit_return)]\n\n @body.validator\n def _check_blocks(self, _attribute: object, body: list[BasicBlock]) -> None:\n blocks = frozenset(body)\n for block in body:\n attrs.validate(block)\n if block.terminator is None:\n raise InternalError(\n f\"Unterminated block {block} assigned to subroutine {self.id}\",\n block.source_location,\n )\n for successor in block.successors:\n if block not in successor.predecessors:\n # Note: this check is here rather than on BasicBlock only because of\n # circular validation issues where you're trying to update the CFG by\n # replacing a terminator\n raise InternalError(\n f\"{block} does not appear in all {block.terminator}\"\n f\" target's predecessor lists - missing from {successor.id} at least\",\n block.terminator.source_location\n or block.source_location\n or self.source_location,\n )\n if not blocks.issuperset(block.predecessors):\n raise InternalError(\n f\"{block} of subroutine {self.id} has predecessor block(s) outside of list\",\n block.source_location,\n )\n if not blocks.issuperset(block.successors):\n raise InternalError(\n f\"{block} of subroutine {self.id} has predecessor block(s) outside of list\",\n block.source_location,\n )\n block_predecessors = dict.fromkeys(block.predecessors)\n for phi in block.phis:\n phi_blocks = dict.fromkeys(a.through for a in phi.args)\n if block_predecessors.keys() != phi_blocks.keys():\n phi_block_labels = list(map(str, phi_blocks.keys()))\n pred_block_labels = list(map(str, block_predecessors.keys()))\n raise InternalError(\n f\"{self.id}: mismatch between phi predecessors ({phi_block_labels})\"\n f\" and {block} predecessors ({pred_block_labels})\"\n f\" for phi node {phi}\",\n self.source_location,\n )\n used_registers = _get_used_registers(body)\n defined_registers = frozenset(self.parameters) | frozenset(_get_assigned_registers(body))\n bad_reads = used_registers - defined_registers\n if bad_reads:\n raise InternalError(\n f\"The following variables are used but never defined:\"\n f\" {', '.join(map(str, bad_reads))}\",\n self.source_location,\n )\n\n @property\n def entry(self) -> BasicBlock:\n return self.body[0]\n\n def get_assigned_registers(self) -> Iterator[Register]:\n yield from self.parameters\n yield from _get_assigned_registers(self.body)\n\n def get_used_registers(self) -> Iterator[Register]:\n yield from _get_used_registers(self.body)\n\n def validate_with_ssa(self) -> None:\n all_assigned = set[Register]()\n for block in self.body:\n for register in block.get_assigned_registers():\n if register in all_assigned:\n raise InternalError(\n f\"SSA constraint violated:\"\n f\" {register.local_id} is assigned multiple times\"\n )\n all_assigned.add(register)\n attrs.validate(self)\n\n\ndef _get_assigned_registers(blocks: Sequence[BasicBlock]) -> Iterator[Register]:\n # TODO: replace with visitor\n for block in blocks:\n for phi in block.phis:\n yield phi.register\n for op in block.ops:\n if isinstance(op, Assignment):\n yield from op.targets\n\n\ndef _get_used_registers(blocks: Sequence[BasicBlock]) -> Set[Register]:\n from puya.ir.register_read_collector import RegisterReadCollector\n\n collector = RegisterReadCollector()\n for block in blocks:\n for op in block.all_ops:\n op.accept(collector)\n return collector.used_registers\n\n\n@attrs.define(kw_only=True, eq=False)\nclass Program(Context):\n \"\"\"An individual TEAL output unit - e.g. an approval program, clear program, lsig\"\"\"\n\n # note: main is represented as a subroutine for simplified handling,\n # but should be \"inlined\" as main contract body during codegen.\n # ie, it could be generated as subroutine \"main\" with proto 0 1,\n # and then start of contract becomes:\n #\n # callsub main\n # return\n # main:\n # proto 0 1\n # ...\n # retsub\n #\n # but, to save program size + op codes, this should be simplified to:\n # ...\n # return\n #\n # ie, just omit the subroutine header, and replace any&all retsub ops with a return instead\n kind: ProgramKind\n main: Subroutine\n subroutines: Sequence[Subroutine]\n avm_version: int\n source_location: SourceLocation | None = None\n\n def __attrs_post_init__(self) -> None:\n if self.source_location is None:\n self.source_location = self.main.source_location\n\n @property\n def all_subroutines(self) -> Iterable[Subroutine]:\n yield self.main\n yield from self.subroutines\n\n\n@attrs.define(eq=False)\nclass Contract(Context):\n source_location: SourceLocation\n approval_program: Program\n clear_program: Program\n metadata: ContractMetaData\n\n def all_subroutines(self) -> Iterable[Subroutine]:\n from itertools import chain\n\n yield from unique(\n chain(\n self.approval_program.all_subroutines,\n self.clear_program.all_subroutines,\n )\n )\n\n def all_programs(self) -> Iterable[Program]:\n return [self.approval_program, self.clear_program]\n\n\n@attrs.define(eq=False)\nclass LogicSignature(Context):\n source_location: SourceLocation\n program: Program\n metadata: LogicSignatureMetaData\n\n def all_subroutines(self) -> Iterable[Subroutine]:\n return self.program.all_subroutines\n\n def all_programs(self) -> Iterable[Program]:\n return [self.program]\n\n\nModuleArtifact: t.TypeAlias = Contract | LogicSignature\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/models.py","language":"Python","license":"NOASSERTION","size":30346} {"code":"","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/optimize\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"from collections import Counter\nfrom functools import cached_property\n\nimport networkx as nx # type: ignore[import-untyped]\n\nfrom puya.ir import models\n\n\nclass CallGraph:\n def __init__(self, program: models.Program) -> None:\n self._program = program\n\n @cached_property\n def _graph(self) -> nx.MultiDiGraph:\n graph = nx.MultiDiGraph()\n for sub in self._program.all_subroutines:\n graph.add_node(sub.id, ref=sub)\n for sub in self._program.all_subroutines:\n for block in sub.body:\n for op in block.ops:\n match op:\n case (\n models.InvokeSubroutine(target=target)\n | models.Assignment(source=models.InvokeSubroutine(target=target))\n ):\n graph.add_edge(sub.id, target.id)\n return graph\n\n @cached_property\n def _paths(self) -> dict[str, dict[str, object]]:\n return dict(nx.all_pairs_shortest_path(self._graph))\n\n def callees(self, sub: models.Subroutine) -> list[tuple[str, int]]:\n return list(Counter(callee_id for callee_id, _ in self._graph.in_edges(sub.id)).items())\n\n def has_path(self, from_: str, to: str) -> bool:\n try:\n self._paths[from_][to]\n except KeyError:\n return False\n else:\n return True\n\n def is_auto_recursive(self, sub: models.Subroutine) -> bool:\n return bool(self._graph.has_predecessor(sub.id, sub.id))\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/optimize\/_call_graph.py","language":"Python","license":"NOASSERTION","size":1535} {"code":"from puya.errors import InternalError\nfrom puya.ir import models\n\n\ndef get_definition(\n subroutine: models.Subroutine, register: models.Register, *, should_exist: bool = True\n) -> models.Assignment | models.Phi | None:\n if register in subroutine.parameters:\n return None\n for block in subroutine.body:\n for phi in block.phis:\n if phi.register == register:\n return phi\n for op in block.ops:\n if isinstance(op, models.Assignment) and register in op.targets:\n return op\n if should_exist:\n raise InternalError(f\"Register is not defined: {register}\", subroutine.source_location)\n return None\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/optimize\/_utils.py","language":"Python","license":"NOASSERTION","size":682} {"code":"from puya import log\nfrom puya.context import CompileContext\nfrom puya.ir import models\nfrom puya.ir.context import TMP_VAR_INDICATOR\nfrom puya.ir.visitor_mem_replacer import MemoryReplacer\n\nlogger = log.get_logger(__name__)\n\n\ndef copy_propagation(_context: CompileContext, subroutine: models.Subroutine) -> bool:\n set_lookup = dict[models.Register, list[models.Register]]()\n all_equivalence_sets = list[list[models.Register]]()\n\n modified = False\n for block in subroutine.body:\n for op in block.ops.copy():\n match op:\n case models.Assignment(targets=[target], source=models.Register() as source):\n try:\n equiv_set = set_lookup[source]\n assert source in equiv_set\n except KeyError:\n set_lookup[source] = equiv_set = [source]\n all_equivalence_sets.append(equiv_set)\n equiv_set.append(target)\n set_lookup[target] = equiv_set\n block.ops.remove(op)\n modified = True\n\n replacements = dict[models.Register, models.Register]()\n for equivalence_set in all_equivalence_sets:\n assert len(equivalence_set) >= 2\n equiv_set_ids = \", \".join(x.local_id for x in equivalence_set)\n logger.debug(f\"Found equivalence set: {equiv_set_ids}\")\n for reg in equivalence_set:\n if TMP_VAR_INDICATOR not in reg.name:\n replacement = reg\n break\n else:\n replacement = equivalence_set[0]\n for r in equivalence_set:\n if r is not replacement:\n replacements[r] = replacement\n\n for block in subroutine.body:\n for phi in block.phis.copy():\n try:\n (single_register,) = {replacements.get(arg.value, arg.value) for arg in phi.args}\n except ValueError:\n continue\n else:\n replacements[phi.register] = single_register\n block.phis.remove(phi)\n modified = True\n replaced = MemoryReplacer.apply(subroutine.body, replacements=replacements)\n if replaced:\n logger.debug(f\"Copy propagation made {replaced} modifications\")\n modified = True\n\n return modified\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/optimize\/assignments.py","language":"Python","license":"NOASSERTION","size":2325} {"code":"import contextlib\nimport itertools\nfrom collections.abc import Iterable\n\nimport attrs\n\nfrom puya import log\nfrom puya.context import CompileContext\nfrom puya.ir import models\nfrom puya.ir.visitor_mutator import IRMutator\nfrom puya.utils import unique\n\nlogger = log.get_logger(__name__)\n\n\n@attrs.define\nclass BlockReferenceReplacer(IRMutator):\n find: models.BasicBlock\n replacement: models.BasicBlock\n\n @classmethod\n def apply(\n cls,\n find: models.BasicBlock,\n replacement: models.BasicBlock,\n blocks: Iterable[models.BasicBlock],\n ) -> None:\n replacer = cls(find=find, replacement=replacement)\n for block in blocks:\n replacer.visit_block(block)\n\n def visit_block(self, block: models.BasicBlock) -> None:\n super().visit_block(block)\n if self.find in block.predecessors:\n block.predecessors = [\n self.replacement if b is self.find else b for b in block.predecessors\n ]\n logger.debug(f\"Replaced predecessor {self.find} with {self.replacement} in {block}\")\n\n def visit_phi_argument(self, arg: models.PhiArgument) -> models.PhiArgument:\n if arg.through == self.find:\n arg.through = self.replacement\n return arg\n\n def visit_conditional_branch(self, branch: models.ConditionalBranch) -> models.ControlOp:\n if branch.zero == self.find:\n branch.zero = self.replacement\n if branch.non_zero == self.find:\n branch.non_zero = self.replacement\n return _replace_single_target_with_goto(branch)\n\n def visit_goto(self, goto: models.Goto) -> models.Goto:\n if goto.target == self.find:\n goto.target = self.replacement\n return goto\n\n def visit_goto_nth(self, goto_nth: models.GotoNth) -> models.ControlOp:\n for index, block in enumerate(goto_nth.blocks):\n if block == self.find:\n goto_nth.blocks[index] = self.replacement\n if goto_nth.default == self.find:\n goto_nth.default = self.replacement\n return _replace_single_target_with_goto(goto_nth)\n\n def visit_switch(self, switch: models.Switch) -> models.ControlOp:\n for case, target in switch.cases.items():\n if target == self.find:\n switch.cases[case] = self.replacement\n if switch.default == self.find:\n switch.default = self.replacement\n return _replace_single_target_with_goto(switch)\n\n\ndef _replace_single_target_with_goto(terminator: models.ControlOp) -> models.ControlOp:\n \"\"\"\n If a ControlOp has a single target, replace it with a Goto, otherwise return the original op.\n \"\"\"\n match terminator:\n case models.ControlOp(unique_targets=[single_target]):\n replacement = models.Goto(\n source_location=terminator.source_location,\n target=single_target,\n )\n logger.debug(f\"replaced {terminator} with {replacement}\")\n return replacement\n case _:\n return terminator\n\n\ndef remove_linear_jump(_context: CompileContext, subroutine: models.Subroutine) -> bool:\n changes = False\n for block in subroutine.body[1:]:\n match block.predecessors:\n case [models.BasicBlock(terminator=models.Goto(target=successor)) as predecessor]:\n assert successor is block\n # can merge blocks when there is an unconditional jump between them\n predecessor.phis.extend(block.phis)\n predecessor.ops.extend(block.ops)\n\n # this will update the predecessors of all block.successors to\n # now point back to predecessor e.g.\n # predecessor <-> block <-> [ss1, ...]\n # predecessor <-> [ss1, ...]\n BlockReferenceReplacer.apply(\n find=block, replacement=predecessor, blocks=block.successors\n )\n\n predecessor.terminator = block.terminator\n\n # update block to reflect modifications\n subroutine.body.remove(block)\n changes = True\n logger.debug(f\"Merged linear {block} into {predecessor}\")\n return changes\n\n\ndef remove_empty_blocks(_context: CompileContext, subroutine: models.Subroutine) -> bool:\n changes = False\n for block in subroutine.body.copy():\n if not block.phis and not block.ops and isinstance(block.terminator, models.Goto):\n empty_block = block\n target = block.terminator.target\n\n if target.phis:\n logger.debug(\n f\"Not removing empty block {empty_block} because it's used by phi nodes\"\n )\n continue\n\n # this will replace any ops that pointed to block\n BlockReferenceReplacer.apply(\n find=empty_block,\n replacement=target,\n blocks=empty_block.predecessors,\n )\n\n # remove the empty block from the targets predecessors, and add and of the empty block\n # predecessors that aren't already present\n target.predecessors = unique(\n itertools.chain(empty_block.predecessors, target.predecessors)\n )\n # might have already been replaced by BlockReferenceReplacer\n with contextlib.suppress(ValueError):\n target.predecessors.remove(empty_block)\n\n if empty_block is subroutine.body[0]:\n # place target at start of body so it's now the new entry block\n subroutine.body.remove(target)\n subroutine.body.insert(0, target)\n subroutine.body.remove(empty_block)\n changes = True\n logger.debug(f\"Removed empty block: {empty_block}\")\n return changes\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/optimize\/collapse_blocks.py","language":"Python","license":"NOASSERTION","size":5841} {"code":"\"\"\"\nThe compiled reference replacement is part of the optimizer pipeline for two reasons:\n\n1.) It relies on any template variables provided being optimized into constant values\n2.) Once compiled references are replaced there are additional optimizations that can occur\n\"\"\"\n\nimport typing\nfrom collections.abc import Mapping\n\nimport attrs\nfrom immutabledict import immutabledict\n\nfrom puya import log\nfrom puya.algo_constants import HASH_PREFIX_PROGRAM, MAX_BYTES_LENGTH\nfrom puya.awst.txn_fields import TxnField\nfrom puya.compilation_artifacts import TemplateValue\nfrom puya.context import ArtifactCompileContext\nfrom puya.errors import CodeError, InternalError\nfrom puya.ir import models as ir\nfrom puya.ir.types_ import AVMBytesEncoding\nfrom puya.ir.visitor_mutator import IRMutator\nfrom puya.program_refs import ProgramKind\nfrom puya.utils import (\n Address,\n biguint_bytes_eval,\n calculate_extra_program_pages,\n method_selector_hash,\n sha512_256_hash,\n)\n\nlogger = log.get_logger(__name__)\n\n\ndef replace_compiled_references(\n context: ArtifactCompileContext, subroutine: ir.Subroutine\n) -> bool:\n replacer = CompiledReferenceReplacer(context)\n for block in subroutine.body:\n replacer.visit_block(block)\n return replacer.modified\n\n\n@attrs.define\nclass CompiledReferenceReplacer(IRMutator):\n context: ArtifactCompileContext\n modified: bool = False\n\n def visit_compiled_logicsig_reference( # type: ignore[override]\n self,\n const: ir.CompiledLogicSigReference,\n ) -> ir.CompiledLogicSigReference | ir.Constant:\n if not _is_constant(const.template_variables):\n return const\n template_constants = _get_template_constants(const.template_variables)\n program_bytecode = self.context.build_program_bytecode(\n const.artifact, ProgramKind.logic_signature, template_constants=template_constants\n )\n address_public_key = sha512_256_hash(HASH_PREFIX_PROGRAM + program_bytecode)\n return ir.AddressConstant(\n value=Address.from_public_key(address_public_key).address,\n source_location=const.source_location,\n )\n\n def visit_compiled_contract_reference( # type: ignore[override]\n self,\n const: ir.CompiledContractReference,\n ) -> ir.CompiledContractReference | ir.Constant:\n field = const.field\n if field in (\n TxnField.GlobalNumUint,\n TxnField.GlobalNumByteSlice,\n TxnField.LocalNumUint,\n TxnField.LocalNumByteSlice,\n ):\n state_total = self.context.get_state_totals(const.artifact)\n match field:\n case TxnField.GlobalNumUint:\n total = state_total.global_uints\n case TxnField.GlobalNumByteSlice:\n total = state_total.global_bytes\n case TxnField.LocalNumUint:\n total = state_total.local_uints\n case TxnField.LocalNumByteSlice:\n total = state_total.local_bytes\n case _:\n raise InternalError(\n f\"Invalid state total field: {field.name}\", const.source_location\n )\n return ir.UInt64Constant(\n value=total,\n source_location=const.source_location,\n )\n\n if not _is_constant(const.template_variables):\n return const\n template_constants = _get_template_constants(const.template_variables)\n match field:\n case TxnField.ApprovalProgramPages | TxnField.ClearStateProgramPages:\n page = const.program_page\n if page is None:\n raise InternalError(\"expected non-none value for page\", const.source_location)\n program_bytecode = self.context.build_program_bytecode(\n const.artifact,\n (\n ProgramKind.approval\n if field == TxnField.ApprovalProgramPages\n else ProgramKind.clear_state\n ),\n template_constants=template_constants,\n )\n program_page = program_bytecode[\n page * MAX_BYTES_LENGTH : (page + 1) * MAX_BYTES_LENGTH\n ]\n return ir.BytesConstant(\n value=program_page,\n encoding=AVMBytesEncoding.base64,\n source_location=const.source_location,\n )\n case TxnField.ExtraProgramPages:\n approval_bytecode = self.context.build_program_bytecode(\n const.artifact, ProgramKind.approval, template_constants=template_constants\n )\n clear_bytecode = self.context.build_program_bytecode(\n const.artifact, ProgramKind.clear_state, template_constants=template_constants\n )\n return ir.UInt64Constant(\n value=calculate_extra_program_pages(\n len(approval_bytecode), len(clear_bytecode)\n ),\n source_location=const.source_location,\n )\n raise InternalError(\n f\"Unhandled compiled reference field: {field.name}\", const.source_location\n )\n\n\ndef _is_constant(\n template_variables: Mapping[str, ir.Value],\n) -> typing.TypeGuard[Mapping[str, ir.Constant]]:\n return all(isinstance(var, ir.Constant) for var in template_variables.values())\n\n\ndef _get_template_constants(\n template_variables: Mapping[str, ir.Constant],\n) -> immutabledict[str, TemplateValue]:\n result = {\n var: (_extract_constant_value(value), value.source_location)\n for var, value in template_variables.items()\n }\n return immutabledict(result)\n\n\ndef _extract_constant_value(value: ir.Constant) -> int | bytes:\n match value:\n case ir.UInt64Constant(value=int_value):\n return int_value\n case ir.BytesConstant(value=bytes_value):\n return bytes_value\n case ir.BigUIntConstant(value=biguint):\n return biguint_bytes_eval(biguint)\n case ir.AddressConstant(value=addr):\n address = Address.parse(addr)\n return address.public_key\n case ir.MethodConstant(value=method):\n return method_selector_hash(method)\n case ir.ITxnConstant():\n raise CodeError(\n \"inner transactions cannot be used as a template variable\",\n value.source_location,\n )\n case _:\n raise InternalError(\n f\"unhandled constant type: {type(value).__name__}\",\n location=value.source_location,\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/optimize\/compiled_reference.py","language":"Python","license":"NOASSERTION","size":6777} {"code":"from collections import defaultdict\n\nimport attrs\n\nfrom puya import log\nfrom puya.context import CompileContext\nfrom puya.ir import models\nfrom puya.ir.register_read_collector import RegisterReadCollector\nfrom puya.ir.visitor_mutator import IRMutator\n\nlogger = log.get_logger(__name__)\n\n\n_AnyOp = models.Op | models.ControlOp\n\n\ndef constant_replacer(_context: CompileContext, subroutine: models.Subroutine) -> bool:\n constants = dict[models.Register, models.Constant]()\n ssa_reads = defaultdict[models.Register, list[_AnyOp]](list)\n for block in subroutine.body:\n assert block.terminator is not None\n ops: tuple[_AnyOp, ...] = (*block.ops, block.terminator)\n for op in ops:\n match op:\n case models.Assignment(targets=[register], source=models.Constant() as constant):\n constants[register] = constant\n case _:\n collector = RegisterReadCollector()\n op.accept(collector)\n for read_reg in collector.used_registers:\n ssa_reads[read_reg].append(op)\n\n modified = 0\n work_list = constants.copy()\n while work_list:\n const_reg, const_val = work_list.popitem()\n replacer = ConstantRegisterReplacer({const_reg: const_val})\n for const_read in ssa_reads[const_reg]:\n if isinstance(const_read, models.Assignment) and const_read.source == const_reg:\n (register,) = const_read.targets\n constants[register] = work_list[register] = const_val\n const_read.accept(replacer)\n modified += replacer.modified\n\n phi_replace = {\n phi.register: phi_constant\n for block in subroutine.body\n for phi in block.phis\n if (phi_constant := _get_singular_phi_constant(phi, constants)) is not None\n }\n if phi_replace:\n modified += ConstantRegisterReplacer.apply(phi_replace, to=subroutine)\n return modified > 0\n\n\ndef _get_singular_phi_constant(\n phi: models.Phi, constants: dict[models.Register, models.Constant]\n) -> models.Constant | None:\n try:\n (constant,) = {constants[phi_arg.value] for phi_arg in phi.args}\n except (KeyError, ValueError):\n return None\n else:\n return constant\n\n\n@attrs.define\nclass ConstantRegisterReplacer(IRMutator):\n constants: dict[models.Register, models.Constant]\n modified: int = 0\n\n @classmethod\n def apply(\n cls, constants: dict[models.Register, models.Constant], to: models.Subroutine\n ) -> int:\n replacer = cls(constants)\n for block in to.body:\n replacer.visit_block(block)\n return replacer.modified\n\n def visit_assignment(self, ass: models.Assignment) -> models.Assignment:\n # don't visit target(s), needs to stay as Register\n ass.source = ass.source.accept(self)\n return ass\n\n def visit_phi(self, phi: models.Phi) -> models.Phi:\n # don't visit phi nodes, needs to stay as Register\n return phi\n\n def visit_register(self, reg: models.Register) -> models.Register:\n try:\n const = self.constants[reg]\n except KeyError:\n return reg\n self.modified += 1\n return const # type: ignore[return-value]\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/optimize\/constant_propagation.py","language":"Python","license":"NOASSERTION","size":3275} {"code":"import attrs\n\nfrom puya.context import ArtifactCompileContext\n\n\n@attrs.define(kw_only=True)\nclass IROptimizationContext(ArtifactCompileContext):\n expand_all_bytes: bool\n\n inlineable_calls: set[tuple[str, str]] = attrs.field(factory=set)\n \"\"\"src -> dst pairs that can\/should be inlined\"\"\"\n constant_with_constant_args: dict[str, bool] = attrs.field(factory=dict)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/optimize\/context.py","language":"Python","license":"NOASSERTION","size":374} {"code":"import attrs\n\nfrom puya import log\nfrom puya.avm import AVMType\nfrom puya.context import CompileContext\nfrom puya.ir import models\nfrom puya.ir.avm_ops import AVMOp\nfrom puya.ir.optimize._utils import get_definition\nfrom puya.ir.ssa import TrivialPhiRemover\nfrom puya.ir.types_ import IRType\nfrom puya.utils import unique\n\nlogger = log.get_logger(__name__)\n\n\n# the ratio of default cases to all cases when a match of constant values\n# can be simplified to a goto-nth\n_SWITCH_SPARSENESS_SIMPLIFICATION_RATIO = 0.5\n\n\ndef simplify_control_ops(_context: CompileContext, subroutine: models.Subroutine) -> bool:\n changes = False\n modified_phis = []\n\n def remove_target(parent: models.BasicBlock, to_remove: models.BasicBlock) -> None:\n to_remove.predecessors.remove(parent)\n for other_phi in to_remove.phis:\n other_phi.args = [arg for arg in other_phi.args if arg.through is not parent]\n modified_phis.append(other_phi)\n\n for block in subroutine.body:\n terminator = block.terminator\n match terminator:\n case models.ProgramExit(result=models.UInt64Constant(value=0)):\n logger.debug(\"simplifying exit 0 to err\")\n block.terminator = models.Fail(\n source_location=terminator.source_location, error_message=None\n )\n case models.ConditionalBranch(\n condition=models.UInt64Constant(value=value), zero=zero, non_zero=non_zero\n ):\n logger.debug(\"simplifying conditional branch with a constant into a goto\")\n if value == 0:\n goto, other = zero, non_zero\n else:\n goto, other = non_zero, zero\n block.terminator = models.Goto(\n source_location=terminator.source_location, target=goto\n )\n if other is not goto:\n remove_target(block, other)\n case models.ConditionalBranch(\n condition=condition,\n zero=models.BasicBlock(\n phis=[], ops=[], terminator=models.Fail(error_message=fail_comment)\n ) as err_block,\n non_zero=non_zero,\n source_location=source_location,\n ):\n logger.debug(\"inlining condition branch to err block into an assert true\")\n block.ops.append(\n models.Intrinsic(\n op=AVMOp.assert_,\n args=[condition],\n error_message=fail_comment,\n source_location=source_location,\n )\n )\n block.terminator = models.Goto(target=non_zero, source_location=source_location)\n if err_block not in block.successors:\n remove_target(block, err_block)\n case models.ConditionalBranch(\n condition=models.Register() as condition,\n non_zero=models.BasicBlock(\n phis=[], ops=[], terminator=models.Fail(error_message=fail_comment)\n ) as err_block,\n zero=zero,\n source_location=source_location,\n ):\n logger.debug(\"inlining condition branch to err block into an assert false\")\n not_condition = models.Register(\n name=f\"not%{condition.name}\",\n ir_type=IRType.bool,\n version=condition.version,\n source_location=source_location,\n )\n if get_definition(subroutine, not_condition, should_exist=False) is None:\n block.ops.append(\n models.Assignment(\n targets=[not_condition],\n source=models.Intrinsic(\n op=AVMOp.not_,\n args=[condition],\n source_location=source_location,\n ),\n source_location=source_location,\n )\n )\n block.ops.append(\n models.Intrinsic(\n op=AVMOp.assert_,\n args=[not_condition],\n error_message=fail_comment,\n source_location=source_location,\n )\n )\n block.terminator = models.Goto(target=zero, source_location=source_location)\n if err_block not in block.successors:\n remove_target(block, err_block)\n case (\n models.ConditionalBranch(\n condition=models.Register() as condition,\n ) as branch\n ) if (\n isinstance(defn := get_definition(subroutine, condition), models.Assignment)\n and isinstance(defn.source, models.Intrinsic)\n and defn.source.op is AVMOp.not_\n ):\n logger.debug(\n f\"simplified branch on !{condition} by swapping zero and non-zero targets\"\n )\n block.terminator = attrs.evolve(\n branch,\n zero=branch.non_zero,\n non_zero=branch.zero,\n condition=defn.source.args[0],\n )\n case (\n models.Switch(\n value=models.Value(atype=AVMType.uint64) as value,\n cases=cases,\n default=default_block,\n source_location=source_location,\n ) as switch\n ) if _can_simplify_switch(switch):\n logger.debug(\"simplifying a switch with constants into goto nth\")\n # reduce to GotoNth\n block_map = dict[int, models.BasicBlock]()\n for case, case_block in cases.items():\n assert isinstance(case, models.UInt64Constant)\n block_map[case.value] = case_block\n max_value = max(block_map)\n block.terminator = models.GotoNth(\n value=value,\n blocks=[block_map.get(i, default_block) for i in range(max_value + 1)],\n source_location=source_location,\n default=default_block,\n )\n case models.GotoNth(\n value=models.UInt64Constant(value=value),\n blocks=blocks,\n default=default_block,\n ):\n logger.debug(\"simplifying a goto nth with a constant into a goto\")\n goto = blocks[value] if value < len(blocks) else default_block\n block.terminator = models.Goto(\n source_location=terminator.source_location, target=goto\n )\n for target in unique(terminator.targets()):\n if target is not goto:\n remove_target(block, target)\n case models.GotoNth(\n value=value,\n blocks=[zero], # the constant here is the size of blocks\n default=non_zero,\n ): # reduces to ConditionalBranch\n logger.debug(\"simplifying a goto nth with two targets into a conditional branch\")\n block.terminator = models.ConditionalBranch(\n condition=value,\n zero=zero,\n non_zero=non_zero,\n source_location=terminator.source_location,\n )\n case _:\n continue\n changes = True\n logger.debug(f\"simplified terminator of {block} from {terminator} to {block.terminator}\")\n for phi in modified_phis:\n TrivialPhiRemover.try_remove(phi, subroutine.body)\n return changes\n\n\ndef _can_simplify_switch(switch: models.Switch) -> bool:\n total_targets = 0\n for case in switch.cases:\n if not isinstance(case, models.UInt64Constant):\n return False\n total_targets = max(total_targets, case.value)\n default_targets = total_targets - len(switch.cases)\n return default_targets < (total_targets * _SWITCH_SPARSENESS_SIMPLIFICATION_RATIO)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/optimize\/control_op_simplification.py","language":"Python","license":"NOASSERTION","size":8330} {"code":"import typing\nfrom collections.abc import Iterable, Sequence, Set\n\nimport attrs\n\nfrom puya import log\nfrom puya.context import CompileContext\nfrom puya.errors import InternalError\nfrom puya.ir import models, visitor\nfrom puya.ir._utils import bfs_block_order\nfrom puya.ir.ssa import TrivialPhiRemover\nfrom puya.utils import StableSet\n\nlogger = log.get_logger(__name__)\n\n\nPURE_AVM_OPS = frozenset(\n [\n # group: ops that can't fail at runtime\n # `txn FirstValidTime` technically could fail, but shouldn't happen on mainnet?\n \"txn\",\n \"sha256\",\n \"keccak256\",\n \"sha3_256\",\n \"sha512_256\",\n \"bitlen\",\n # group: could only fail on a type error\n \"!\",\n \"!=\",\n \"&\",\n \"&&\",\n \"<\",\n \"<=\",\n \"==\",\n \">\",\n \">=\",\n \"|\",\n \"||\",\n \"~\",\n \"addw\",\n \"mulw\",\n \"itob\",\n \"len\",\n \"select\",\n \"sqrt\",\n \"shl\",\n \"shr\",\n # group: fail if an input is zero\n \"%\",\n \"\/\",\n \"expw\",\n \"divmodw\",\n \"divw\",\n # group: fail on over\/underflow\n \"*\",\n \"+\",\n \"-\",\n \"^\",\n \"exp\",\n # group: fail on index out of bounds\n \"arg\",\n \"arg_0\",\n \"arg_1\",\n \"arg_2\",\n \"arg_3\",\n \"args\",\n \"extract\",\n \"extract3\",\n \"extract_uint16\",\n \"extract_uint32\",\n \"extract_uint64\",\n \"replace2\",\n \"replace3\",\n \"setbit\",\n \"setbyte\",\n \"getbit\",\n \"getbyte\",\n \"gaid\",\n \"gaids\",\n \"gload\",\n \"gloads\",\n \"gloadss\",\n \"substring\",\n \"substring3\",\n \"txna\",\n \"txnas\",\n \"gtxn\",\n \"gtxna\",\n \"gtxnas\",\n \"gtxns\",\n \"gtxnsa\",\n \"gtxnsas\",\n \"block\",\n # group: fail on input too large\n \"b%\",\n \"b*\",\n \"b+\",\n \"b-\",\n \"b\/\",\n \"b^\",\n \"btoi\",\n # group: might fail on input too large? TODO: verify these\n \"b!=\",\n \"b<\",\n \"b<=\",\n \"b==\",\n \"b>\",\n \"b>=\",\n \"b&\",\n \"b|\",\n \"b~\",\n \"bsqrt\",\n # group: fail on output too large\n \"concat\",\n \"bzero\",\n # group: fail on input format \/ byte lengths\n \"base64_decode\",\n \"json_ref\",\n \"ecdsa_pk_decompress\",\n \"ecdsa_pk_recover\",\n \"ec_add\",\n \"ec_pairing_check\",\n \"ec_scalar_mul\",\n \"ec_subgroup_check\",\n \"ec_multi_scalar_mul\",\n \"ec_map_to\",\n \"ecdsa_verify\",\n \"ed25519verify\",\n \"ed25519verify_bare\",\n \"vrf_verify\",\n # group: v11\n \"falcon_verify\",\n \"sumhash512\",\n ]\n)\n\n# ops that have no observable side effects outside the function\n# note: originally generated basd on all ops that:\n# - return a stack value (this, as of v10, yields no false negatives)\n# - AND isn't in the generate_avm_ops.py list of exclusions (which are all control flow\n# or pure stack manipulations)\n# - AND isn't box_create or box_del, they were the only remaining false positives\nIMPURE_SIDE_EFFECT_FREE_AVM_OPS = frozenset(\n [\n # group: ops that can't fail at runtime\n \"global\", # OpcodeBudget is non-const, otherwise this could be pure\n # group: could only fail on a type error\n \"app_global_get\",\n \"app_global_get_ex\",\n \"load\",\n # group: fail on resource not \"available\"\n # TODO: determine if any of this group is pure\n \"acct_params_get\",\n \"app_opted_in\",\n \"app_params_get\",\n \"asset_holding_get\",\n \"asset_params_get\",\n \"app_local_get\",\n \"app_local_get_ex\",\n \"balance\",\n \"min_balance\",\n \"box_extract\",\n \"box_get\",\n \"box_len\",\n # group: fail on index out of bounds\n \"loads\",\n # group: might fail depending on state\n \"itxn\",\n \"itxna\",\n \"itxnas\",\n \"gitxn\",\n \"gitxna\",\n \"gitxnas\",\n ]\n)\n\n_should_be_empty = PURE_AVM_OPS & IMPURE_SIDE_EFFECT_FREE_AVM_OPS\nassert not _should_be_empty, _should_be_empty\nSIDE_EFFECT_FREE_AVM_OPS = frozenset([*PURE_AVM_OPS, *IMPURE_SIDE_EFFECT_FREE_AVM_OPS])\n\n\n@attrs.define\nclass SubroutineCollector(visitor.IRTraverser):\n subroutines: StableSet[models.Subroutine] = attrs.field(factory=StableSet)\n\n @classmethod\n def collect(cls, program: models.Program) -> StableSet[models.Subroutine]:\n collector = cls()\n collector.visit_subroutine(program.main)\n return collector.subroutines\n\n def visit_subroutine(self, subroutine: models.Subroutine) -> None:\n if subroutine not in self.subroutines:\n self.subroutines.add(subroutine)\n self.visit_all_blocks(subroutine.body)\n\n def visit_invoke_subroutine(self, callsub: models.InvokeSubroutine) -> None:\n self.visit_subroutine(callsub.target)\n\n\ndef remove_unused_subroutines(program: models.Program) -> bool:\n subroutines = SubroutineCollector.collect(program)\n if modified := (len(subroutines) != (1 + len(program.subroutines))):\n to_keep = [p for p in program.subroutines if p in subroutines]\n for p in program.subroutines:\n if p not in subroutines:\n logger.debug(f\"removing unused subroutine {p.id}\")\n program.subroutines = to_keep\n return modified\n\n\ndef remove_unused_variables(_context: CompileContext, subroutine: models.Subroutine) -> bool:\n modified = 0\n assignments = dict[tuple[models.BasicBlock, models.Assignment], set[models.Register]]()\n for block, op, register in UnusedRegisterCollector.collect(subroutine):\n if isinstance(op, models.Assignment):\n assignments.setdefault((block, op), set()).add(register)\n else:\n assert register == op.register\n block.phis.remove(op)\n logger.debug(f\"Removing unused variable {register.local_id}\")\n modified += 1\n\n for (block, ass), registers in assignments.items():\n if registers.symmetric_difference(ass.targets):\n pass # some registers still used\n elif isinstance(ass.source, models.Value | models.InnerTransactionField) or (\n isinstance(ass.source, models.Intrinsic)\n and ass.source.op.code in SIDE_EFFECT_FREE_AVM_OPS\n ):\n for reg in sorted(registers, key=lambda r: r.local_id):\n logger.debug(f\"Removing unused variable {reg.local_id}\")\n block.ops.remove(ass)\n modified += 1\n else:\n logger.debug(\n f\"Not removing unused assignment since source is not marked as pure: {ass}\"\n )\n return modified > 0\n\n\n@attrs.define(kw_only=True)\nclass UnusedRegisterCollector(visitor.IRTraverser):\n used: set[models.Register] = attrs.field(factory=set)\n assigned: dict[models.Register, tuple[models.BasicBlock, models.Assignment | models.Phi]] = (\n attrs.field(factory=dict)\n )\n active_block: models.BasicBlock\n\n @classmethod\n def collect(\n cls, sub: models.Subroutine\n ) -> Iterable[tuple[models.BasicBlock, models.Assignment | models.Phi, models.Register]]:\n collector = cls(active_block=sub.entry)\n collector.visit_all_blocks(sub.body)\n for reg, (block, ass) in collector.assigned.items():\n if reg not in collector.used:\n yield block, ass, reg\n\n @typing.override\n def visit_block(self, block: models.BasicBlock) -> None:\n self.active_block = block\n super().visit_block(block)\n\n @typing.override\n def visit_assignment(self, ass: models.Assignment) -> None:\n for target in ass.targets:\n self.assigned[target] = (self.active_block, ass)\n ass.source.accept(self)\n\n @typing.override\n def visit_phi(self, phi: models.Phi) -> None:\n # don't visit phi.register, as this would mean the phi can never be considered unused\n for arg in phi.args:\n arg.accept(self)\n self.assigned[phi.register] = (self.active_block, phi)\n\n @typing.override\n def visit_register(self, reg: models.Register) -> None:\n self.used.add(reg)\n\n\ndef remove_unreachable_blocks(_context: CompileContext, subroutine: models.Subroutine) -> bool:\n reachable_set = frozenset(bfs_block_order(subroutine.entry))\n unreachable_blocks = [b for b in subroutine.body if b not in reachable_set]\n if not unreachable_blocks:\n return False\n\n logger.debug(f\"Removing unreachable blocks: {', '.join(map(str, unreachable_blocks))}\")\n\n reachable_blocks = []\n for block in subroutine.body:\n if block in reachable_set:\n reachable_blocks.append(block)\n if not reachable_set.issuperset(block.successors):\n raise InternalError(\n f\"Block {block} has unreachable successor(s),\"\n f\" but was not marked as unreachable itself\"\n )\n if not reachable_set.issuperset(block.predecessors):\n block.predecessors = [b for b in block.predecessors if b in reachable_set]\n logger.debug(f\"Removed unreachable predecessors from {block}\")\n\n UnreachablePhiArgsRemover.apply(unreachable_blocks, reachable_blocks)\n subroutine.body = reachable_blocks\n return True\n\n\n@attrs.define\nclass UnreachablePhiArgsRemover(visitor.IRTraverser):\n _unreachable_blocks: Set[models.BasicBlock]\n _reachable_blocks: Sequence[models.BasicBlock]\n\n @classmethod\n def apply(\n cls,\n unreachable_blocks: Sequence[models.BasicBlock],\n reachable_blocks: Sequence[models.BasicBlock],\n ) -> None:\n collector = cls(frozenset(unreachable_blocks), reachable_blocks)\n collector.visit_all_blocks(reachable_blocks)\n\n def visit_phi(self, phi: models.Phi) -> None:\n args_to_remove = [a for a in phi.args if a.through in self._unreachable_blocks]\n if not args_to_remove:\n return\n logger.debug(\n \"Removing unreachable phi arguments: \" + \", \".join(sorted(map(str, args_to_remove)))\n )\n phi.args = [a for a in phi.args if a not in args_to_remove]\n if not phi.non_self_args:\n raise InternalError(\n f\"undefined phi created when removing args through \"\n f\"{', '.join(map(str, self._unreachable_blocks))}\"\n )\n TrivialPhiRemover.try_remove(phi, self._reachable_blocks)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/optimize\/dead_code_elimination.py","language":"Python","license":"NOASSERTION","size":10570} {"code":"import copy\nimport itertools\nimport typing\nfrom collections import defaultdict\nfrom collections.abc import Collection, Iterable, Iterator, Mapping, Sequence\n\nimport attrs\nimport networkx as nx # type: ignore[import-untyped]\n\nfrom puya import log\nfrom puya.ir import models\nfrom puya.ir.context import TMP_VAR_INDICATOR\nfrom puya.ir.optimize._call_graph import CallGraph\nfrom puya.ir.optimize.context import IROptimizationContext\nfrom puya.ir.optimize.intrinsic_simplification import COMPILE_TIME_CONSTANT_OPS\nfrom puya.ir.visitor import IRTraverser\nfrom puya.ir.visitor_mutator import IRMutator\nfrom puya.utils import lazy_setdefault\n\nlogger = log.get_logger(__name__)\n\n\ndef analyse_subroutines_for_inlining(\n context: IROptimizationContext,\n program: models.Program,\n routable_method_ids: Collection[str] | None,\n) -> None:\n context.inlineable_calls.clear()\n context.constant_with_constant_args.clear()\n\n call_graph = CallGraph(program)\n for sub in program.subroutines:\n if sub.inline is False:\n pass # nothing to do\n elif any(phi.args for phi in sub.entry.phis):\n logger.debug(\n f\"function has phi node(s) with arguments in entry block: {sub.id}\",\n location=sub.source_location,\n )\n if sub.inline is True:\n logger.warning(\n \"function not suitable for inlining due to complex control flow\",\n location=sub.source_location,\n )\n sub.inline = False\n elif call_graph.is_auto_recursive(sub):\n logger.debug(f\"function is auto-recursive: {sub.id}\", location=sub.source_location)\n if sub.inline is True:\n logger.warning(\"unable to inline recursive function\", location=sub.source_location)\n sub.inline = False\n elif sub.inline is True:\n for callee_id, _ in call_graph.callees(sub):\n if not call_graph.has_path(sub.id, callee_id):\n context.inlineable_calls.add((callee_id, sub.id))\n else:\n logger.warning(\n f\"not inlining call from {callee_id} to {sub.id}\"\n f\" because call may be re-entrant\",\n location=sub.source_location,\n )\n else:\n typing.assert_type(sub.inline, None)\n if context.options.optimization_level == 0:\n return\n\n # for optimization levels below 2, skip auto-inlining routable methods into the approval\n # program. mostly this can be beneficial in terms of #ops, but not always.\n # also, it impacts the debugging experience\n skip_routable_ids = frozenset[str]()\n if context.options.optimization_level < 2:\n skip_routable_ids = frozenset(routable_method_ids or ())\n\n for sub in program.subroutines:\n if sub.inline is None:\n if _is_trivial(sub):\n # special case for trivial methods, even when routable\n logger.debug(f\"marking trivial method {sub.id} as inlineable\")\n for callee_id, _ in call_graph.callees(sub):\n # don't need to check re-entrancy here since there's no callsub\n context.inlineable_calls.add((callee_id, sub.id))\n elif sub.id not in skip_routable_ids:\n match call_graph.callees(sub):\n case [(callee_id, 1)]:\n assert (\n callee_id != sub.id\n ), f\"function {sub.id} is auto-recursive and disconnected\"\n logger.debug(f\"marking single-use function {sub.id} for inlining\")\n context.inlineable_calls.add((callee_id, sub.id))\n if context.inlineable_calls:\n return\n for sub in program.subroutines:\n if sub.inline is None and sub.id not in skip_routable_ids:\n complexity = sum(\n len(b.phis) + len(b.ops) + len(_not_none(b.terminator).targets()) for b in sub.body\n )\n threshold = max(3, 1 + len(sub._returns) + len(sub.parameters)) # noqa: SLF001\n if complexity <= threshold:\n logger.debug(\n f\"marking simple function {sub.id} for inlining\"\n f\" ({complexity=} <= {threshold=})\"\n )\n for callee_id, _ in call_graph.callees(sub):\n if not call_graph.has_path(sub.id, callee_id):\n context.inlineable_calls.add((callee_id, sub.id))\n\n\ndef _is_trivial(sub: models.Subroutine) -> bool:\n match sub.body:\n case [models.BasicBlock(phis=[], ops=[])]:\n return True\n return False\n\n\ndef perform_subroutine_inlining(\n context: IROptimizationContext, subroutine: models.Subroutine\n) -> bool:\n inline_calls_to = {\n to_id for from_id, to_id in context.inlineable_calls if from_id == subroutine.id\n }\n if not (inline_calls_to or context.options.optimization_level >= 2):\n return False\n modified = False\n blocks_to_visit = subroutine.body.copy()\n max_block_id = max(_not_none(block.id) for block in blocks_to_visit)\n next_id = itertools.count(max_block_id + 1)\n while blocks_to_visit:\n block = blocks_to_visit.pop()\n for op_index, op in enumerate(block.ops):\n match op:\n case models.Assignment(\n targets=return_targets, source=models.InvokeSubroutine() as call\n ):\n pass\n case models.InvokeSubroutine() as call:\n return_targets = []\n case _:\n continue\n if call.target.id in inline_calls_to:\n logger.debug(\n f\"inlining call to {call.target.id} in {subroutine.id}\",\n location=op.source_location,\n )\n elif (\n context.options.optimization_level >= 2\n and call.target.inline is None\n and all(isinstance(arg, models.Constant) for arg in call.args)\n and lazy_setdefault(\n context.constant_with_constant_args,\n call.target.id,\n lambda _: _ConstantFunctionDetector.is_constant_with_constant_args(\n call.target\n ),\n )\n ):\n logger.debug(\n f\"constant function call to {call.target.id} in {subroutine.id}\",\n location=op.source_location,\n )\n else:\n continue\n\n remainder, created_blocks = _inline_call(\n block,\n call,\n next_id,\n op_index,\n return_targets,\n list(subroutine.get_assigned_registers()),\n )\n # only visit the remainder of the block, the newly created blocks\n # come from a different subroutine, so shouldn't be tested for inlining\n # within the curren subroutine\n blocks_to_visit.append(remainder)\n created_blocks.append(remainder)\n idx_after_block = subroutine.body.index(block) + 1\n subroutine.body[idx_after_block:idx_after_block] = created_blocks\n modified = True\n break # we're done with this block, since it's been split\n return modified\n\n\ndef _inline_call(\n block: models.BasicBlock,\n call: models.InvokeSubroutine,\n next_id: Iterator[int],\n op_index: int,\n return_targets: Sequence[models.Register],\n host_assigned_registers: list[models.Register],\n) -> tuple[models.BasicBlock, list[models.BasicBlock]]:\n # make a copy of the entire block graph, and adjust register versions\n # to avoid any collisions, as well as updating block IDs\n register_offsets = defaultdict[str, int](int)\n for host_reg in host_assigned_registers:\n register_offsets[host_reg.name] = max(\n register_offsets[host_reg.name], host_reg.version + 1\n )\n new_blocks = _inlined_blocks(call.target, register_offsets)\n for new_block in new_blocks:\n new_block.id = next(next_id)\n # split the block after the callsub instruction\n ops_after = block.ops[op_index + 1 :]\n del block.ops[op_index:]\n terminator_after = block.terminator\n assert terminator_after is not None\n for succ in terminator_after.unique_targets:\n succ.predecessors.remove(block)\n inlined_entry = new_blocks[0]\n block.terminator = models.Goto(target=inlined_entry, source_location=call.source_location)\n inlined_entry.predecessors.append(block)\n for phi in inlined_entry.phis:\n # TODO: assign undefined and use that as phi arg so we can inline phi nodes with args.\n # this requires finding a new register though, and is quite hard to write code\n # that would trigger this, so leaving for now\n assert not phi.args, \"entry phi with arguments should have been prevented from inlining\"\n inlined_entry.ops.insert(\n 0,\n models.Assignment(\n targets=[phi.register],\n source=models.Undefined(ir_type=phi.ir_type, source_location=phi.source_location),\n source_location=phi.source_location,\n ),\n )\n inlined_entry.phis.clear()\n # assign parameters before call\n for arg, param in zip(call.args, call.target.parameters, strict=True):\n updated_param = models.Register(\n name=param.name,\n ir_type=param.ir_type,\n version=param.version + register_offsets[param.name],\n source_location=param.source_location,\n )\n block.ops.append(\n models.Assignment(\n targets=[updated_param], source=arg, source_location=arg.source_location\n )\n )\n\n returning_blocks = [\n (new_block, new_block.terminator.result)\n for new_block in new_blocks\n if isinstance(new_block.terminator, models.SubroutineReturn)\n ]\n # create the return block and insert as a predecessor of the original blocks target(s)\n remainder = models.BasicBlock(\n id=next(next_id),\n phis=[],\n ops=ops_after,\n terminator=terminator_after,\n predecessors=[],\n comment=f\"after_inlined_{call.target.id}\",\n source_location=block.source_location,\n )\n for succ in remainder.successors:\n for phi in succ.phis:\n for phi_arg in phi.args:\n if phi_arg.through == block:\n phi_arg.through = remainder\n succ.predecessors.append(remainder)\n # replace inlined retsubs with unconditional branches to the second block half\n for new_block, _ in returning_blocks:\n new_block.terminator = models.Goto(target=remainder, source_location=call.source_location)\n remainder.predecessors.append(new_block)\n\n num_returns = len(returning_blocks)\n if num_returns == 1:\n # if there is a single retsub, we can assign to the return variables in that block\n # directly without violating SSA\n ((new_block, return_values),) = returning_blocks\n if return_targets:\n new_block.ops.append(\n models.Assignment(\n targets=return_targets,\n source=models.ValueTuple(values=return_values, source_location=None),\n source_location=None,\n )\n )\n elif num_returns > 1:\n # otherwise when there's more than on restsub block,\n # return value(s) become phi node(s) in the second block half\n return_phis = [models.Phi(register=ret_target) for ret_target in return_targets]\n for new_block_idx, (new_block, return_values) in enumerate(returning_blocks):\n for ret_idx, ret_phi in enumerate(return_phis):\n ret_value = return_values[ret_idx]\n if not isinstance(ret_value, models.Register):\n tmp_value = ret_value\n tmp_reg_name = f\"{call.target.id}{TMP_VAR_INDICATOR}{ret_idx}\"\n ret_value = models.Register(\n ir_type=ret_value.ir_type,\n source_location=ret_value.source_location,\n name=tmp_reg_name,\n version=new_block_idx + register_offsets[tmp_reg_name],\n )\n new_block.ops.append(\n models.Assignment(\n targets=[ret_value],\n source=tmp_value,\n source_location=tmp_value.source_location,\n )\n )\n ret_phi.args.append(models.PhiArgument(value=ret_value, through=new_block))\n\n remainder.phis = return_phis\n return remainder, new_blocks\n\n\ndef _not_none[T](x: T | None) -> T:\n assert x is not None\n return x\n\n\ndef _inlined_blocks(\n sub: models.Subroutine, register_offsets: Mapping[str, int]\n) -> list[models.BasicBlock]:\n ref_collector = _SubroutineReferenceCollector()\n ref_collector.visit_all_blocks(sub.body)\n memo = {id(s): s for s in ref_collector.subroutines}\n blocks = copy.deepcopy(sub.body, memo=memo)\n _OffsetRegisterVersions.apply(blocks, register_offsets=register_offsets)\n return blocks\n\n\n@attrs.define\nclass _OffsetRegisterVersions(IRMutator):\n register_offsets: Mapping[str, int]\n\n @classmethod\n def apply(\n cls, blocks: Iterable[models.BasicBlock], *, register_offsets: Mapping[str, int]\n ) -> None:\n replacer = cls(register_offsets=register_offsets)\n for block in blocks:\n replacer.visit_block(block)\n\n def visit_register(self, reg: models.Register) -> models.Register:\n return models.Register(\n name=reg.name,\n ir_type=reg.ir_type,\n version=reg.version + self.register_offsets[reg.name],\n source_location=reg.source_location,\n )\n\n\n@attrs.define\nclass _SubroutineReferenceCollector(IRTraverser):\n subroutines: set[models.Subroutine] = attrs.field(factory=set)\n\n @typing.override\n def visit_invoke_subroutine(self, callsub: models.InvokeSubroutine) -> None:\n self.subroutines.add(callsub.target)\n super().visit_invoke_subroutine(callsub)\n\n\nclass _NonConstantFunctionError(Exception):\n pass\n\n\nclass _ConstantFunctionDetector(IRTraverser):\n def __init__(self) -> None:\n self._block_graph = nx.DiGraph()\n\n def has_cycle(self, *, start_from: int | None = None) -> bool:\n try:\n nx.find_cycle(self._block_graph, source=start_from)\n except nx.NetworkXNoCycle:\n return False\n else:\n return True\n\n @classmethod\n def is_constant_with_constant_args(cls, sub: models.Subroutine) -> bool:\n \"\"\"Detect if a function is constant assuming all argument are constants\"\"\"\n visitor = cls()\n try:\n visitor.visit_all_blocks(sub.body)\n except _NonConstantFunctionError:\n return False\n return not visitor.has_cycle(start_from=sub.entry.id)\n\n @typing.override\n def visit_block(self, block: models.BasicBlock) -> None:\n super().visit_block(block)\n self._block_graph.add_node(block.id)\n for target in block.successors:\n self._block_graph.add_edge(block.id, target.id)\n\n @typing.override\n def visit_invoke_subroutine(self, callsub: models.InvokeSubroutine) -> None:\n raise _NonConstantFunctionError\n\n @typing.override\n def visit_template_var(self, deploy_var: models.TemplateVar) -> None:\n raise _NonConstantFunctionError\n\n @typing.override\n def visit_compiled_contract_reference(self, const: models.CompiledContractReference) -> None:\n raise _NonConstantFunctionError\n\n @typing.override\n def visit_compiled_logicsig_reference(self, const: models.CompiledLogicSigReference) -> None:\n raise _NonConstantFunctionError\n\n @typing.override\n def visit_intrinsic_op(self, intrinsic: models.Intrinsic) -> None:\n if intrinsic.op.code not in COMPILE_TIME_CONSTANT_OPS:\n raise _NonConstantFunctionError\n super().visit_intrinsic_op(intrinsic)\n\n @typing.override\n def visit_itxn_constant(self, const: models.ITxnConstant) -> None:\n raise _NonConstantFunctionError\n\n @typing.override\n def visit_inner_transaction_field(self, field: models.InnerTransactionField) -> None:\n raise _NonConstantFunctionError\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/optimize\/inlining.py","language":"Python","license":"NOASSERTION","size":16636} {"code":"import attrs\n\nfrom puya.context import CompileContext\nfrom puya.ir import models\nfrom puya.ir.avm_ops import AVMOp\nfrom puya.ir.visitor_mutator import IRMutator\n\n\ndef inner_txn_field_replacer(_context: CompileContext, subroutine: models.Subroutine) -> bool:\n modified = IntrinsicFieldReplacer.apply(to=subroutine)\n return modified > 0\n\n\n@attrs.define\nclass IntrinsicFieldReplacer(IRMutator):\n modified: int = 0\n\n @classmethod\n def apply(cls, to: models.Subroutine) -> int:\n replacer = cls()\n for block in to.body:\n replacer.visit_block(block)\n return replacer.modified\n\n def visit_inner_transaction_field(\n self, field: models.InnerTransactionField\n ) -> models.InnerTransactionField | models.Intrinsic:\n match field.group_index:\n case models.ITxnConstant(value=group_index):\n pass\n case _:\n return field\n match field.is_last_in_group:\n case models.UInt64Constant(value=is_last_in_group):\n pass\n case _:\n is_last_in_group = 0\n self.modified += 1\n return (\n models.Intrinsic(\n op=AVMOp.itxnas if field.array_index else AVMOp.itxn,\n immediates=[field.field],\n args=[field.array_index] if field.array_index else [],\n source_location=field.source_location,\n )\n if is_last_in_group\n else models.Intrinsic(\n op=AVMOp.gitxnas if field.array_index else AVMOp.gitxn,\n immediates=[group_index, field.field],\n args=[field.array_index] if field.array_index else [],\n source_location=field.source_location,\n )\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/optimize\/inner_txn.py","language":"Python","license":"NOASSERTION","size":1774} {"code":"import base64\nimport contextlib\nimport math\nimport operator\nimport typing\nfrom collections import defaultdict, deque\nfrom collections.abc import Callable, Container, Generator, Iterable, Mapping, Sequence, Set\nfrom itertools import zip_longest\n\nimport attrs\n\nfrom puya import algo_constants, log\nfrom puya.avm import AVMType\nfrom puya.ir import models\nfrom puya.ir.avm_ops import AVMOp\nfrom puya.ir.models import Intrinsic, UInt64Constant\nfrom puya.ir.optimize.context import IROptimizationContext\nfrom puya.ir.optimize.dead_code_elimination import SIDE_EFFECT_FREE_AVM_OPS\nfrom puya.ir.register_read_collector import RegisterReadCollector\nfrom puya.ir.types_ import AVMBytesEncoding, IRType\nfrom puya.ir.visitor_mutator import IRMutator\nfrom puya.parse import SourceLocation\nfrom puya.utils import biguint_bytes_eval, method_selector_hash, set_add\n\nlogger = log.get_logger(__name__)\n\n\n_AnyOp = models.Op | models.ControlOp | models.Phi\n\n_RegisterAssignments = Mapping[models.Register, models.Assignment]\n\nCOMPILE_TIME_CONSTANT_OPS = frozenset(\n [\n # \"generic\" comparison ops\n \"==\",\n \"!=\",\n # uint64 comparison ops\n \"<\",\n \"<=\",\n \">\",\n \">=\",\n # boolean ops\n \"!\",\n \"&&\",\n \"||\",\n # uint64 bitwise ops\n \"&\",\n \"|\",\n \"^\",\n \"~\",\n \"shl\",\n \"shr\",\n # uint64 math\n \"+\",\n \"-\",\n \"*\",\n \"\/\",\n \"%\",\n \"exp\",\n \"sqrt\",\n # wide math\n \"addw\",\n \"mulw\",\n \"divw\",\n \"expw\",\n \"divmodw\",\n # bit\/byte ops\n \"concat\",\n \"extract\",\n \"extract3\",\n \"getbit\",\n \"getbyte\",\n \"len\",\n \"replace2\",\n \"replace3\",\n \"setbit\",\n \"setbyte\",\n \"substring\",\n \"substring3\",\n # conversion\n \"itob\",\n \"btoi\",\n \"extract_uint16\",\n \"extract_uint32\",\n \"extract_uint64\",\n # byte math\n \"b+\",\n \"b-\",\n \"b*\",\n \"b\/\",\n \"b%\",\n \"bsqrt\",\n # byte comaprison ops\n \"b==\",\n \"b!=\",\n \"b<\",\n \"b<=\",\n \"b>\",\n \"b>=\",\n # byte bitwise ops\n \"b&\",\n \"b|\",\n \"b^\",\n \"b~\",\n # misc\n \"assert\",\n \"bzero\",\n \"select\",\n \"bitlen\",\n # ! unimplemented for constant arg evaluation\n \"base64_decode\",\n \"ec_add\",\n \"ec_map_to\",\n \"ec_multi_scalar_mul\",\n \"ec_pairing_check\",\n \"ec_scalar_mul\",\n \"ec_subgroup_check\",\n \"ecdsa_pk_decompress\",\n \"ecdsa_pk_recover\",\n \"ecdsa_verify\",\n \"ed25519verify\",\n \"ed25519verify_bare\",\n \"json_ref\",\n \"keccak256\",\n \"sha256\",\n \"sha3_256\",\n \"sha512_256\",\n \"vrf_verify\",\n \"sumhash512\", # AVM 11\n ]\n)\n_CONSTANT_EVALUABLE: typing.Final[frozenset[str]] = COMPILE_TIME_CONSTANT_OPS - {\n AVMOp.itob.code,\n AVMOp.bzero.code,\n}\n\n\ndef intrinsic_simplifier(context: IROptimizationContext, subroutine: models.Subroutine) -> bool:\n if context.expand_all_bytes:\n work_list = _AssignmentWorkQueue(COMPILE_TIME_CONSTANT_OPS)\n else:\n work_list = _AssignmentWorkQueue(_CONSTANT_EVALUABLE)\n ssa_reads = _SSAReadTracker()\n\n register_assignments = dict[models.Register, models.Assignment]()\n for block in subroutine.body:\n for op in block.all_ops:\n ssa_reads.add(op)\n if isinstance(op, models.Assignment):\n work_list.enqueue(op)\n if len(op.targets) == 1:\n (target,) = op.targets\n register_assignments[target] = op\n\n modified = 0\n while work_list:\n ass, source = work_list.dequeue()\n simplified = _try_fold_intrinsic(register_assignments, source)\n if simplified is not None:\n logger.debug(f\"Simplified {source} to {simplified}\")\n with ssa_reads.update(ass):\n ass.source = simplified\n modified += 1\n # if it became a Value, propagate to any assignment-readers and add to work list\n if isinstance(simplified, models.Value):\n (target,) = ass.targets\n replacer = _RegisterValueReplacer(register=target, replacement=simplified)\n for target_read in ssa_reads.get(target, copy=True):\n if isinstance(target_read, models.Assignment):\n work_list.enqueue(target_read)\n # special case for indirection of otherwise non-inlined constants\n match target_read:\n case models.Assignment(\n targets=[target_read_target],\n source=models.Intrinsic(op=(AVMOp.bzero | AVMOp.itob)),\n ) if not context.expand_all_bytes:\n for indirect_target_read in ssa_reads.get(target_read_target):\n if isinstance(indirect_target_read, models.Assignment):\n work_list.enqueue(indirect_target_read)\n with ssa_reads.update(target_read):\n target_read.accept(replacer)\n modified += replacer.modified\n else:\n typing.assert_type(simplified, models.Intrinsic)\n # source is still an intrinsic, add it back to the work list\n work_list.enqueue(ass)\n # add any assignment-readers to the work list\n for target in ass.targets:\n for target_read in ssa_reads.get(target):\n if isinstance(target_read, models.Assignment):\n work_list.enqueue(target_read)\n\n for block in subroutine.body:\n for op in block.ops:\n if (\n isinstance(op, models.Assignment)\n and isinstance(op.source, models.Intrinsic)\n and op.source.args\n ):\n with_immediates = _try_convert_stack_args_to_immediates(op.source)\n if with_immediates is not None:\n logger.debug(f\"Simplified {op.source} to {with_immediates}\")\n op.source = with_immediates\n modified += 1\n\n register_intrinsics = {\n target: ass.source\n for target, ass in register_assignments.items()\n if isinstance(ass.source, models.Intrinsic)\n }\n modified += _simplify_conditional_branches(subroutine, register_intrinsics)\n modified += _simplify_non_returning_intrinsics(subroutine, register_intrinsics)\n return modified > 0\n\n\nclass _AssignmentWorkQueue:\n def __init__(self, constant_evaluable: Container[str]) -> None:\n self._constant_evaluable = constant_evaluable\n self._dq = deque[tuple[models.Assignment, models.Intrinsic]]()\n self._set = set[Sequence[models.Register]]()\n\n def enqueue(self, op: models.Assignment) -> bool:\n if (\n isinstance(op.source, models.Intrinsic)\n and op.source.op.code in self._constant_evaluable\n and set_add(self._set, op.targets)\n ):\n self._dq.append((op, op.source))\n return True\n return False\n\n def dequeue(self) -> tuple[models.Assignment, models.Intrinsic]:\n op, source = self._dq.popleft()\n assert source is op.source\n self._set.remove(op.targets)\n return op, source\n\n def __bool__(self) -> int:\n return bool(self._dq)\n\n\nclass _SSAReadTracker:\n def __init__(self) -> None:\n self._data = defaultdict[models.Register, set[_AnyOp]](set)\n\n def add(self, op: _AnyOp) -> None:\n for read_reg in self._register_reads(op):\n self._data[read_reg].add(op)\n\n def get(self, reg: models.Register, *, copy: bool = False) -> Iterable[_AnyOp]:\n reads = self._data.get(reg)\n if reads is None:\n return ()\n if copy:\n return reads.copy()\n return reads\n\n @contextlib.contextmanager\n def update(self, op: _AnyOp) -> Generator[None, None, None]:\n old_reads = self._register_reads(op)\n yield\n new_reads = self._register_reads(op)\n for removed_read in old_reads - new_reads:\n self._data[removed_read].remove(op)\n for added_read in new_reads - old_reads:\n self._data[added_read].add(op)\n\n @staticmethod\n def _register_reads(visitable: models.IRVisitable) -> Set[models.Register]:\n collector = RegisterReadCollector()\n visitable.accept(collector)\n return collector.used_registers\n\n\n@attrs.define(kw_only=True)\nclass _RegisterValueReplacer(IRMutator):\n register: models.Register\n replacement: models.Value\n modified: int = 0\n\n @typing.override\n def visit_assignment(self, ass: models.Assignment) -> models.Assignment:\n # don't visit target(s), needs to stay as Register\n ass.source = ass.source.accept(self)\n return ass\n\n @typing.override\n def visit_phi(self, phi: models.Phi) -> models.Phi:\n # don't visit phi nodes, needs to stay as Register\n return phi\n\n @typing.override\n def visit_register(self, reg: models.Register) -> models.Value: # type: ignore[override]\n if reg != self.register:\n return reg\n self.modified += 1\n return self.replacement\n\n\ndef _simplify_conditional_branches(\n subroutine: models.Subroutine, register_intrinsics: Mapping[models.Register, models.Intrinsic]\n) -> int:\n modified = 0\n branch_registers = dict[\n models.Register, list[tuple[models.ConditionalBranch, models.BasicBlock]]\n ]()\n for block in subroutine.body:\n match block.terminator:\n case (\n models.ConditionalBranch(condition=models.Register() as cond) as branch\n ) if cond in register_intrinsics:\n branch_registers.setdefault(cond, []).append((branch, block))\n for target, usages in branch_registers.items():\n intrinsic = register_intrinsics[target]\n cond_maybe_simplified = _try_simplify_bool_intrinsic(intrinsic)\n if cond_maybe_simplified is not None:\n for branch, used_block in usages:\n used_block.terminator = attrs.evolve(branch, condition=cond_maybe_simplified)\n modified += 1\n return modified\n\n\ndef _simplify_non_returning_intrinsics(\n subroutine: models.Subroutine, register_intrinsics: Mapping[models.Register, models.Intrinsic]\n) -> int:\n modified = 0\n for block in subroutine.body:\n ops = []\n for op in block.ops:\n if not isinstance(op, models.Intrinsic):\n ops.append(op)\n else:\n result = _visit_intrinsic_op(op, register_intrinsics)\n if result is not op:\n modified += 1\n if result is not None:\n ops.append(result)\n block.ops[:] = ops\n return modified\n\n\ndef _visit_intrinsic_op(\n intrinsic: Intrinsic, register_intrinsics: Mapping[models.Register, models.Intrinsic]\n) -> Intrinsic | None:\n # if we get here, it means either the intrinsic doesn't have a return or it's ignored,\n # in either case, the result has to be either an Op or None (ie delete),\n # so we don't invoke _try_fold_intrinsic here\n if intrinsic.op == AVMOp.assert_:\n (cond,) = intrinsic.args\n if isinstance(cond, models.UInt64Constant):\n value = cond.value\n if value:\n return None\n else:\n # an assert 0 could be simplified to an err, but\n # this would make it a ControlOp, so the block would\n # need to be restructured\n pass\n elif cond in register_intrinsics:\n cond_op = register_intrinsics[cond] # type: ignore[index]\n assert_cond_maybe_simplified = _try_simplify_bool_intrinsic(cond_op)\n if assert_cond_maybe_simplified is not None:\n return attrs.evolve(intrinsic, args=[assert_cond_maybe_simplified])\n return intrinsic\n elif intrinsic.op == AVMOp.itxn_field:\n (field_im,) = intrinsic.immediates\n if field_im in (\"ApprovalProgramPages\", \"ClearStateProgramPages\"):\n (page_value,) = intrinsic.args\n if isinstance(page_value, models.BytesConstant) and page_value.value == b\"\":\n return None\n return intrinsic\n elif intrinsic.op.code in SIDE_EFFECT_FREE_AVM_OPS:\n logger.debug(f\"Removing unused pure op {intrinsic}\")\n return None\n elif intrinsic.args:\n simplified = _try_convert_stack_args_to_immediates(intrinsic)\n if simplified is not None:\n return simplified\n else:\n return intrinsic\n else:\n return intrinsic\n\n\ndef _try_simplify_bool_condition(\n register_assignments: _RegisterAssignments, cond: models.Value\n) -> models.Value | None:\n if cond in register_assignments:\n cond_defn = register_assignments[cond] # type: ignore[index]\n return _try_simplify_bool_intrinsic(cond_defn.source)\n return None\n\n\ndef _try_simplify_bool_intrinsic(cond_op: models.ValueProvider) -> models.Value | None:\n match cond_op:\n case (\n models.Intrinsic(\n args=[\n models.Value(atype=AVMType.uint64) as a,\n models.Value(atype=AVMType.uint64) as b,\n ]\n ) as intrinsic\n ):\n cond_maybe_simplified = _try_simplify_uint64_binary_op(\n intrinsic, a, b, bool_context=True\n )\n if isinstance(cond_maybe_simplified, models.Value):\n return cond_maybe_simplified\n return None\n\n\ndef _try_convert_stack_args_to_immediates(intrinsic: Intrinsic) -> Intrinsic | None:\n match intrinsic:\n case Intrinsic(\n op=AVMOp.gitxnas,\n args=[models.UInt64Constant(value=array_index)],\n immediates=[group_index, field],\n ):\n return attrs.evolve(\n intrinsic,\n op=AVMOp.gitxna,\n args=[],\n immediates=[group_index, field, array_index],\n )\n case Intrinsic(\n op=AVMOp.itxnas,\n args=[models.UInt64Constant(value=array_index)],\n immediates=[field],\n ):\n return attrs.evolve(\n intrinsic,\n op=AVMOp.itxna,\n args=[],\n immediates=[field, array_index],\n )\n case Intrinsic(\n op=(AVMOp.loads | AVMOp.stores as op),\n args=[models.UInt64Constant(value=slot), *rest],\n ):\n return attrs.evolve(\n intrinsic,\n immediates=[slot],\n args=rest,\n op=AVMOp.load if op == AVMOp.loads else AVMOp.store,\n )\n case Intrinsic(\n op=(AVMOp.extract3 | AVMOp.extract),\n args=[\n models.Value(atype=AVMType.bytes),\n models.UInt64Constant(value=S),\n models.UInt64Constant(value=L),\n ],\n ) if S <= 255 and 1 <= L <= 255:\n # note the lower bound of 1 on length, extract with immediates vs extract3\n # have *very* different behaviour if the length is 0\n return attrs.evolve(\n intrinsic, immediates=[S, L], args=intrinsic.args[:1], op=AVMOp.extract\n )\n case Intrinsic(\n op=AVMOp.substring3,\n args=[\n models.Value(atype=AVMType.bytes),\n models.UInt64Constant(value=S),\n models.UInt64Constant(value=E),\n ],\n ) if S <= 255 and E <= 255:\n return attrs.evolve(\n intrinsic, immediates=[S, E], args=intrinsic.args[:1], op=AVMOp.substring\n )\n case Intrinsic(\n op=AVMOp.replace3,\n args=[a, models.UInt64Constant(value=S), b],\n ) if S <= 255:\n return attrs.evolve(intrinsic, immediates=[S], args=[a, b], op=AVMOp.replace2)\n case Intrinsic(\n op=AVMOp.args,\n args=[models.UInt64Constant(value=idx)],\n ) if idx <= 255:\n return attrs.evolve(intrinsic, op=AVMOp.arg, immediates=[idx], args=[])\n return None\n\n\ndef _try_fold_intrinsic(\n register_assignments: _RegisterAssignments, intrinsic: models.Intrinsic\n) -> models.Value | models.Intrinsic | None:\n op_loc = intrinsic.source_location\n if intrinsic.op is AVMOp.select:\n false, true, selector = intrinsic.args\n selector_const = _get_int_constant(selector)\n if selector_const is not None:\n return true if selector_const else false\n maybe_simplified_select_cond = _try_simplify_bool_condition(register_assignments, selector)\n if maybe_simplified_select_cond is not None:\n return attrs.evolve(intrinsic, args=[false, true, maybe_simplified_select_cond])\n if false == true:\n return true\n match (\n _get_byte_constant(register_assignments, false),\n _get_byte_constant(register_assignments, true),\n ):\n case (None, _) | (_, None):\n pass\n case (\n models.BytesConstant(value=false_value),\n models.BytesConstant(value=true_value) as true_bytes_const,\n ) if false_value == true_value:\n return true_bytes_const\n match _get_int_constant(false), _get_int_constant(true):\n case (None, _) | (_, None):\n pass\n case 1, 0:\n return attrs.evolve(intrinsic, op=AVMOp.not_, args=[selector])\n case 0, int(true_int_value) if selector.ir_type == IRType.bool:\n if true_int_value == 1:\n return selector\n return attrs.evolve(intrinsic, op=AVMOp.mul, args=[selector, true])\n case 0, 1:\n zero_const = UInt64Constant(value=0, source_location=intrinsic.source_location)\n return attrs.evolve(intrinsic, op=AVMOp.neq, args=[selector, zero_const])\n elif intrinsic.op is AVMOp.replace2:\n (start,) = intrinsic.immediates\n assert isinstance(start, int)\n byte_arg_a, byte_arg_b = intrinsic.args\n if (byte_const_a := _get_byte_constant(register_assignments, byte_arg_a)) is not None and (\n byte_const_b := _get_byte_constant(register_assignments, byte_arg_b)\n ) is not None:\n replaced = bytearray(byte_const_a.value)\n replaced[start : start + len(byte_const_b.value)] = byte_const_b.value\n return models.BytesConstant(\n value=bytes(replaced),\n encoding=_choose_encoding(byte_const_a.encoding, byte_const_b.encoding),\n source_location=op_loc,\n )\n elif intrinsic.op is AVMOp.replace3:\n byte_arg_a, start_s, byte_arg_b = intrinsic.args\n if (\n (start2 := _get_int_constant(start_s)) is not None\n and (byte_const_a := _get_byte_constant(register_assignments, byte_arg_a)) is not None\n and (byte_const_b := _get_byte_constant(register_assignments, byte_arg_b)) is not None\n ):\n replaced = bytearray(byte_const_a.value)\n replaced[start2 : start2 + len(byte_const_b.value)] = byte_const_b.value\n return models.BytesConstant(\n value=bytes(replaced),\n encoding=_choose_encoding(byte_const_a.encoding, byte_const_b.encoding),\n source_location=op_loc,\n )\n elif intrinsic.op is AVMOp.getbit:\n match intrinsic.args:\n case [\n models.UInt64Constant(value=source, ir_type=IRType.uint64),\n models.UInt64Constant(value=index),\n ]:\n getbit_result = 1 if (source & (1 << index)) else 0\n return models.UInt64Constant(value=getbit_result, source_location=op_loc)\n case [\n models.Value(atype=AVMType.bytes) as byte_arg,\n models.UInt64Constant(value=index),\n ] if (byte_const := _get_byte_constant(register_assignments, byte_arg)) is not None:\n binary_array = [\n x for xs in [bin(bb)[2:].zfill(8) for bb in byte_const.value] for x in xs\n ]\n the_bit = binary_array[index]\n return models.UInt64Constant(source_location=op_loc, value=int(the_bit))\n elif intrinsic.op is AVMOp.setbit:\n match intrinsic.args:\n case [\n models.UInt64Constant(value=source, ir_type=IRType.uint64),\n models.UInt64Constant(value=index),\n models.UInt64Constant(value=value),\n ]:\n if value:\n setbit_result = source | (1 << index)\n else:\n setbit_result = source & ~(1 << index)\n return models.UInt64Constant(value=setbit_result, source_location=op_loc)\n case [\n models.Value(atype=AVMType.bytes) as byte_arg,\n models.UInt64Constant(value=index),\n models.UInt64Constant(value=value),\n ] if (byte_const := _get_byte_constant(register_assignments, byte_arg)) is not None:\n binary_array = [\n x for xs in [bin(bb)[2:].zfill(8) for bb in byte_const.value] for x in xs\n ]\n try:\n binary_array[index] = \"1\" if value else \"0\"\n except IndexError:\n return None # would fail at runtime\n binary_string = \"\".join(binary_array)\n adjusted_const_value = int(binary_string, 2).to_bytes(\n len(byte_const.value), byteorder=\"big\"\n )\n return models.BytesConstant(\n source_location=op_loc,\n encoding=byte_const.encoding,\n value=adjusted_const_value,\n )\n case [a, b, c]:\n bool_arg_maybe_simplified = _try_simplify_bool_condition(register_assignments, c)\n if bool_arg_maybe_simplified is not None:\n return attrs.evolve(intrinsic, args=[a, b, bool_arg_maybe_simplified])\n elif intrinsic.op.code.startswith(\"extract_uint\"):\n match intrinsic.args:\n case [\n models.BytesConstant(value=bytes_value),\n models.UInt64Constant(value=offset),\n ]:\n bit_size = int(intrinsic.op.code.removeprefix(\"extract_uint\"))\n byte_size = bit_size \/\/ 8\n extracted = bytes_value[offset : offset + byte_size]\n if len(extracted) != byte_size:\n return None # would fail at runtime, lets hope this is unreachable \ud83d\ude2c\n uint64_result = int.from_bytes(extracted, byteorder=\"big\", signed=False)\n return models.UInt64Constant(\n value=uint64_result,\n source_location=op_loc,\n )\n elif intrinsic.op is AVMOp.concat:\n left_arg, right_arg = intrinsic.args\n left_const = _get_byte_constant(register_assignments, left_arg)\n right_const = _get_byte_constant(register_assignments, right_arg)\n if left_const is not None:\n if left_const.value == b\"\":\n return right_arg\n if right_const is not None:\n # two constants, just fold\n target_encoding = _choose_encoding(left_const.encoding, right_const.encoding)\n result_value = left_const.value + right_const.value\n result = models.BytesConstant(\n value=result_value,\n encoding=target_encoding,\n source_location=op_loc,\n )\n return result\n elif right_const is not None:\n if right_const.value == b\"\":\n return left_arg\n elif intrinsic.op.code.startswith(\"extract\"):\n match intrinsic:\n case (\n models.Intrinsic(\n immediates=[int(S), int(L)],\n args=[byte_arg],\n )\n | models.Intrinsic(\n immediates=[],\n args=[\n byte_arg,\n models.UInt64Constant(value=S),\n models.UInt64Constant(value=L),\n ],\n )\n ) if (byte_const := _get_byte_constant(register_assignments, byte_arg)) is not None:\n # note there is a difference of behaviour between extract with stack args\n # and with immediates - zero is to the end with immediates,\n # and zero length with stacks\n if intrinsic.immediates and L == 0:\n extracted = byte_const.value[S:]\n else:\n extracted = byte_const.value[S : S + L]\n return models.BytesConstant(\n source_location=op_loc, encoding=byte_const.encoding, value=extracted\n )\n elif intrinsic.op.code.startswith(\"substring\"):\n match intrinsic:\n case (\n models.Intrinsic(\n immediates=[int(S), int(E)],\n args=[byte_arg],\n )\n | models.Intrinsic(\n immediates=[],\n args=[\n byte_arg,\n models.UInt64Constant(value=S),\n models.UInt64Constant(value=E),\n ],\n )\n ) if (byte_const := _get_byte_constant(register_assignments, byte_arg)) is not None:\n if E < S:\n return None # would fail at runtime, lets hope this is unreachable \ud83d\ude2c\n extracted = byte_const.value[S:E]\n return models.BytesConstant(\n source_location=op_loc, encoding=byte_const.encoding, value=extracted\n )\n elif not intrinsic.immediates:\n match intrinsic.args:\n case [models.Value(atype=AVMType.uint64) as x]:\n return _try_simplify_uint64_unary_op(intrinsic, x)\n case [\n models.Value(atype=AVMType.uint64) as a,\n models.Value(atype=AVMType.uint64) as b,\n ]:\n return _try_simplify_uint64_binary_op(intrinsic, a, b)\n case [models.Value(atype=AVMType.bytes) as x]:\n return _try_simplify_bytes_unary_op(register_assignments, intrinsic, x)\n case [\n models.Value(atype=AVMType.bytes) as a,\n models.Value(atype=AVMType.bytes) as b,\n ]:\n return _try_simplify_bytes_binary_op(register_assignments, intrinsic, a, b)\n\n return None\n\n\ndef _get_int_constant(value: models.Value) -> int | None:\n if isinstance(value, models.UInt64Constant):\n return value.value\n return None\n\n\ndef _get_biguint_constant(\n register_assignments: _RegisterAssignments, value: models.Value\n) -> tuple[int, bytes, AVMBytesEncoding] | tuple[None, None, None]:\n if isinstance(value, models.BigUIntConstant):\n return value.value, biguint_bytes_eval(value.value), AVMBytesEncoding.base16\n byte_const = _get_byte_constant(register_assignments, value)\n if byte_const is not None and len(byte_const.value) <= 64:\n return (\n int.from_bytes(byte_const.value, byteorder=\"big\", signed=False),\n byte_const.value,\n byte_const.encoding,\n )\n return None, None, None\n\n\ndef _byte_wise(op: Callable[[int, int], int], lhs: bytes, rhs: bytes) -> bytes:\n return bytes([op(a, b) for a, b in zip_longest(lhs[::-1], rhs[::-1], fillvalue=0)][::-1])\n\n\ndef _choose_encoding(a: AVMBytesEncoding, b: AVMBytesEncoding) -> AVMBytesEncoding:\n if a == b:\n # preserve encoding if both equal\n return a\n # exclude utf8 from known choices, we don't preserve that encoding choice unless\n # they're both utf8 strings, which is covered by the first check\n known_binary_choices = {a, b} - {AVMBytesEncoding.utf8, AVMBytesEncoding.unknown}\n if not known_binary_choices:\n return AVMBytesEncoding.unknown\n\n # pick the most compact encoding of the known binary encodings\n if AVMBytesEncoding.base64 in known_binary_choices:\n return AVMBytesEncoding.base64\n if AVMBytesEncoding.base32 in known_binary_choices:\n return AVMBytesEncoding.base32\n return AVMBytesEncoding.base16\n\n\ndef _decode_address(address: str) -> bytes:\n # Pad address so it's a valid b32 string\n padded_address = address + (6 * \"=\")\n address_bytes = base64.b32decode(padded_address)\n public_key_hash = address_bytes[: algo_constants.PUBLIC_KEY_HASH_LENGTH]\n return public_key_hash\n\n\ndef _get_byte_constant(\n register_assignments: _RegisterAssignments, byte_arg: models.Value\n) -> models.BytesConstant | None:\n if byte_arg in register_assignments:\n byte_arg_defn = register_assignments[byte_arg] # type: ignore[index]\n match byte_arg_defn.source:\n case models.Intrinsic(op=AVMOp.itob, args=[models.UInt64Constant(value=itob_arg)]):\n return _eval_itob(itob_arg, byte_arg_defn.source_location)\n case models.Intrinsic(op=AVMOp.bzero, args=[models.UInt64Constant(value=bzero_arg)]):\n return _eval_bzero(bzero_arg, byte_arg_defn.source_location)\n case models.Intrinsic(op=AVMOp.global_, immediates=[\"ZeroAddress\"]):\n return models.BytesConstant(\n value=_decode_address(algo_constants.ZERO_ADDRESS),\n encoding=AVMBytesEncoding.base32,\n source_location=byte_arg.source_location,\n )\n elif isinstance(byte_arg, models.Constant):\n if isinstance(byte_arg, models.BytesConstant):\n return byte_arg\n if isinstance(byte_arg, models.BigUIntConstant):\n return models.BytesConstant(\n value=biguint_bytes_eval(byte_arg.value),\n encoding=AVMBytesEncoding.base16,\n source_location=byte_arg.source_location,\n )\n if isinstance(byte_arg, models.AddressConstant):\n return models.BytesConstant(\n value=_decode_address(byte_arg.value),\n encoding=AVMBytesEncoding.base32,\n source_location=byte_arg.source_location,\n )\n if isinstance(byte_arg, models.MethodConstant):\n return models.BytesConstant(\n value=method_selector_hash(byte_arg.value),\n encoding=AVMBytesEncoding.base16,\n source_location=byte_arg.source_location,\n )\n return None\n\n\ndef _eval_itob(arg: int, loc: SourceLocation | None) -> models.BytesConstant:\n return models.BytesConstant(\n value=arg.to_bytes(8, byteorder=\"big\", signed=False),\n encoding=AVMBytesEncoding.base16,\n source_location=loc,\n )\n\n\ndef _eval_bzero(arg: int, loc: SourceLocation | None) -> models.BytesConstant | None:\n if arg <= 64:\n return models.BytesConstant(\n value=b\"\\x00\" * arg,\n encoding=AVMBytesEncoding.base16,\n source_location=loc,\n )\n return None\n\n\ndef _try_simplify_uint64_unary_op(\n intrinsic: models.Intrinsic, arg: models.Value\n) -> models.Value | None:\n op_loc = intrinsic.source_location\n x = _get_int_constant(arg)\n if x is not None:\n if intrinsic.op is AVMOp.not_:\n not_x = 0 if x else 1\n return models.UInt64Constant(value=not_x, source_location=op_loc)\n elif intrinsic.op is AVMOp.bitwise_not:\n inverted = x ^ 0xFFFFFFFFFFFFFFFF\n return models.UInt64Constant(value=inverted, source_location=op_loc)\n elif intrinsic.op is AVMOp.sqrt:\n value = math.isqrt(x)\n return models.UInt64Constant(value=value, source_location=op_loc)\n elif intrinsic.op is AVMOp.bitlen:\n return UInt64Constant(value=x.bit_length(), source_location=op_loc)\n elif intrinsic.op is AVMOp.itob:\n return _eval_itob(x, op_loc)\n elif intrinsic.op is AVMOp.bzero:\n return _eval_bzero(x, op_loc)\n else:\n logger.debug(f\"Don't know how to simplify {intrinsic.op.code} of {x}\")\n return None\n\n\ndef _try_simplify_bytes_unary_op(\n register_assignments: _RegisterAssignments, intrinsic: models.Intrinsic, arg: models.Value\n) -> models.Value | None:\n op_loc = intrinsic.source_location\n if intrinsic.op is AVMOp.bsqrt:\n biguint_const, _, _ = _get_biguint_constant(register_assignments, arg)\n if biguint_const is not None:\n value = math.isqrt(biguint_const)\n return models.BigUIntConstant(value=value, source_location=op_loc)\n else:\n byte_const = _get_byte_constant(register_assignments, arg)\n if byte_const is not None:\n if intrinsic.op is AVMOp.bitwise_not_bytes:\n inverted = bytes([x ^ 0xFF for x in byte_const.value])\n return models.BytesConstant(\n value=inverted, encoding=byte_const.encoding, source_location=op_loc\n )\n elif intrinsic.op is AVMOp.btoi:\n converted = int.from_bytes(byte_const.value, byteorder=\"big\", signed=False)\n return models.UInt64Constant(value=converted, source_location=op_loc)\n elif intrinsic.op is AVMOp.len_:\n length = len(byte_const.value)\n return models.UInt64Constant(value=length, source_location=op_loc)\n elif intrinsic.op is AVMOp.bitlen:\n converted = int.from_bytes(byte_const.value, byteorder=\"big\", signed=False)\n return UInt64Constant(value=converted.bit_length(), source_location=op_loc)\n else:\n logger.debug(f\"Don't know how to simplify {intrinsic.op.code} of {byte_const}\")\n return None\n\n\ndef _try_simplify_uint64_binary_op(\n intrinsic: models.Intrinsic, a: models.Value, b: models.Value, *, bool_context: bool = False\n) -> models.Value | models.Intrinsic | None:\n op = intrinsic.op\n c: models.Value | int | None = None\n\n if a == b:\n match op:\n case AVMOp.sub:\n c = 0\n case AVMOp.eq | AVMOp.lte | AVMOp.gte:\n c = 1\n case AVMOp.neq | AVMOp.lt | AVMOp.gt:\n c = 0\n case AVMOp.div_floor:\n c = 1\n case AVMOp.bitwise_xor:\n c = 0\n case AVMOp.bitwise_and | AVMOp.bitwise_or:\n c = a\n if c is None:\n a_const = _get_int_constant(a)\n b_const = _get_int_constant(b)\n\n # a >= 0 <-> 1\n if b_const == 0 and op == AVMOp.gte: # noqa: SIM114\n c = 1\n # 0 <= b <-> 1\n elif a_const == 0 and op == AVMOp.lte:\n c = 1\n elif a_const == 1 and op == AVMOp.mul:\n c = b\n elif b_const == 1 and op == AVMOp.mul:\n c = a\n elif a_const == 0 and op in (AVMOp.add, AVMOp.or_):\n c = b\n elif b_const == 0 and op in (AVMOp.add, AVMOp.sub, AVMOp.or_):\n c = a\n elif 0 in (a_const, b_const) and op in (AVMOp.mul, AVMOp.and_):\n c = 0\n # 0 != b <-> b\n # OR\n # 0 < b <-> b\n # OR\n # 1 <= b <-> b\n elif (bool_context or b.ir_type == IRType.bool) and (\n (a_const == 0 and op in (AVMOp.neq, AVMOp.lt)) or (a_const == 1 and op == AVMOp.lte)\n ):\n c = b\n # a != 0 <-> a\n # OR\n # a > 0 <-> a\n # OR\n # a >= 1 <-> a\n elif (bool_context or a.ir_type == IRType.bool) and (\n (b_const == 0 and op in (AVMOp.neq, AVMOp.gt)) or (b_const == 1 and op == AVMOp.gte)\n ):\n c = a\n elif a_const is not None and b_const is not None:\n match op:\n case AVMOp.add:\n c = a_const + b_const\n case AVMOp.sub:\n c = a_const - b_const\n case AVMOp.mul:\n c = a_const * b_const\n case AVMOp.div_floor if b_const != 0:\n c = a_const \/\/ b_const\n case AVMOp.mod if b_const != 0:\n c = a_const % b_const\n case AVMOp.lt:\n c = 1 if a_const < b_const else 0\n case AVMOp.lte:\n c = 1 if a_const <= b_const else 0\n case AVMOp.gt:\n c = 1 if a_const > b_const else 0\n case AVMOp.gte:\n c = 1 if a_const >= b_const else 0\n case AVMOp.eq:\n c = 1 if a_const == b_const else 0\n case AVMOp.neq:\n c = 1 if a_const != b_const else 0\n case AVMOp.and_:\n c = int(a_const and b_const)\n case AVMOp.or_:\n c = int(a_const or b_const)\n case AVMOp.shl:\n c = (a_const << b_const) % (2**64)\n case AVMOp.shr:\n c = a_const >> b_const\n case AVMOp.exp:\n if a_const == 0 and b_const == 0:\n return None # would fail at runtime, lets hope this is unreachable \ud83d\ude2c\n c = a_const**b_const\n case AVMOp.bitwise_or:\n c = a_const | b_const\n case AVMOp.bitwise_and:\n c = a_const & b_const\n case AVMOp.bitwise_xor:\n c = a_const ^ b_const\n case _:\n logger.debug(\n f\"Don't know how to simplify {a_const} {intrinsic.op.code} {b_const}\"\n )\n # 0 == b <-> !b\n elif a_const == 0 and op == AVMOp.eq:\n return attrs.evolve(intrinsic, op=AVMOp.not_, args=[b])\n # a == 0 <-> !a\n elif b_const == 0 and op == AVMOp.eq:\n return attrs.evolve(intrinsic, op=AVMOp.not_, args=[a])\n if not isinstance(c, int):\n return c\n if c < 0:\n # Value cannot be folded as it would result in a negative uint64\n return None\n return models.UInt64Constant(value=c, source_location=intrinsic.source_location)\n\n\ndef _try_simplify_bytes_binary_op(\n register_assignments: _RegisterAssignments,\n intrinsic: models.Intrinsic,\n a: models.Value,\n b: models.Value,\n) -> models.Value | None:\n op = intrinsic.op\n op_loc = intrinsic.source_location\n c: models.Value | int | None = None\n\n if a == b:\n match op:\n case AVMOp.sub_bytes:\n c = 0\n case AVMOp.eq_bytes | AVMOp.eq | AVMOp.lte_bytes | AVMOp.gte_bytes:\n c = 1\n case AVMOp.neq_bytes | AVMOp.neq | AVMOp.lt_bytes | AVMOp.gt_bytes:\n c = 0\n case AVMOp.div_floor_bytes:\n c = 1\n case AVMOp.bitwise_xor_bytes:\n c = 0\n case AVMOp.bitwise_and_bytes | AVMOp.bitwise_or_bytes:\n c = a\n if c is None:\n a_const, a_const_bytes, a_encoding = _get_biguint_constant(register_assignments, a)\n b_const, b_const_bytes, b_encoding = _get_biguint_constant(register_assignments, b)\n if a_const == 1 and op == AVMOp.mul_bytes:\n c = b\n elif b_const == 1 and op == AVMOp.mul_bytes:\n c = a\n elif a_const == 0 and op == AVMOp.add_bytes:\n c = b\n elif b_const == 0 and op in (AVMOp.add_bytes, AVMOp.sub_bytes):\n c = a\n elif 0 in (a_const, b_const) and op == AVMOp.mul_bytes:\n c = 0\n elif a_const is not None and b_const is not None:\n if typing.TYPE_CHECKING:\n assert a_const_bytes is not None\n assert b_const_bytes is not None\n assert a_encoding is not None\n assert b_encoding is not None\n match op:\n case AVMOp.add_bytes:\n c = a_const + b_const\n case AVMOp.sub_bytes:\n c = a_const - b_const\n case AVMOp.mul_bytes:\n c = a_const * b_const\n case AVMOp.div_floor_bytes:\n c = a_const \/\/ b_const\n case AVMOp.mod_bytes if b_const != 0:\n c = a_const % b_const\n case AVMOp.lt_bytes:\n c = 1 if a_const < b_const else 0\n case AVMOp.lte_bytes:\n c = 1 if a_const <= b_const else 0\n case AVMOp.gt_bytes:\n c = 1 if a_const > b_const else 0\n case AVMOp.gte_bytes:\n c = 1 if a_const >= b_const else 0\n case AVMOp.eq_bytes:\n c = 1 if a_const == b_const else 0\n case AVMOp.neq_bytes:\n c = 1 if a_const != b_const else 0\n case AVMOp.eq:\n c = 1 if a_const_bytes == b_const_bytes else 0\n case AVMOp.neq:\n c = 1 if a_const_bytes != b_const_bytes else 0\n case AVMOp.bitwise_or_bytes:\n return models.BytesConstant(\n value=_byte_wise(operator.or_, a_const_bytes, b_const_bytes),\n encoding=_choose_encoding(a_encoding, b_encoding),\n source_location=op_loc,\n )\n case AVMOp.bitwise_and_bytes:\n return models.BytesConstant(\n value=_byte_wise(operator.and_, a_const_bytes, b_const_bytes),\n encoding=_choose_encoding(a_encoding, b_encoding),\n source_location=op_loc,\n )\n case AVMOp.bitwise_xor_bytes:\n return models.BytesConstant(\n value=_byte_wise(operator.xor, a_const_bytes, b_const_bytes),\n encoding=_choose_encoding(a_encoding, b_encoding),\n source_location=op_loc,\n )\n case _:\n logger.debug(\n f\"Don't know how to simplify {a_const} {intrinsic.op.code} {b_const}\"\n )\n if not isinstance(c, int):\n return c\n if c < 0:\n # don't fold to a negative\n return None\n # could look at StackType of op_signature.returns, but some are StackType.any\n if op in (\n AVMOp.eq_bytes,\n AVMOp.eq,\n AVMOp.neq_bytes,\n AVMOp.neq,\n AVMOp.lt_bytes,\n AVMOp.lte_bytes,\n AVMOp.gt_bytes,\n AVMOp.gte_bytes,\n ):\n return models.UInt64Constant(value=c, source_location=intrinsic.source_location)\n else:\n return models.BigUIntConstant(value=c, source_location=intrinsic.source_location)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/optimize\/intrinsic_simplification.py","language":"Python","license":"NOASSERTION","size":43369} {"code":"import typing\nfrom collections import defaultdict\n\nimport attrs\n\nfrom puya.context import CompileContext\nfrom puya.ir import models\nfrom puya.ir.avm_ops import AVMOp\n\n_ARRAY_FIELDS: typing.Final = frozenset(\n (\n \"ApplicationArgs\",\n \"Accounts\",\n \"Assets\",\n \"Applications\",\n \"ApprovalProgramPages\",\n \"ClearStateProgramPages\",\n )\n)\n_ZERO_DEFAULTS: typing.Final = frozenset(\n (\n \"ExtraProgramPages\",\n \"GlobalNumUint\",\n \"GlobalNumByteSlice\",\n \"LocalNumUint\",\n \"LocalNumByteSlice\",\n )\n)\n\n\ndef elide_itxn_field_calls(_context: CompileContext, subroutine: models.Subroutine) -> bool:\n modified = False\n for block in subroutine.body:\n if _elide_within_block(block):\n modified = True\n return modified\n\n\ndef _elide_within_block(block: models.BasicBlock) -> bool:\n groups = list[_ITxnGroup]()\n current_group: _ITxnGroup | None = None\n for op_idx, op in enumerate(block.ops):\n if isinstance(op, models.Intrinsic):\n match op.op:\n case AVMOp.itxn_begin | AVMOp.itxn_next:\n groups.append(current_group := _ITxnGroup(has_start=True))\n case AVMOp.itxn_submit:\n current_group = None\n case AVMOp.itxn_field:\n (field_im,) = op.immediates\n assert isinstance(field_im, str)\n if field_im not in _ARRAY_FIELDS:\n if current_group is None:\n groups.append(current_group := _ITxnGroup(has_start=False))\n current_group.sets[field_im].append(op_idx)\n if not groups:\n return False\n remove_indexes = set[int]()\n for group in groups:\n for field_im, indexes in group.sets.items():\n final_idx = indexes.pop()\n remove_indexes.update(indexes)\n if group.has_start and field_im in _ZERO_DEFAULTS:\n match block.ops[final_idx]:\n case models.Intrinsic(args=[models.UInt64Constant(value=0)]):\n remove_indexes.add(final_idx)\n if not remove_indexes:\n return False\n block.ops = [op for idx, op in enumerate(block.ops) if idx not in remove_indexes]\n return True\n\n\n@attrs.define\nclass _ITxnGroup:\n has_start: bool\n sets: defaultdict[str, list[int]] = attrs.field(factory=lambda: defaultdict(list))\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/optimize\/itxn_field_elision.py","language":"Python","license":"NOASSERTION","size":2440} {"code":"from collections.abc import Callable, Collection, Iterable\n\nimport attrs\n\nfrom puya import log\nfrom puya.context import ArtifactCompileContext\nfrom puya.ir import models\nfrom puya.ir.optimize.assignments import copy_propagation\nfrom puya.ir.optimize.collapse_blocks import remove_empty_blocks, remove_linear_jump\nfrom puya.ir.optimize.compiled_reference import replace_compiled_references\nfrom puya.ir.optimize.constant_propagation import constant_replacer\nfrom puya.ir.optimize.context import IROptimizationContext\nfrom puya.ir.optimize.control_op_simplification import simplify_control_ops\nfrom puya.ir.optimize.dead_code_elimination import (\n remove_unreachable_blocks,\n remove_unused_subroutines,\n remove_unused_variables,\n)\nfrom puya.ir.optimize.inlining import analyse_subroutines_for_inlining, perform_subroutine_inlining\nfrom puya.ir.optimize.inner_txn import inner_txn_field_replacer\nfrom puya.ir.optimize.intrinsic_simplification import intrinsic_simplifier\nfrom puya.ir.optimize.itxn_field_elision import elide_itxn_field_calls\nfrom puya.ir.optimize.repeated_code_elimination import repeated_expression_elimination\nfrom puya.ir.to_text_visitor import render_program\nfrom puya.utils import attrs_extend\n\nMAX_PASSES = 100\nSubroutineOptimizerCallable = Callable[[IROptimizationContext, models.Subroutine], bool]\nlogger = log.get_logger(__name__)\n\n\n@attrs.define(kw_only=True)\nclass SubroutineOptimization:\n id: str\n desc: str\n _optimize: SubroutineOptimizerCallable\n loop: bool\n\n @classmethod\n def from_function(\n cls, func: SubroutineOptimizerCallable, *, loop: bool = False\n ) -> \"SubroutineOptimization\":\n func_name = func.__name__\n func_desc = func_name.replace(\"_\", \" \").title().strip()\n return SubroutineOptimization(id=func_name, desc=func_desc, optimize=func, loop=loop)\n\n def optimize(self, context: IROptimizationContext, ir: models.Subroutine) -> bool:\n did_modify = self._optimize(context, ir)\n if did_modify:\n while self.loop and self._optimize(context, ir):\n pass\n return did_modify\n\n\ndef get_subroutine_optimizations(optimization_level: int) -> Iterable[SubroutineOptimization]:\n if optimization_level:\n return [\n SubroutineOptimization.from_function(perform_subroutine_inlining),\n SubroutineOptimization.from_function(_split_parallel_copies),\n SubroutineOptimization.from_function(constant_replacer),\n SubroutineOptimization.from_function(copy_propagation),\n SubroutineOptimization.from_function(intrinsic_simplifier),\n SubroutineOptimization.from_function(elide_itxn_field_calls),\n SubroutineOptimization.from_function(remove_unused_variables),\n SubroutineOptimization.from_function(inner_txn_field_replacer),\n SubroutineOptimization.from_function(replace_compiled_references),\n SubroutineOptimization.from_function(simplify_control_ops, loop=True),\n SubroutineOptimization.from_function(remove_linear_jump),\n SubroutineOptimization.from_function(remove_empty_blocks),\n SubroutineOptimization.from_function(remove_unreachable_blocks),\n SubroutineOptimization.from_function(repeated_expression_elimination),\n ]\n else:\n return [\n SubroutineOptimization.from_function(perform_subroutine_inlining),\n SubroutineOptimization.from_function(_split_parallel_copies),\n SubroutineOptimization.from_function(constant_replacer),\n SubroutineOptimization.from_function(remove_unused_variables),\n SubroutineOptimization.from_function(inner_txn_field_replacer),\n SubroutineOptimization.from_function(replace_compiled_references),\n ]\n\n\ndef _split_parallel_copies(_ctx: ArtifactCompileContext, sub: models.Subroutine) -> bool:\n # not an optimisation, but simplifies other optimisation code\n any_modified = False\n for block in sub.body:\n ops = list[models.Op]()\n modified = False\n for op in block.ops.copy():\n if isinstance(op, models.Assignment) and isinstance(op.source, models.ValueTuple):\n for dst, src in zip(op.targets, op.source.values, strict=True):\n modified = True\n ops.append(\n models.Assignment(\n targets=[dst],\n source=src,\n source_location=op.source_location,\n )\n )\n else:\n ops.append(op)\n if modified:\n any_modified = True\n block.ops = ops\n return any_modified\n\n\ndef optimize_program_ir(\n context: ArtifactCompileContext,\n program: models.Program,\n *,\n routable_method_ids: Collection[str] | None,\n) -> None:\n pipeline = get_subroutine_optimizations(context.options.optimization_level)\n opt_context = attrs_extend(IROptimizationContext, context, expand_all_bytes=False)\n for pass_num in range(1, MAX_PASSES + 1):\n program_modified = False\n logger.debug(f\"Begin optimization pass {pass_num}\/{MAX_PASSES}\")\n analyse_subroutines_for_inlining(opt_context, program, routable_method_ids)\n for subroutine in program.all_subroutines:\n logger.debug(f\"Optimizing subroutine {subroutine.id}\")\n for optimizer in pipeline:\n logger.debug(f\"Optimizer: {optimizer.desc}\")\n if optimizer.optimize(opt_context, subroutine):\n program_modified = True\n subroutine.validate_with_ssa()\n if remove_unused_subroutines(program):\n program_modified = True\n if not program_modified:\n logger.debug(f\"No optimizations performed in pass {pass_num}, ending loop\")\n break\n if context.options.output_optimization_ir:\n render_program(context, program, qualifier=\"ssa.opt\")\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/optimize\/main.py","language":"Python","license":"NOASSERTION","size":6012} {"code":"import functools\nimport operator\nimport typing\nfrom collections.abc import Sequence\n\nimport attrs\n\nfrom puya import log\nfrom puya.context import CompileContext\nfrom puya.ir import models\nfrom puya.ir.avm_ops import AVMOp\nfrom puya.ir.optimize.assignments import copy_propagation\nfrom puya.ir.optimize.dead_code_elimination import PURE_AVM_OPS\nfrom puya.ir.visitor import NoOpIRVisitor\n\nlogger = log.get_logger(__name__)\n\n\n@attrs.frozen\nclass IntrinsicData:\n op: AVMOp\n immediates: tuple[str | int, ...]\n args: tuple[models.Value, ...]\n\n @classmethod\n def from_op(cls, op: models.Intrinsic) -> typing.Self:\n return cls(\n op=op.op,\n immediates=tuple(op.immediates),\n args=tuple(op.args),\n )\n\n\ndef repeated_expression_elimination(\n context: CompileContext, subroutine: models.Subroutine\n) -> bool:\n any_modified = False\n dom = compute_dominators(subroutine)\n modified = True\n while modified:\n modified = False\n block_asserted = dict[models.BasicBlock, set[models.Value]]()\n block_const_intrinsics = dict[\n models.BasicBlock, dict[IntrinsicData, Sequence[models.Register]]\n ]()\n for block in subroutine.body:\n visitor = RCEVisitor(block)\n for op in block.ops.copy():\n modified = bool(op.accept(visitor)) or modified\n block_asserted[block] = visitor.asserted\n block_const_intrinsics[block] = visitor.const_intrinsics\n\n for block in subroutine.body:\n dominators = dom[block]\n if dominators:\n visitor = RCEVisitor(\n block,\n # if there is a single dominator then reduce will return the original\n # collection of that dominator, so copy to ensure original collections are\n # not modified\n const_intrinsics=functools.reduce(\n operator.or_, (block_const_intrinsics[b] for b in dominators)\n ).copy(),\n asserted=functools.reduce(\n operator.or_, (block_asserted[b] for b in dominators)\n ).copy(),\n )\n for op in block.ops.copy():\n modified = bool(op.accept(visitor)) or modified\n if modified:\n any_modified = True\n copy_propagation(context, subroutine)\n return any_modified\n\n\ndef compute_dominators(\n subroutine: models.Subroutine,\n) -> dict[models.BasicBlock, list[models.BasicBlock]]:\n all_blocks = set(subroutine.body)\n dom = {b: all_blocks if b.predecessors else {b} for b in subroutine.body}\n changes = True\n while changes:\n changes = False\n for block in reversed(subroutine.body):\n if block.predecessors:\n pred_dom = functools.reduce(set.intersection, (dom[p] for p in block.predecessors))\n new = pred_dom | {block}\n if new != dom[block]:\n dom[block] = new\n changes = True\n return {\n b: sorted(dom_set - {b}, key=lambda a: typing.cast(int, a.id))\n for b, dom_set in dom.items()\n }\n\n\n@attrs.define\nclass RCEVisitor(NoOpIRVisitor[bool]):\n block: models.BasicBlock\n const_intrinsics: dict[IntrinsicData, Sequence[models.Register]] = attrs.field(factory=dict)\n asserted: set[models.Value] = attrs.field(factory=set)\n\n _assignment: models.Assignment | None = None\n\n def visit_assignment(self, ass: models.Assignment) -> bool | None:\n self._assignment = ass\n remove = ass.source.accept(self)\n self._assignment = None\n return remove\n\n def visit_intrinsic_op(self, intrinsic: models.Intrinsic) -> bool:\n modified = False\n if (ass := self._assignment) is not None:\n # only consider ops with stack args because they're much more likely to\n # produce extra stack manipulations\n if intrinsic.args and intrinsic.op.code in PURE_AVM_OPS:\n key = IntrinsicData.from_op(intrinsic)\n try:\n existing = self.const_intrinsics[key]\n except KeyError:\n self.const_intrinsics[key] = ass.targets\n else:\n logger.debug(\n f\"Replacing redundant declaration {ass}\"\n f\" with copy of existing registers {existing}\"\n )\n modified = True\n if len(existing) == 1:\n ass.source = existing[0]\n else:\n current_idx = self.block.ops.index(ass)\n self.block.ops[current_idx : current_idx + 1] = [\n models.Assignment(\n targets=[dst], source=src, source_location=ass.source_location\n )\n for dst, src in zip(ass.targets, existing, strict=True)\n ]\n elif intrinsic.op.code == \"assert\":\n (assert_arg,) = intrinsic.args\n if assert_arg in self.asserted:\n logger.debug(f\"Removing redundant assert of {assert_arg}\")\n modified = True\n self.block.ops.remove(intrinsic)\n else:\n self.asserted.add(assert_arg)\n return modified\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/optimize\/repeated_code_elimination.py","language":"Python","license":"NOASSERTION","size":5447} {"code":"from collections.abc import Set\n\nimport attrs\n\nfrom puya.ir import models\nfrom puya.ir.visitor import IRTraverser\n\n\n@attrs.frozen\nclass RegisterReadCollector(IRTraverser):\n _used_registers: list[models.Register] = attrs.field(factory=list, init=False)\n\n @property\n def used_registers(self) -> Set[models.Register]:\n return dict.fromkeys(self._used_registers).keys()\n\n def visit_register(self, reg: models.Register) -> None:\n self._used_registers.append(reg)\n\n def visit_assignment(self, ass: models.Assignment) -> None:\n ass.source.accept(self)\n\n def visit_phi(self, phi: models.Phi) -> None:\n for arg in phi.args:\n self.visit_phi_argument(arg)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/register_read_collector.py","language":"Python","license":"NOASSERTION","size":702} {"code":"from collections.abc import Sequence\n\nimport attrs\n\nfrom puya import log\nfrom puya.errors import InternalError\nfrom puya.ir import models as ir\nfrom puya.ir.types_ import IRType\nfrom puya.ir.visitor_mutator import IRMutator\nfrom puya.parse import SourceLocation\n\nlogger = log.get_logger(__name__)\n\n\nclass BraunSSA:\n \"\"\"\n Constructs CFG+SSA IR directly from an AST like-structure, without having to go\n through an intermediate non-SSA IR and then compute dominance frontiers etc.\n\n The primary reference is https:\/\/pp.ipd.kit.edu\/uploads\/publikationen\/braun13cc.pdf,\n but also of interest is https:\/\/pp.ipd.kit.edu\/uploads\/publikationen\/buchwald16cc.pdf,\n in which the algorithm is converted into a functional programming form,\n and formally verified.\n \"\"\"\n\n def __init__(\n self,\n all_blocks: Sequence[ir.BasicBlock],\n live_variables: Sequence[ir.Register],\n active_block: ir.BasicBlock,\n ) -> None:\n self._all_blocks = all_blocks # note: this is a shared reference with BlocksBuilder\n self._sealed_blocks = set[ir.BasicBlock]()\n self._current_def = dict[str, dict[ir.BasicBlock, ir.Register]]()\n self._incomplete_phis = dict[ir.BasicBlock, list[ir.Phi]]()\n self._variable_versions = dict[str, int]()\n # initialize any live variables at the start of the subroutines, i.e. parameters\n for parameter in live_variables:\n self.write_variable(parameter.name, active_block, parameter)\n self._variable_versions[parameter.name] = 1\n\n def has_version(self, variable: str) -> bool:\n return variable in self._variable_versions\n\n def write_variable(self, variable: str, block: ir.BasicBlock, value: ir.Register) -> None:\n self._current_def.setdefault(variable, {})[block] = value\n\n def has_write(self, variable: str, block: ir.BasicBlock) -> bool:\n try:\n self._current_def[variable][block]\n except KeyError:\n return False\n else:\n return True\n\n def read_variable(self, variable: str, ir_type: IRType, block: ir.BasicBlock) -> ir.Register:\n try:\n result = self._current_def[variable][block]\n except KeyError:\n result = self._read_variable_recursive(variable, ir_type, block)\n return result\n\n def _read_variable_recursive(\n self, variable: str, ir_type: IRType, block: ir.BasicBlock\n ) -> ir.Register:\n value: ir.Register\n if not self.is_sealed(block):\n logger.debug(\n f\"Looking for '{variable}' in an unsealed block creating an incomplete \"\n f\"Phi: {block}\"\n )\n # incomplete CFG\n phi = self._new_phi(block, variable, ir_type)\n self._incomplete_phis.setdefault(block, []).append(phi)\n value = phi.register\n elif len(block.predecessors) == 1:\n value = self.read_variable(variable, ir_type, block.predecessors[0])\n else:\n # break any potential cycles with empty Phi\n phi = self._new_phi(block, variable, ir_type)\n self.write_variable(variable, block, phi.register)\n value = self._add_phi_operands(phi, block)\n self.write_variable(variable, block, value)\n return value\n\n def new_register(\n self, name: str, ir_type: IRType, location: SourceLocation | None\n ) -> ir.Register:\n version = self._variable_versions.get(name, 0)\n self._variable_versions[name] = version + 1\n return ir.Register(source_location=location, name=name, version=version, ir_type=ir_type)\n\n def is_sealed(self, block: ir.BasicBlock) -> bool:\n return block in self._sealed_blocks\n\n def verify_complete(self) -> None:\n unsealed = [b for b in self._all_blocks if not self.is_sealed(b)]\n if unsealed:\n raise InternalError(\n f\"{len(unsealed)} block\/s were not sealed: \" + \", \".join(map(str, unsealed))\n )\n incomplete_phis = [p for block_phis in self._incomplete_phis.values() for p in block_phis]\n if incomplete_phis:\n # if we get here, there is a bug in this algorithm itself\n raise InternalError(\n f\"{len(incomplete_phis)} phi node\/s are incomplete: \"\n + \", \".join(map(str, incomplete_phis))\n )\n\n def _new_phi(self, block: ir.BasicBlock, variable: str, ir_type: IRType) -> ir.Phi:\n reg = self.new_register(variable, ir_type, location=None)\n phi = ir.Phi(register=reg)\n block.phis.append(phi)\n\n logger.debug(\n f\"Created Phi assignment: {phi} while trying to resolve '{variable}' in {block}\"\n )\n return phi\n\n def _add_phi_operands(self, phi: ir.Phi, block: ir.BasicBlock) -> ir.Register:\n variable = phi.register.name\n for block_pred in block.predecessors:\n pred_variable = self.read_variable(variable, phi.ir_type, block_pred)\n phi.args.append(\n ir.PhiArgument(\n value=pred_variable,\n through=block_pred,\n )\n )\n logger.debug(f\"Added {pred_variable} to Phi node: {phi} in {block_pred}\")\n attrs.validate(phi)\n trivial_replacements = TrivialPhiRemover.try_remove(phi, self._all_blocks)\n if not trivial_replacements:\n return phi.register\n _, result = trivial_replacements[0]\n\n variable_def = self._current_def[variable]\n for removed_phi, replacement_memory in trivial_replacements:\n for unsealed_block, incomplete_phis in self._incomplete_phis.items():\n if removed_phi in incomplete_phis:\n raise InternalError(\n f\"removed an incomplete phi {removed_phi} from block {unsealed_block}!!\"\n )\n if replacement_memory.name != variable:\n raise InternalError(\n \"Tangled phi web created during SSA construction\",\n replacement_memory.source_location,\n )\n if removed_phi.register == result:\n result = replacement_memory\n # ensure replacement is also recorded in variable cache\n replacements = 0\n for block_def, arg in variable_def.items():\n if arg == removed_phi.register:\n variable_def[block_def] = replacement_memory\n replacements += 1\n logger.debug(\n f\"Replaced trivial Phi node: {removed_phi} ({removed_phi.register})\"\n f\" with {replacement_memory} in current definition for {replacements} blocks\"\n )\n return result\n\n def seal_block(self, block: ir.BasicBlock) -> None:\n logger.debug(f\"Sealing {block}\")\n if self.is_sealed(block):\n raise InternalError(f\"Cannot seal a block that was already sealed: {block}\")\n\n for predecessor in block.predecessors:\n if not predecessor.terminated:\n raise InternalError(f\"All predecessors must be terminated before sealing: {block}\")\n\n phi_list = self._incomplete_phis.pop(block, [])\n for phi in phi_list:\n self._add_phi_operands(phi, block)\n\n self._sealed_blocks.add(block)\n\n\n@attrs.define(kw_only=True)\nclass TrivialPhiRemover(IRMutator):\n _find: ir.Phi\n _replacement: ir.Register\n collected: list[ir.Phi] = attrs.field(factory=list)\n replaced: int = 0\n\n @classmethod\n def try_remove(\n cls, phi: ir.Phi, blocks: Sequence[ir.BasicBlock]\n ) -> list[tuple[ir.Phi, ir.Register]]:\n try:\n replacement, *other = {a.value for a in phi.non_self_args}\n except ValueError:\n # # per https:\/\/pp.ipd.kit.edu\/uploads\/publikationen\/buchwald16cc.pdf, section 4.1\n logger.warning(f\"Variable {phi.register.name} potentially used before assignment\")\n return []\n\n result = []\n # if other, then phi merges >1 value: not trivial\n if not other:\n result.append((phi, replacement))\n # replace users of phi with replacement\n logger.debug(f\"Replacing trivial Phi node: {phi} ({phi.register}) with {replacement}\")\n # this approach is not very efficient, but is simpler than tracking all usages\n # and good enough for now\n replacer = cls(find=phi, replacement=replacement)\n for block in blocks:\n replacer.visit_block(block)\n # recursively check\/replace all phi users, which may now be trivial\n for phi_user in replacer.collected:\n result.extend(cls.try_remove(phi_user, blocks))\n return result\n\n def visit_register(self, reg: ir.Register) -> ir.Register:\n if reg != self._find.register:\n return reg\n self.replaced += 1\n return self._replacement\n\n def visit_phi(self, phi: ir.Phi) -> ir.Phi | None:\n if phi is self._find:\n logger.debug(f\"Deleting Phi assignment: {phi}\")\n return None\n prior_replace_count = self.replaced\n result = super().visit_phi(phi)\n assert result is phi, \"phi instance changed\"\n if self.replaced > prior_replace_count:\n self.collected.append(result)\n return result\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/ssa.py","language":"Python","license":"NOASSERTION","size":9388} {"code":"import contextlib\nimport typing\nfrom collections.abc import Iterator, Sequence\n\nfrom puya import log\nfrom puya.context import ArtifactCompileContext\nfrom puya.ir import models\nfrom puya.ir.types_ import IRType\nfrom puya.ir.utils import format_bytes, format_error_comment\nfrom puya.ir.visitor import IRVisitor\nfrom puya.utils import make_path_relative_to_cwd\n\nlogger = log.get_logger(__name__)\n\n\nclass ToTextVisitor(IRVisitor[str]):\n @typing.override\n def visit_assignment(self, op: models.Assignment) -> str:\n targets = \", \".join(f\"{r.accept(self)}: {r.ir_type.name}\" for r in op.targets)\n if len(op.targets) > 1:\n targets = f\"({targets})\"\n source = op.source.accept(self)\n return f\"let {targets} = {source}\"\n\n @typing.override\n def visit_register(self, op: models.Register) -> str:\n return op.local_id\n\n @typing.override\n def visit_undefined(self, op: models.Undefined) -> str:\n return \"undefined\"\n\n @typing.override\n def visit_uint64_constant(self, op: models.UInt64Constant) -> str:\n return f\"{op.value}u\" if not op.teal_alias else op.teal_alias\n\n @typing.override\n def visit_biguint_constant(self, op: models.BigUIntConstant) -> str:\n return f\"{op.value}b\"\n\n @typing.override\n def visit_bytes_constant(self, op: models.BytesConstant) -> str:\n return format_bytes(op.value, op.encoding)\n\n @typing.override\n def visit_address_constant(self, op: models.AddressConstant) -> str:\n return f\"addr {op.value}\"\n\n @typing.override\n def visit_method_constant(self, op: models.MethodConstant) -> str:\n return f'method \"{op.value}\"'\n\n @typing.override\n def visit_itxn_constant(self, op: models.ITxnConstant) -> str:\n return f\"{op.ir_type.name}({op.value})\"\n\n @typing.override\n def visit_compiled_contract_reference(self, const: models.CompiledContractReference) -> str:\n return (\n \", \".join(\n (\n f\"compiled_contract({const.artifact!r}\",\n f\"field={const.field.name}\",\n f\"program_page={const.program_page}\",\n *(\n f\"{var}={val.accept(self)}\"\n for var, val in const.template_variables.items()\n ),\n )\n )\n + \")\"\n )\n\n @typing.override\n def visit_compiled_logicsig_reference(self, const: models.CompiledLogicSigReference) -> str:\n return (\n \", \".join(\n (\n f\"compiled_logicsig({const.artifact!r}\",\n *(\n f\"{var}={val.accept(self)}\"\n for var, val in const.template_variables.items()\n ),\n )\n )\n + \")\"\n )\n\n @typing.override\n def visit_intrinsic_op(self, intrinsic: models.Intrinsic) -> str:\n callee = intrinsic.op.code\n immediates = list(map(str, intrinsic.immediates))\n if immediates:\n callee = f\"({' '.join((callee, *immediates))})\"\n args = \" \".join(arg.accept(self) for arg in intrinsic.args)\n if args:\n callee = f\"({callee} {args})\"\n if intrinsic.error_message:\n callee += f\" \/\/ {format_error_comment(intrinsic.op.code, intrinsic.error_message)}\"\n return callee\n\n @typing.override\n def visit_inner_transaction_field(self, field: models.InnerTransactionField) -> str:\n group = field.group_index.accept(self)\n array_access = f\"[{field.array_index.accept(self)}]\" if field.array_index else \"\"\n return f\"itxn[{group}].{field.field}{array_access}\"\n\n @typing.override\n def visit_invoke_subroutine(self, op: models.InvokeSubroutine) -> str:\n args = \", \".join(a.accept(self) for a in op.args)\n return f\"{op.target.id}({args})\"\n\n @typing.override\n def visit_conditional_branch(self, op: models.ConditionalBranch) -> str:\n return f\"goto {op.condition.accept(self)} ? {op.non_zero} : {op.zero}\"\n\n @typing.override\n def visit_goto(self, op: models.Goto) -> str:\n return f\"goto {op.target}\"\n\n @typing.override\n def visit_goto_nth(self, op: models.GotoNth) -> str:\n blocks = \", \".join(map(str, op.blocks))\n return f\"goto_nth [{blocks}][{op.value.accept(self)}] else goto {op.default}\"\n\n @typing.override\n def visit_switch(self, op: models.Switch) -> str:\n cases = {k.accept(self): str(b) for k, b in op.cases.items()}\n cases[\"*\"] = str(op.default)\n map_ = \", \".join(f\"{k} => {v}\" for k, v in cases.items())\n return f\"switch {op.value.accept(self)} {{{map_}}}\"\n\n @typing.override\n def visit_subroutine_return(self, op: models.SubroutineReturn) -> str:\n results = \" \".join(r.accept(self) for r in op.result)\n return f\"return {results}\"\n\n @typing.override\n def visit_template_var(self, deploy_var: models.TemplateVar) -> str:\n return f\"TemplateVar[{deploy_var.ir_type.name}]({deploy_var.name})\"\n\n @typing.override\n def visit_program_exit(self, op: models.ProgramExit) -> str:\n return f\"exit {op.result.accept(self)}\"\n\n @typing.override\n def visit_fail(self, op: models.Fail) -> str:\n if op.error_message:\n return f\"fail \/\/ {op.error_message}\"\n return \"fail\"\n\n @typing.override\n def visit_phi(self, op: models.Phi) -> str:\n r = op.register\n target = f\"{r.accept(self)}: {r.ir_type.name}\"\n if op.args:\n args = \", \".join(a.accept(self) for a in op.args)\n source = f\"\u03c6({args})\"\n else:\n source = \"undefined\"\n return f\"let {target} = {source}\"\n\n @typing.override\n def visit_phi_argument(self, op: models.PhiArgument) -> str:\n return f\"{op.value.accept(self)} <- {op.through}\"\n\n @typing.override\n def visit_value_tuple(self, tup: models.ValueTuple) -> str:\n return \"(\" + \", \".join(val.accept(self) for val in tup.values) + \")\"\n\n\nclass TextEmitter:\n def __init__(self) -> None:\n self.lines = list[str]()\n self._indent = 0\n\n def append(self, line: str) -> None:\n self.lines.append((self._indent * \" \") + line)\n\n @contextlib.contextmanager\n def indent(self, spaces: int = 4) -> Iterator[None]:\n self._indent += spaces\n try:\n yield\n finally:\n self._indent -= spaces\n\n\ndef _render_block_name(block: models.BasicBlock) -> str:\n result = f\"{block}: \/\/ \"\n if block.comment:\n result += f\"{block.comment}_\"\n result += f\"L{block.source_location.line}\"\n return result\n\n\ndef _render_body(emitter: TextEmitter, blocks: Sequence[models.BasicBlock]) -> None:\n renderer = ToTextVisitor()\n for block in blocks:\n assert block.terminated\n emitter.append(_render_block_name(block))\n with emitter.indent():\n for op in block.all_ops:\n emitter.append(op.accept(renderer))\n\n\ndef render_program(\n context: ArtifactCompileContext, program: models.Program, *, qualifier: str\n) -> None:\n path = context.build_output_path(program.kind, qualifier, \"ir\")\n if path is None:\n return\n emitter = TextEmitter()\n emitter.append(f\"main {program.main.id}:\")\n with emitter.indent():\n _render_body(emitter, program.main.body)\n for sub in program.subroutines:\n emitter.append(\"\")\n args = \", \".join(f\"{r.name}: {r.ir_type.name}\" for r in sub.parameters)\n match sub.returns:\n case []:\n returns = \"void\"\n case [IRType(name=returns)]:\n pass\n case _ as ir_types:\n returns = f\"<{', '.join(t.name for t in ir_types)}>\"\n emitter.append(f\"subroutine {sub.id}({args}) -> {returns}:\")\n with emitter.indent():\n _render_body(emitter, sub.body)\n path.write_text(\"\\n\".join(emitter.lines), encoding=\"utf-8\")\n logger.debug(f\"Output IR to {make_path_relative_to_cwd(path)}\")\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/to_text_visitor.py","language":"Python","license":"NOASSERTION","size":8037} {"code":"import enum\nimport typing\nfrom collections.abc import Sequence\n\nfrom puya.avm import AVMType\nfrom puya.awst import (\n nodes as awst_nodes,\n wtypes,\n)\nfrom puya.awst.nodes import BytesEncoding\nfrom puya.errors import CodeError, InternalError\nfrom puya.ir.avm_ops_models import StackType\nfrom puya.parse import SourceLocation\n\n\n@enum.unique\nclass AVMBytesEncoding(enum.StrEnum):\n unknown = enum.auto()\n base16 = enum.auto()\n base32 = enum.auto()\n base64 = enum.auto()\n utf8 = enum.auto()\n\n\n@enum.unique\nclass IRType(enum.StrEnum):\n bytes = enum.auto()\n uint64 = enum.auto()\n bool = enum.auto()\n biguint = enum.auto()\n itxn_group_idx = enum.auto() # the group index of the result\n itxn_field_set = enum.auto() # a collection of fields for a pending itxn submit\n\n @property\n def avm_type(self) -> typing.Literal[AVMType.uint64, AVMType.bytes]:\n maybe_result = self.maybe_avm_type\n if not isinstance(maybe_result, AVMType):\n raise InternalError(f\"{maybe_result} cannot be mapped to AVM stack type\")\n return maybe_result\n\n @property\n def maybe_avm_type(self) -> typing.Literal[AVMType.uint64, AVMType.bytes] | str:\n match self:\n case IRType.uint64 | IRType.bool:\n return AVMType.uint64\n case IRType.bytes | IRType.biguint:\n return AVMType.bytes\n case IRType.itxn_group_idx | IRType.itxn_field_set:\n return self.name\n case _:\n typing.assert_never(self)\n\n\ndef bytes_enc_to_avm_bytes_enc(bytes_encoding: BytesEncoding) -> AVMBytesEncoding:\n try:\n return AVMBytesEncoding(bytes_encoding.value)\n except ValueError as ex:\n raise InternalError(f\"Unhandled BytesEncoding: {bytes_encoding}\") from ex\n\n\ndef wtype_to_ir_type(\n expr_or_wtype: wtypes.WType | awst_nodes.Expression,\n source_location: SourceLocation | None = None,\n) -> IRType:\n if isinstance(expr_or_wtype, awst_nodes.Expression):\n return wtype_to_ir_type(\n expr_or_wtype.wtype, source_location=source_location or expr_or_wtype.source_location\n )\n else:\n wtype = expr_or_wtype\n match wtype:\n case wtypes.bool_wtype:\n return IRType.bool\n case wtypes.biguint_wtype:\n return IRType.biguint\n case wtypes.WInnerTransaction():\n return IRType.itxn_group_idx\n case wtypes.WInnerTransactionFields():\n return IRType.itxn_field_set\n case wtypes.void_wtype:\n raise InternalError(\"can't translate void wtype to irtype\", source_location)\n # case wtypes.state_key:\n # return IRType.state_key # TODO\n # case wtypes.box_key:\n # return IRType.box_key # TODO\n match wtype.scalar_type:\n case AVMType.uint64:\n return IRType.uint64\n case AVMType.bytes:\n return IRType.bytes\n case None:\n raise CodeError(\n f\"unsupported nested\/compound wtype encountered: {wtype}\", source_location\n )\n case _:\n typing.assert_never(wtype.scalar_type)\n\n\ndef get_wtype_arity(wtype: wtypes.WType) -> int:\n \"\"\"Returns the number of values this wtype represents on the stack\"\"\"\n if isinstance(wtype, wtypes.WTuple):\n return sum_wtypes_arity(wtype.types)\n else:\n return 1\n\n\ndef sum_wtypes_arity(types: Sequence[wtypes.WType]) -> int:\n return sum(map(get_wtype_arity, types))\n\n\ndef wtype_to_ir_types(\n expr_or_wtype: wtypes.WType | awst_nodes.Expression,\n source_location: SourceLocation | None = None,\n) -> list[IRType]:\n if isinstance(expr_or_wtype, awst_nodes.Expression):\n wtype = expr_or_wtype.wtype\n else:\n wtype = expr_or_wtype\n if wtype == wtypes.void_wtype:\n return []\n elif isinstance(wtype, wtypes.WTuple):\n return [\n ir_type\n for wtype in wtype.types\n for ir_type in wtype_to_ir_types(wtype, source_location)\n ]\n else:\n return [wtype_to_ir_type(wtype, source_location)]\n\n\ndef stack_type_to_avm_type(stack_type: StackType) -> AVMType:\n match stack_type:\n case StackType.uint64 | StackType.bool | StackType.asset | StackType.application:\n return AVMType.uint64\n case (\n StackType.bytes\n | StackType.bigint\n | StackType.box_name\n | StackType.address\n | StackType.state_key\n ):\n return AVMType.bytes\n case StackType.any | StackType.address_or_index:\n return AVMType.any\n\n\ndef stack_type_to_ir_type(stack_type: StackType) -> IRType | None:\n match stack_type:\n case StackType.bool:\n return IRType.bool\n case StackType.bigint:\n return IRType.biguint\n case StackType.uint64 | StackType.asset | StackType.application:\n return IRType.uint64\n case StackType.bytes | StackType.box_name | StackType.address | StackType.state_key:\n return IRType.bytes\n case StackType.any | StackType.address_or_index:\n return None\n case _:\n typing.assert_never(stack_type)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/types_.py","language":"Python","license":"NOASSERTION","size":5198} {"code":"import base64\nfrom collections.abc import Sequence\n\nfrom puya.awst import (\n nodes as awst_nodes,\n wtypes,\n)\nfrom puya.ir.types_ import AVMBytesEncoding\n\n\ndef escape_utf8_string(s: str) -> str:\n \"\"\"Escape a UTF-8 string for use in TEAL assembly.\n\n Args:\n s: A UTF-8 string to escape.\n\n Returns:\n An escaped version of the input string. This version will be surrounded in double quotes,\n all special characters (such as \\\\n) will be escaped with additional backslashes, and all\n Unicode characters beyond the latin-1 encoding will be encoded in hex escapes (e.g. \\\\xf0).\n \"\"\"\n # The point of this conversion is to escape all special characters and turn all Unicode\n # characters into hex-escaped characters in the input string.\n #\n # The first step breaks up large Unicode characters into multiple UTF-8 hex characters:\n # s_1 = s.encode(\"utf-8\").decode(\"latin-1\")\n # e.g. \"\\n \ud83d\ude00\" => \"\\n \u00f0\\x9f\\x98\\x80\"\n #\n # The next step escapes all special characters:\n # s_1.encode(\"unicode-escape\").decode(\"latin-1\")\n # e.g. \"\\n \u00f0\\x9f\\x98\\x80\" => \"\\\\n \\\\xf0\\\\x9f\\\\x98\\\\x80\"\n #\n # If we skipped the first step we would end up with Unicode codepoints instead of hex escaped\n # characters, which TEAL assembly cannot process:\n # s.encode(\"unicode-escape\").decode(\"latin-1\")\n # e.g. \"\\n \ud83d\ude00\" => \"\\\\n \\\\U0001f600'\"\n s = s.encode(\"utf-8\").decode(\"latin-1\").encode(\"unicode-escape\").decode(\"latin-1\")\n\n # Escape double quote characters (not covered by unicode-escape) but leave in single quotes\n s = s.replace('\"', '\\\\\"')\n\n # Surround string in double quotes\n return '\"' + s + '\"'\n\n\ndef format_bytes(b: bytes, encoding: AVMBytesEncoding) -> str:\n match encoding:\n case AVMBytesEncoding.utf8:\n return escape_utf8_string(b.decode())\n case AVMBytesEncoding.base32:\n return base64.b32encode(b).decode(\"ascii\").rstrip(\"=\")\n case AVMBytesEncoding.base64:\n return base64.b64encode(b).decode(\"ascii\")\n case AVMBytesEncoding.base16 | AVMBytesEncoding.unknown:\n return f\"0x{b.hex()}\"\n\n\ndef format_tuple_index(var_type: wtypes.WTuple, base_name: str, index_or_name: int | str) -> str:\n # If a named tuple is indexed numerical, convert this to the item name\n if isinstance(index_or_name, int) and var_type.names is not None:\n index_or_name = var_type.names[index_or_name]\n return f\"{base_name}.{index_or_name}\"\n\n\ndef lvalue_items(tup: awst_nodes.TupleExpression) -> Sequence[awst_nodes.Lvalue]:\n items = list[awst_nodes.Lvalue]()\n for item in tup.items:\n assert isinstance(item, awst_nodes.Lvalue)\n items.append(item)\n return items\n\n\ndef format_error_comment(op: str, error_message: str) -> str:\n if op in (\"err\", \"assert\"):\n return error_message\n else:\n return f\"on error: {error_message}\"\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/utils.py","language":"Python","license":"NOASSERTION","size":2916} {"code":"","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/validation\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"import abc\nimport typing\n\nfrom puya.context import CompileContext\nfrom puya.ir.avm_ops_models import RunMode\nfrom puya.ir.models import Contract, LogicSignature, ModuleArtifact, Program\nfrom puya.ir.visitor import IRTraverser\n\n\nclass DestructuredIRValidator(IRTraverser, abc.ABC):\n def __init__(\n self,\n context: CompileContext,\n program: Program,\n run_mode: typing.Literal[RunMode.app, RunMode.lsig],\n ):\n self.context = context\n self.current_run_mode = run_mode\n self.active_program = program\n\n @classmethod\n def validate(cls, context: CompileContext, artifact: ModuleArtifact) -> None:\n match artifact:\n case LogicSignature() as l_sig:\n cls.validate_logic_sig(context, l_sig)\n case Contract() as contract:\n cls.validate_contract(context, contract)\n case _:\n typing.assert_never(artifact)\n\n @classmethod\n def validate_logic_sig(cls, context: CompileContext, logic_sig: LogicSignature) -> None:\n validator = cls(context, logic_sig.program, RunMode.lsig)\n for sub in logic_sig.program.all_subroutines:\n validator.visit_all_blocks(sub.body)\n\n @classmethod\n def validate_contract(cls, context: CompileContext, contract: Contract) -> None:\n for program in contract.all_programs():\n validator = cls(context, program, RunMode.app)\n for sub in program.all_subroutines:\n validator.visit_all_blocks(sub.body)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/validation\/_base.py","language":"Python","license":"NOASSERTION","size":1528} {"code":"import typing\nfrom collections.abc import Iterable\n\nfrom puya import log\nfrom puya.ir.models import (\n CompiledContractReference,\n CompiledLogicSigReference,\n Constant,\n TemplateVar,\n Value,\n)\nfrom puya.ir.validation._base import DestructuredIRValidator\n\nlogger = log.get_logger(__name__)\n\n\nclass CompileReferenceValidator(DestructuredIRValidator):\n @typing.override\n def visit_compiled_contract_reference(self, const: CompiledContractReference) -> None:\n _log_non_constant_values(const.template_variables.values())\n\n @typing.override\n def visit_compiled_logicsig_reference(self, const: CompiledLogicSigReference) -> None:\n _log_non_constant_values(const.template_variables.values())\n\n\ndef _log_non_constant_values(values: Iterable[Value]) -> None:\n for value in values:\n if isinstance(value, Constant):\n continue\n if isinstance(value, TemplateVar):\n logger.error(\n \"nested template variables are not supported\",\n location=value.source_location,\n )\n else:\n logger.error(\n \"non-constant template value\",\n location=value.source_location,\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/validation\/compile_reference_validator.py","language":"Python","license":"NOASSERTION","size":1219} {"code":"import typing\n\nfrom puya import log\nfrom puya.ir.models import InnerTransactionField, ITxnConstant\nfrom puya.ir.validation._base import DestructuredIRValidator\n\nlogger = log.get_logger(__name__)\n\n\nclass ITxnResultFieldValidator(DestructuredIRValidator):\n @typing.override\n def visit_itxn_constant(self, const: ITxnConstant) -> None:\n logger.info(\n \"Potential cause of field access with non-constant group index\",\n location=const.source_location,\n )\n\n @typing.override\n def visit_inner_transaction_field(self, field: InnerTransactionField) -> None:\n logger.error(\n \"Inner transaction field access with non constant group index,\"\n \" to resolve move field access to same code path where the inner transaction is\"\n \" submitted\",\n location=field.source_location,\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/validation\/itxn_result_field_validator.py","language":"Python","license":"NOASSERTION","size":867} {"code":"import attrs\n\nfrom puya.context import CompileContext\nfrom puya.ir.models import ModuleArtifact\nfrom puya.ir.validation.compile_reference_validator import CompileReferenceValidator\nfrom puya.ir.validation.itxn_result_field_validator import ITxnResultFieldValidator\nfrom puya.ir.validation.min_avm_version_validator import MinAvmVersionValidator\nfrom puya.ir.validation.op_run_mode_validator import OpRunModeValidator\n\n\ndef validate_module_artifact(context: CompileContext, artifact: ModuleArtifact) -> None:\n attrs.validate(artifact)\n for validator_cls in (\n OpRunModeValidator,\n MinAvmVersionValidator,\n ITxnResultFieldValidator,\n CompileReferenceValidator,\n ):\n validator_cls.validate(context, artifact)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/validation\/main.py","language":"Python","license":"NOASSERTION","size":750} {"code":"import typing\n\nfrom puya import log\nfrom puya.ir.models import Intrinsic\nfrom puya.ir.validation._base import DestructuredIRValidator\n\nlogger = log.get_logger(__name__)\n\n\nclass MinAvmVersionValidator(DestructuredIRValidator):\n @typing.override\n def visit_intrinsic_op(self, intrinsic: Intrinsic) -> None:\n program_avm_version = self.active_program.avm_version\n op_avm_version = intrinsic.op_variant.min_avm_version\n if op_avm_version > program_avm_version:\n op_desc = intrinsic.op.value\n # if variant min version differs from op min version, then include variant enum\n if op_avm_version != intrinsic.op.min_avm_version:\n op_desc += f\" {intrinsic.op_variant.enum}\"\n logger.error(\n f\"Opcode {op_desc!r} requires a min AVM version of \"\n f\"{op_avm_version} but the target AVM version is\"\n f\" {program_avm_version}\",\n location=intrinsic.source_location,\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/validation\/min_avm_version_validator.py","language":"Python","license":"NOASSERTION","size":1009} {"code":"import typing\n\nfrom puya import log\nfrom puya.ir.avm_ops_models import RunMode\nfrom puya.ir.models import Intrinsic\nfrom puya.ir.validation._base import DestructuredIRValidator\n\nlogger = log.get_logger(__name__)\n\n\nclass OpRunModeValidator(DestructuredIRValidator):\n @typing.override\n def visit_intrinsic_op(self, intrinsic: Intrinsic) -> None:\n match intrinsic.op_variant.supported_modes:\n case RunMode.any:\n pass\n case RunMode.app:\n if self.current_run_mode != RunMode.app:\n logger.warning(\n f\"The operation {intrinsic} is only allowed in smart contracts\",\n location=intrinsic.source_location,\n )\n case RunMode.lsig:\n if self.current_run_mode != RunMode.lsig:\n logger.warning(\n f\"The operation {intrinsic} is only allowed in logic signatures\",\n location=intrinsic.source_location,\n )\n case _:\n typing.assert_never(intrinsic.op_variant.supported_modes)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/validation\/op_run_mode_validator.py","language":"Python","license":"NOASSERTION","size":1138} {"code":"# ruff: noqa: ARG002\n\nfrom __future__ import annotations # needed to break import cycle\n\nimport typing as t\nfrom abc import ABC, abstractmethod\n\nif t.TYPE_CHECKING:\n from collections.abc import Iterable\n\n import puya.ir.models\n\n\nclass IRVisitor[T](ABC):\n @abstractmethod\n def visit_assignment(self, ass: puya.ir.models.Assignment) -> T: ...\n\n @abstractmethod\n def visit_register(self, reg: puya.ir.models.Register) -> T: ...\n\n @abstractmethod\n def visit_undefined(self, val: puya.ir.models.Undefined) -> T: ...\n\n @abstractmethod\n def visit_uint64_constant(self, const: puya.ir.models.UInt64Constant) -> T: ...\n\n @abstractmethod\n def visit_biguint_constant(self, const: puya.ir.models.BigUIntConstant) -> T: ...\n\n @abstractmethod\n def visit_bytes_constant(self, const: puya.ir.models.BytesConstant) -> T: ...\n\n @abstractmethod\n def visit_compiled_contract_reference(\n self, const: puya.ir.models.CompiledContractReference\n ) -> T: ...\n\n @abstractmethod\n def visit_compiled_logicsig_reference(\n self, const: puya.ir.models.CompiledLogicSigReference\n ) -> T: ...\n\n @abstractmethod\n def visit_address_constant(self, const: puya.ir.models.AddressConstant) -> T: ...\n\n @abstractmethod\n def visit_method_constant(self, const: puya.ir.models.MethodConstant) -> T: ...\n\n @abstractmethod\n def visit_itxn_constant(self, const: puya.ir.models.ITxnConstant) -> T: ...\n\n @abstractmethod\n def visit_phi(self, phi: puya.ir.models.Phi) -> T: ...\n\n @abstractmethod\n def visit_phi_argument(self, arg: puya.ir.models.PhiArgument) -> T: ...\n\n @abstractmethod\n def visit_intrinsic_op(self, intrinsic: puya.ir.models.Intrinsic) -> T: ...\n\n @abstractmethod\n def visit_inner_transaction_field(\n self, intrinsic: puya.ir.models.InnerTransactionField\n ) -> T: ...\n\n @abstractmethod\n def visit_invoke_subroutine(self, callsub: puya.ir.models.InvokeSubroutine) -> T: ...\n\n @abstractmethod\n def visit_value_tuple(self, tup: puya.ir.models.ValueTuple) -> T: ...\n\n @abstractmethod\n def visit_conditional_branch(self, branch: puya.ir.models.ConditionalBranch) -> T: ...\n\n @abstractmethod\n def visit_goto(self, goto: puya.ir.models.Goto) -> T: ...\n\n @abstractmethod\n def visit_goto_nth(self, goto_nth: puya.ir.models.GotoNth) -> T: ...\n\n @abstractmethod\n def visit_switch(self, switch: puya.ir.models.Switch) -> T: ...\n\n @abstractmethod\n def visit_subroutine_return(self, retsub: puya.ir.models.SubroutineReturn) -> T: ...\n\n @abstractmethod\n def visit_program_exit(self, exit_: puya.ir.models.ProgramExit) -> T: ...\n\n @abstractmethod\n def visit_fail(self, fail: puya.ir.models.Fail) -> T: ...\n\n @abstractmethod\n def visit_template_var(self, deploy_var: puya.ir.models.TemplateVar) -> T: ...\n\n\nclass IRTraverser(IRVisitor[None]):\n def visit_all_blocks(self, blocks: Iterable[puya.ir.models.BasicBlock]) -> None:\n for block in blocks:\n self.visit_block(block)\n\n def visit_block(self, block: puya.ir.models.BasicBlock) -> None:\n for op in list(block.all_ops): # make a copy in case visitors need to modify ops\n op.accept(self)\n\n def visit_assignment(self, ass: puya.ir.models.Assignment) -> None:\n for target in ass.targets:\n target.accept(self)\n ass.source.accept(self)\n\n def visit_register(self, reg: puya.ir.models.Register) -> None:\n pass\n\n def visit_undefined(self, val: puya.ir.models.Undefined) -> None:\n pass\n\n def visit_uint64_constant(self, const: puya.ir.models.UInt64Constant) -> None:\n pass\n\n def visit_biguint_constant(self, const: puya.ir.models.BigUIntConstant) -> None:\n pass\n\n def visit_bytes_constant(self, const: puya.ir.models.BytesConstant) -> None:\n pass\n\n def visit_address_constant(self, const: puya.ir.models.AddressConstant) -> None:\n pass\n\n def visit_template_var(self, deploy_var: puya.ir.models.TemplateVar) -> None:\n pass\n\n def visit_method_constant(self, const: puya.ir.models.MethodConstant) -> None:\n pass\n\n def visit_compiled_contract_reference(\n self, const: puya.ir.models.CompiledContractReference\n ) -> None:\n for var in const.template_variables.values():\n var.accept(self)\n\n def visit_compiled_logicsig_reference(\n self, const: puya.ir.models.CompiledLogicSigReference\n ) -> None:\n for var in const.template_variables.values():\n var.accept(self)\n\n def visit_itxn_constant(self, const: puya.ir.models.ITxnConstant) -> None:\n pass\n\n def visit_phi(self, phi: puya.ir.models.Phi) -> None:\n phi.register.accept(self)\n for arg in phi.args:\n arg.accept(self)\n\n def visit_phi_argument(self, arg: puya.ir.models.PhiArgument) -> None:\n arg.value.accept(self)\n\n def visit_intrinsic_op(self, intrinsic: puya.ir.models.Intrinsic) -> None:\n for arg in intrinsic.args:\n arg.accept(self)\n\n def visit_inner_transaction_field(self, field: puya.ir.models.InnerTransactionField) -> None:\n field.group_index.accept(self)\n field.is_last_in_group.accept(self)\n if field.array_index:\n field.array_index.accept(self)\n\n def visit_invoke_subroutine(self, callsub: puya.ir.models.InvokeSubroutine) -> None:\n for arg in callsub.args:\n arg.accept(self)\n\n def visit_conditional_branch(self, branch: puya.ir.models.ConditionalBranch) -> None:\n branch.condition.accept(self)\n\n def visit_goto(self, goto: puya.ir.models.Goto) -> None:\n pass\n\n def visit_goto_nth(self, goto_nth: puya.ir.models.GotoNth) -> None:\n goto_nth.value.accept(self)\n\n def visit_switch(self, switch: puya.ir.models.Switch) -> None:\n switch.value.accept(self)\n for case in switch.cases:\n case.accept(self)\n\n def visit_subroutine_return(self, retsub: puya.ir.models.SubroutineReturn) -> None:\n for r in retsub.result:\n r.accept(self)\n\n def visit_program_exit(self, exit_: puya.ir.models.ProgramExit) -> None:\n exit_.result.accept(self)\n\n def visit_fail(self, fail: puya.ir.models.Fail) -> None:\n pass\n\n def visit_value_tuple(self, tup: puya.ir.models.ValueTuple) -> None:\n for v in tup.values:\n v.accept(self)\n\n\nclass NoOpIRVisitor[T](IRVisitor[T | None]):\n def visit_assignment(self, ass: puya.ir.models.Assignment) -> T | None:\n return None\n\n def visit_register(self, reg: puya.ir.models.Register) -> T | None:\n return None\n\n def visit_undefined(self, val: puya.ir.models.Undefined) -> T | None:\n return None\n\n def visit_uint64_constant(self, const: puya.ir.models.UInt64Constant) -> T | None:\n return None\n\n def visit_biguint_constant(self, const: puya.ir.models.BigUIntConstant) -> T | None:\n return None\n\n def visit_bytes_constant(self, const: puya.ir.models.BytesConstant) -> T | None:\n return None\n\n def visit_address_constant(self, const: puya.ir.models.AddressConstant) -> T | None:\n return None\n\n def visit_method_constant(self, const: puya.ir.models.MethodConstant) -> T | None:\n return None\n\n def visit_itxn_constant(self, const: puya.ir.models.ITxnConstant) -> T | None:\n return None\n\n def visit_compiled_contract_reference(\n self, const: puya.ir.models.CompiledContractReference\n ) -> T | None:\n return None\n\n def visit_compiled_logicsig_reference(\n self, const: puya.ir.models.CompiledLogicSigReference\n ) -> T | None:\n return None\n\n def visit_phi(self, phi: puya.ir.models.Phi) -> T | None:\n return None\n\n def visit_template_var(self, deploy_var: puya.ir.models.TemplateVar) -> T | None:\n return None\n\n def visit_phi_argument(self, arg: puya.ir.models.PhiArgument) -> T | None:\n return None\n\n def visit_intrinsic_op(self, intrinsic: puya.ir.models.Intrinsic) -> T | None:\n return None\n\n def visit_inner_transaction_field(\n self, field: puya.ir.models.InnerTransactionField\n ) -> T | None:\n return None\n\n def visit_invoke_subroutine(self, callsub: puya.ir.models.InvokeSubroutine) -> T | None:\n return None\n\n def visit_value_tuple(self, tup: puya.ir.models.ValueTuple) -> T | None:\n return None\n\n def visit_conditional_branch(self, branch: puya.ir.models.ConditionalBranch) -> T | None:\n return None\n\n def visit_goto(self, goto: puya.ir.models.Goto) -> T | None:\n return None\n\n def visit_goto_nth(self, goto_nth: puya.ir.models.GotoNth) -> T | None:\n return None\n\n def visit_switch(self, switch: puya.ir.models.Switch) -> T | None:\n return None\n\n def visit_subroutine_return(self, retsub: puya.ir.models.SubroutineReturn) -> T | None:\n return None\n\n def visit_program_exit(self, exit_: puya.ir.models.ProgramExit) -> T | None:\n return None\n\n def visit_fail(self, fail: puya.ir.models.Fail) -> T | None:\n return None\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/visitor.py","language":"Python","license":"NOASSERTION","size":9096} {"code":"from collections.abc import Iterable, Mapping\n\nimport attrs\n\nfrom puya.ir import models\nfrom puya.ir.visitor_mutator import IRMutator\n\n\n@attrs.define\nclass MemoryReplacer(IRMutator):\n _replacements: Mapping[models.Register, models.Register]\n replaced: int = 0\n\n @classmethod\n def apply(\n cls,\n blocks: Iterable[models.BasicBlock],\n *,\n replacements: Mapping[models.Register, models.Register],\n ) -> int:\n if not replacements:\n return 0\n replacer = cls(replacements=replacements)\n for block in blocks:\n replacer.visit_block(block)\n return replacer.replaced\n\n def visit_register(self, reg: models.Register) -> models.Register:\n try:\n replacement = self._replacements[reg]\n except KeyError:\n return reg\n self.replaced += 1\n return replacement\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/visitor_mem_replacer.py","language":"Python","license":"NOASSERTION","size":886} {"code":"import typing as t\n\nimport attrs\n\nfrom puya.ir import models\nfrom puya.ir.visitor import IRVisitor\n\n\n@attrs.define\nclass IRMutator(IRVisitor[t.Any]):\n def visit_block(self, block: models.BasicBlock) -> None:\n new_phis = []\n for phi in block.phis:\n new_phi = self.visit_phi(phi)\n if new_phi is not None:\n new_phis.append(new_phi)\n block.phis = new_phis\n new_ops = []\n for op in block.ops:\n new_op = op.accept(self)\n if new_op is not None:\n new_ops.append(new_op)\n block.ops = new_ops\n if block.terminator is not None:\n block.terminator = block.terminator.accept(self)\n\n def visit_assignment(self, ass: models.Assignment) -> models.Assignment | None:\n ass.targets = [self.visit_register(r) for r in ass.targets]\n ass.source = ass.source.accept(self)\n return ass\n\n def visit_register(self, reg: models.Register) -> models.Register:\n return reg\n\n def visit_undefined(self, val: models.Undefined) -> models.Undefined:\n return val\n\n def visit_template_var(self, deploy_var: models.TemplateVar) -> models.TemplateVar:\n return deploy_var\n\n def visit_uint64_constant(self, const: models.UInt64Constant) -> models.UInt64Constant:\n return const\n\n def visit_biguint_constant(self, const: models.BigUIntConstant) -> models.BigUIntConstant:\n return const\n\n def visit_bytes_constant(self, const: models.BytesConstant) -> models.BytesConstant:\n return const\n\n def visit_address_constant(self, const: models.AddressConstant) -> models.AddressConstant:\n return const\n\n def visit_method_constant(self, const: models.MethodConstant) -> models.MethodConstant:\n return const\n\n def visit_itxn_constant(self, const: models.ITxnConstant) -> models.ITxnConstant:\n return const\n\n def visit_compiled_contract_reference(\n self, const: models.CompiledContractReference\n ) -> models.CompiledContractReference:\n return attrs.evolve(\n const,\n template_variables={\n var: value.accept(self) for var, value in const.template_variables.items()\n },\n )\n\n def visit_compiled_logicsig_reference(\n self, const: models.CompiledLogicSigReference\n ) -> models.CompiledLogicSigReference:\n return attrs.evolve(\n const,\n template_variables={\n var: value.accept(self) for var, value in const.template_variables.items()\n },\n )\n\n def visit_phi(self, phi: models.Phi) -> models.Phi | None:\n phi.register = self.visit_register(phi.register)\n phi.args = [self.visit_phi_argument(a) for a in phi.args]\n return phi\n\n def visit_phi_argument(self, arg: models.PhiArgument) -> models.PhiArgument:\n arg.value = arg.value.accept(self)\n return arg\n\n def visit_intrinsic_op(self, intrinsic: models.Intrinsic) -> models.Intrinsic | None:\n intrinsic.args = [a.accept(self) for a in intrinsic.args]\n return intrinsic\n\n def visit_inner_transaction_field(\n self, field: models.InnerTransactionField\n ) -> models.InnerTransactionField | models.Intrinsic:\n field.group_index = field.group_index.accept(self)\n field.is_last_in_group = field.is_last_in_group.accept(self)\n if field.array_index:\n field.array_index = field.array_index.accept(self)\n return field\n\n def visit_invoke_subroutine(self, callsub: models.InvokeSubroutine) -> models.InvokeSubroutine:\n callsub.args = [a.accept(self) for a in callsub.args]\n return callsub\n\n def visit_conditional_branch(self, branch: models.ConditionalBranch) -> models.ControlOp:\n branch.condition = branch.condition.accept(self)\n return branch\n\n def visit_goto_nth(self, goto_nth: models.GotoNth) -> models.ControlOp:\n goto_nth.value = goto_nth.value.accept(self)\n return goto_nth\n\n def visit_goto(self, goto: models.Goto) -> models.ControlOp:\n return goto\n\n def visit_switch(self, switch: models.Switch) -> models.ControlOp:\n switch.value = switch.value.accept(self)\n switch.cases = {case.accept(self): target for case, target in switch.cases.items()}\n return switch\n\n def visit_subroutine_return(self, retsub: models.SubroutineReturn) -> models.ControlOp:\n retsub.result = [v.accept(self) for v in retsub.result]\n return retsub\n\n def visit_program_exit(self, exit_: models.ProgramExit) -> models.ControlOp:\n exit_.result = exit_.result.accept(self)\n return exit_\n\n def visit_fail(self, fail: models.Fail) -> models.ControlOp:\n return fail\n\n def visit_value_tuple(self, tup: models.ValueTuple) -> models.ValueTuple:\n tup.values = [v.accept(self) for v in tup.values]\n return tup\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/visitor_mutator.py","language":"Python","license":"NOASSERTION","size":4908} {"code":"import itertools\nimport typing\nfrom collections.abc import Sequence, Set\n\nimport attrs\n\nfrom puya.errors import InternalError\nfrom puya.ir import models as ops\nfrom puya.ir.visitor import IRTraverser\nfrom puya.utils import StableSet\n\nIrOp: typing.TypeAlias = ops.Op | ops.ControlOp | ops.Phi\n\n\n@attrs.define(kw_only=True)\nclass _OpLifetime:\n block: ops.BasicBlock\n used: StableSet[ops.Register] = attrs.field(on_setattr=attrs.setters.frozen)\n defined: StableSet[ops.Register] = attrs.field(on_setattr=attrs.setters.frozen)\n successors: Sequence[IrOp] = attrs.field(on_setattr=attrs.setters.frozen)\n\n live_in: StableSet[ops.Register] = attrs.field(factory=StableSet)\n live_out: StableSet[ops.Register] = attrs.field(factory=StableSet)\n\n\n@attrs.define\nclass _VlaTraverser(IRTraverser):\n used: StableSet[ops.Register] = attrs.field(factory=StableSet)\n defined: StableSet[ops.Register] = attrs.field(factory=StableSet)\n\n @classmethod\n def apply(cls, op: IrOp) -> tuple[StableSet[ops.Register], StableSet[ops.Register]]:\n traverser = cls()\n op.accept(traverser)\n return traverser.used, traverser.defined\n\n def visit_register(self, reg: ops.Register) -> None:\n self.used.add(reg)\n\n def visit_assignment(self, ass: ops.Assignment) -> None:\n ass.source.accept(self)\n self.defined = StableSet.from_iter(ass.targets)\n\n def visit_phi(self, _phi: ops.Phi) -> None:\n # WARNING: this is slightly trickier than it might seem for SSA,\n # consider how this translates when coming out of SSA -\n # the target register isn't defined here, but defined at\n # the end of each predecessor block.\n # Similarly, the arguments aren't live-in at this location necessarily.\n raise InternalError(\"IR VLA not capable of handling SSA yet\")\n\n\n@attrs.define\nclass VariableLifetimeAnalysis:\n \"\"\"Performs VLA analysis for a subroutine, providing a mapping of ops to sets of live local_ids\n see https:\/\/www.classes.cs.uchicago.edu\/archive\/2004\/spring\/22620-1\/docs\/liveness.pdf\"\"\"\n\n subroutine: ops.Subroutine\n _op_lifetimes: dict[IrOp, _OpLifetime] = attrs.field(init=False)\n\n @_op_lifetimes.default\n def _op_lifetimes_factory(self) -> dict[IrOp, _OpLifetime]:\n result = dict[IrOp, _OpLifetime]()\n block_map = {b.id: next(b.all_ops) for b in self.subroutine.body}\n for block in self.subroutine.body:\n assert not block.phis\n all_ops = list(block.all_ops)\n for op, next_op in itertools.zip_longest(all_ops, all_ops[1:]):\n used, defined = _VlaTraverser.apply(op)\n if next_op is None:\n # for last op, add first op of each successor block\n successors = [block_map[s.id] for s in block.successors]\n else:\n successors = [next_op]\n result[op] = _OpLifetime(\n block=block,\n used=used,\n defined=defined,\n successors=successors,\n )\n return result\n\n def get_live_out_variables(self, op: IrOp) -> Set[ops.Register]:\n return self._op_lifetimes[op].live_out\n\n def get_live_in_variables(self, op: IrOp) -> Set[ops.Register]:\n return self._op_lifetimes[op].live_in\n\n @classmethod\n def analyze(cls, subroutine: ops.Subroutine) -> typing.Self:\n analysis = cls(subroutine)\n analysis._analyze() # noqa: SLF001\n return analysis\n\n def _analyze(self) -> None:\n changes = True\n while changes:\n changes = False\n for n in self._op_lifetimes.values():\n # For OUT, find out the union of previous variables\n # in the IN set for each succeeding node of n.\n\n # out[n] = U s \u2208 succ[n] in[s]\n live_out = StableSet[ops.Register]()\n for s in n.successors:\n live_out |= self._op_lifetimes[s].live_in\n\n # in[n] = use[n] U (out[n] - def [n])\n live_in = n.used | (live_out - n.defined)\n\n if not (live_in == n.live_in and live_out == n.live_out):\n n.live_in = live_in\n n.live_out = live_out\n changes = True\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ir\/vla.py","language":"Python","license":"NOASSERTION","size":4360} {"code":"import contextlib\nimport json\nimport logging\nimport os.path\nimport sys\nimport typing\nfrom collections import Counter\nfrom collections.abc import Iterator, Mapping, Sequence\nfrom contextvars import ContextVar\nfrom enum import IntEnum, StrEnum, auto\nfrom io import StringIO\nfrom pathlib import Path\n\nimport attrs\nimport structlog\n\nfrom puya.parse import SourceLocation\n\n\nclass LogFormat(StrEnum):\n default = auto()\n json = auto()\n\n @staticmethod\n def from_string(s: str) -> \"LogFormat\":\n try:\n return LogFormat[s]\n except KeyError as err:\n raise ValueError from err\n\n\nclass LogLevel(IntEnum):\n notset = logging.NOTSET\n debug = logging.DEBUG\n info = logging.INFO\n warning = logging.WARNING\n error = logging.ERROR\n critical = logging.CRITICAL\n\n def __str__(self) -> str:\n return self.name\n\n @staticmethod\n def from_string(s: str) -> \"LogLevel\":\n try:\n return LogLevel[s]\n except KeyError as err:\n raise ValueError from err\n\n\n@attrs.frozen\nclass Log:\n level: LogLevel\n message: str\n location: SourceLocation | None\n\n @property\n def file(self) -> Path | None:\n return None if self.location is None else self.location.file\n\n @property\n def line(self) -> int | None:\n return None if self.location is None else self.location.line\n\n\n@attrs.define\nclass LoggingContext:\n logs: list[Log] = attrs.field(factory=list)\n sources_by_path: Mapping[Path, Sequence[str] | None] | None = None\n\n def _log_level_counts(self) -> Mapping[LogLevel, int]:\n return Counter(log.level for log in self.logs)\n\n @property\n def num_errors(self) -> int:\n level_counts = self._log_level_counts()\n return sum(count for level, count in level_counts.items() if level >= LogLevel.error)\n\n def exit_if_errors(self) -> None:\n level_counts = self._log_level_counts()\n if level_counts[LogLevel.critical]:\n sys.exit(2)\n elif level_counts[LogLevel.error]:\n sys.exit(1)\n\n\n_current_ctx: ContextVar[LoggingContext] = ContextVar(\"current_ctx\")\n\n\nclass PuyaJsonRender(structlog.processors.JSONRenderer):\n def __init__(self, *, base_path: str) -> None:\n super().__init__()\n self.base_path = base_path + os.path.sep\n\n def _location_json(\n self, location: SourceLocation | None\n ) -> Mapping[str, str | int | None] | None:\n if not location or not location.file:\n return None\n\n file = str(location.file)\n if file.startswith(self.base_path):\n file = file[len(self.base_path) :]\n\n return {\n \"file\": file,\n \"line\": location.line,\n \"end_line\": location.end_line,\n \"column\": location.column,\n \"end_column\": location.end_column,\n }\n\n def __call__(\n self,\n _logger: structlog.typing.WrappedLogger,\n _name: str,\n event_dict: structlog.typing.EventDict,\n ) -> str:\n # force event to str for compatibility with standard library\n event = event_dict.pop(\"event\", None)\n if not isinstance(event, str):\n event = str(event)\n\n important: bool = event_dict.pop(\"important\", False)\n location: SourceLocation | None = event_dict.pop(\"location\", None)\n level = event_dict.pop(\"level\", \"info\")\n\n return json.dumps(\n {\n \"level\": level,\n \"location\": self._location_json(location),\n \"message\": event,\n \"important\": important,\n }\n )\n\n\nclass PuyaConsoleRender(structlog.dev.ConsoleRenderer):\n def __init__(self, *, colors: bool, base_path: str):\n super().__init__(colors=colors)\n self.level_to_color = self.get_default_level_styles(colors)\n self.base_path = base_path\n if not self.base_path.endswith(\n os.path.sep\n ): # TODO: can we always append the path seperator?\n self.base_path += os.path.sep\n\n def _location_as_link(self, location: SourceLocation | None) -> str:\n if not location or not location.file:\n return \"\"\n\n file = str(location.file)\n if file.startswith(self.base_path):\n file = file[len(self.base_path) :]\n\n line = str(location.line) if location.line else \"1\"\n col = f\":{location.column + 1}\" if location.column else \"\"\n return f\"{file}:{line}{col}\"\n\n def __call__(\n self,\n _logger: structlog.typing.WrappedLogger,\n _name: str,\n event_dict: structlog.typing.EventDict,\n ) -> str:\n # force event to str for compatibility with standard library\n event = event_dict.pop(\"event\", None)\n if not isinstance(event, str):\n event = str(event)\n lines = [event]\n related_errors = event_dict.pop(\"related_lines\", None)\n if related_errors:\n assert isinstance(related_errors, list)\n lines.extend(related_errors)\n important: bool = event_dict.pop(\"important\", False)\n location: SourceLocation | None = event_dict.pop(\"location\", None)\n if location and location.file is None:\n location = None\n location_as_link = self._location_as_link(location) if location else \"\"\n level = event_dict.pop(\"level\", \"info\")\n\n align_related_lines = \" \" * (len(location_as_link) + 1 + len(level) + 1)\n sio = StringIO()\n reset_colour = self._styles.reset\n if important:\n sio.write(self._styles.bright)\n reset_colour += self._styles.bright\n for idx, line in enumerate(lines):\n if idx:\n sio.write(\"\\n\")\n sio.write(align_related_lines)\n else:\n if location:\n sio.write(self._styles.logger_name)\n location_link = self._location_as_link(location)\n sio.write(location_link)\n sio.write(\" \")\n sio.write(reset_colour)\n\n sio.write(self.level_to_color.get(level, \"\"))\n sio.write(level)\n sio.write(\": \")\n sio.write(reset_colour)\n sio.write(line)\n sio.write(self._styles.reset)\n\n stack = event_dict.pop(\"stack\", None)\n exc = event_dict.pop(\"exception\", None)\n exc_info = event_dict.pop(\"exc_info\", None)\n\n event_dict_keys: typing.Iterable[str] = event_dict.keys()\n if self._sort_keys:\n event_dict_keys = sorted(event_dict_keys)\n\n sio.write(\n \" \".join(\n self._styles.kv_key\n + key\n + self._styles.reset\n + \"=\"\n + self._styles.kv_value\n + self._repr(event_dict[key])\n + self._styles.reset\n for key in event_dict_keys\n )\n )\n\n if stack is not None:\n sio.write(\"\\n\" + stack)\n if exc_info or exc is not None:\n sio.write(\"\\n\\n\" + \"=\" * 79 + \"\\n\")\n\n if exc_info:\n exc_info = figure_out_exc_info(exc_info)\n\n self._exception_formatter(sio, exc_info)\n elif exc is not None:\n sio.write(\"\\n\" + exc)\n\n return sio.getvalue()\n\n\n# copied from structlog.dev._figure_out_exc_info\ndef figure_out_exc_info(\n v: BaseException | structlog.typing.ExcInfo | bool,\n) -> structlog.typing.ExcInfo | bool:\n \"\"\"\n Depending on the Python version will try to do the smartest thing possible\n to transform *v* into an ``exc_info`` tuple.\n \"\"\"\n if isinstance(v, BaseException):\n return type(v), v, v.__traceback__\n\n if isinstance(v, tuple):\n return v\n\n if v:\n return sys.exc_info() # type: ignore[return-value]\n\n return v\n\n\n@attrs.define\nclass FilterByLogLevel:\n min_log_level: LogLevel\n\n def __call__(\n self,\n _logger: structlog.typing.WrappedLogger,\n method: str,\n event_dict: structlog.typing.EventDict,\n ) -> structlog.typing.EventDict:\n if LogLevel[method] < self.min_log_level:\n raise structlog.DropEvent\n return event_dict\n\n\ndef configure_logging(\n *,\n min_log_level: LogLevel = LogLevel.notset,\n cache_logger: bool = True,\n log_format: LogFormat = LogFormat.default,\n) -> None:\n if cache_logger and structlog.is_configured():\n raise ValueError(\n \"Logging can not be configured more than once if using cache_logger = True\"\n )\n base_path = str(Path.cwd()) # TODO: don't assume this?\n match log_format:\n case LogFormat.json:\n log_renderer: structlog.typing.Processor = PuyaJsonRender(base_path=base_path)\n case LogFormat.default:\n log_renderer = PuyaConsoleRender(\n colors=\"NO_COLOR\" not in os.environ, base_path=base_path\n )\n case never:\n typing.assert_never(never)\n\n processors: list[structlog.typing.Processor] = [\n structlog.contextvars.merge_contextvars,\n structlog.processors.add_log_level,\n structlog.processors.StackInfoRenderer(),\n log_renderer,\n ]\n if min_log_level != LogLevel.notset:\n # filtering via a processor instead of via the logger like\n # structlog.make_filtering_bound_logger(min_log_level.value)\n # so that structlog.testing.capture_logs() still works in test cases\n processors.insert(0, FilterByLogLevel(min_log_level))\n structlog.configure(\n processors=processors,\n context_class=dict,\n logger_factory=structlog.PrintLoggerFactory(),\n cache_logger_on_first_use=cache_logger,\n )\n\n\nclass _Logger:\n def __init__(self, name: str, initial_values: dict[str, typing.Any]):\n self._logger = structlog.get_logger(name, **initial_values)\n\n def debug(\n self,\n event: object,\n *args: typing.Any,\n location: SourceLocation | None = None,\n **kwargs: typing.Any,\n ) -> None:\n self._report(LogLevel.debug, event, *args, location=location, **kwargs)\n\n def info(\n self,\n event: object,\n *args: typing.Any,\n location: SourceLocation | None = None,\n **kwargs: typing.Any,\n ) -> None:\n self._report(LogLevel.info, event, *args, location=location, **kwargs)\n\n def warning(\n self,\n event: object,\n *args: typing.Any,\n location: SourceLocation | None = None,\n **kwargs: typing.Any,\n ) -> None:\n self._report(LogLevel.warning, event, *args, location=location, **kwargs)\n\n def error(\n self,\n event: object,\n *args: typing.Any,\n location: SourceLocation | None = None,\n **kwargs: typing.Any,\n ) -> None:\n self._report(LogLevel.error, event, *args, location=location, **kwargs)\n\n def exception(\n self,\n event: object,\n *args: typing.Any,\n location: SourceLocation | None = None,\n **kwargs: typing.Any,\n ) -> None:\n kwargs.setdefault(\"exc_info\", True)\n self._report(LogLevel.critical, event, *args, location=location, **kwargs)\n\n def critical(\n self,\n event: object,\n *args: typing.Any,\n location: SourceLocation | None = None,\n **kwargs: typing.Any,\n ) -> None:\n self._report(LogLevel.critical, event, *args, location=location, **kwargs)\n\n def log(\n self,\n level: LogLevel,\n event: object,\n *args: typing.Any,\n location: SourceLocation | None = None,\n **kwargs: typing.Any,\n ) -> None:\n self._report(level, event, *args, location=location, **kwargs)\n\n def _report(\n self,\n level: LogLevel,\n event: object,\n *args: typing.Any,\n location: SourceLocation | None = None,\n **kwargs: typing.Any,\n ) -> None:\n log_ctx = _current_ctx.get(None)\n if (\n level >= LogLevel.error\n and location\n and log_ctx\n and log_ctx.sources_by_path\n and location.file\n ):\n file_source = log_ctx.sources_by_path.get(location.file)\n if file_source is not None:\n kwargs[\"related_lines\"] = _get_pretty_source(file_source, location)\n self._logger.log(level, event, *args, location=location, **kwargs)\n if log_ctx:\n if isinstance(event, str) and args:\n message = event % args\n else:\n message = str(event)\n log_ctx.logs.append(Log(level, message, location))\n\n\ndef _get_pretty_source(\n file_source: Sequence[str], location: SourceLocation\n) -> Sequence[str] | None:\n lines = file_source[location.line - 1 : location.end_line]\n if len(lines) != location.line_count:\n logger = get_logger(__name__)\n logger.warning(f\"source length mismatch for {location}\")\n return None\n try:\n (source_line,) = lines\n except ValueError:\n # source line is followed by additional lines, don't bother annotating columns\n return lines\n # Shifts column after tab expansion\n column = len(source_line[: location.column].expandtabs())\n end_column = len(source_line[: location.end_column].expandtabs())\n\n return [\n source_line.expandtabs(),\n \" \" * column + f\"^{'~' * max(end_column - column - 1, 0)}\",\n ]\n\n\ndef get_logger(name: str, **initial_values: typing.Any) -> _Logger:\n return _Logger(name, initial_values)\n\n\n@contextlib.contextmanager\ndef logging_context() -> Iterator[LoggingContext]:\n ctx = LoggingContext()\n restore = _current_ctx.set(ctx)\n try:\n yield ctx\n finally:\n _current_ctx.reset(restore)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/log.py","language":"Python","license":"NOASSERTION","size":13780} {"code":"from pathlib import Path\n\nimport attrs\nimport cattrs.preconf.json\n\nfrom puya import log\nfrom puya.awst import (\n nodes as awst_nodes,\n serialize,\n)\nfrom puya.compile import awst_to_teal\nfrom puya.errors import log_exceptions\nfrom puya.options import PuyaOptions\nfrom puya.program_refs import ContractReference, LogicSigReference\n\nlogger = log.get_logger(__name__)\n\n\n@attrs.frozen(kw_only=True)\nclass _PuyaOptionsWithCompilationSet(PuyaOptions):\n compilation_set: dict[str, Path]\n\n\ndef main(*, options_json: str, awst_json: str, source_annotations_json: str | None) -> None:\n with log.logging_context() as log_ctx, log_exceptions():\n json_converter = cattrs.preconf.json.make_converter()\n sources_by_path = {}\n if source_annotations_json:\n sources_by_path = json_converter.loads(\n source_annotations_json, dict[Path, list[str] | None]\n )\n log_ctx.sources_by_path = sources_by_path\n awst = serialize.awst_from_json(awst_json)\n options = json_converter.loads(options_json, _PuyaOptionsWithCompilationSet)\n compilation_set = dict[ContractReference | LogicSigReference, Path]()\n awst_lookup = {n.id: n for n in awst}\n for target_id, path in options.compilation_set.items():\n match awst_lookup.get(target_id):\n case awst_nodes.Contract(id=contract_id):\n compilation_set[contract_id] = path\n case awst_nodes.LogicSignature(id=lsig_id):\n compilation_set[lsig_id] = path\n case None:\n logger.error(f\"compilation target {target_id!r} not found in AWST\")\n case other:\n logger.error(f\"unexpected compilation target type: {type(other).__name__}\")\n awst_to_teal(log_ctx, options, compilation_set, sources_by_path, awst)\n # note: needs to be outside the with block\n log_ctx.exit_if_errors()\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/main.py","language":"Python","license":"NOASSERTION","size":1947} {"code":"","repo_name":"algorandfoundation\/puya","path":"src\/puya\/mir\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"import contextlib\nfrom collections.abc import Iterator\n\nimport attrs\n\nfrom puya.errors import InternalError\n\n\n@attrs.define\nclass AlignedWriter:\n _headers: list[str] = attrs.field(factory=list)\n _lines: list[list[str] | str] = attrs.field(factory=list)\n _current_line: list[str] = attrs.field(factory=list)\n _ignore_current_line: bool = False\n _padding: dict[int, int] = attrs.field(factory=dict)\n _indent: str = \"\"\n omit_empty_columns: bool = True\n\n @property\n def ignore_current_line(self) -> bool:\n return self._ignore_current_line\n\n @property\n def current_indent(self) -> str:\n return self._indent\n\n @contextlib.contextmanager\n def indent(self) -> Iterator[None]:\n indent_width = 4\n original_indent = self._indent\n self._indent += \" \" * indent_width\n try:\n yield\n finally:\n self._indent = original_indent\n\n def add_header(self, header: str, padding: int = 1) -> None:\n self._padding[len(self._headers)] = padding\n self._headers.append(header)\n\n def append(self, part: str) -> None:\n self._current_line.append(part)\n\n def new_line(self) -> None:\n parts = self._current_line\n if not self._ignore_current_line:\n if parts and self._indent:\n parts[0] = f\"{self._indent}{parts[0]}\"\n self._lines.append(parts)\n self._ignore_current_line = False\n self._current_line = []\n\n def append_line(self, line: str) -> None:\n if self._current_line or self._ignore_current_line:\n raise InternalError(\n \"Cannot append a new line while a current line is in progress, missing new_line()?\"\n )\n self._lines.append(line)\n\n def ignore_line(self) -> None:\n self._ignore_current_line = True\n\n def _join_columns(self, line: list[str], widths: dict[int, int]) -> str:\n return \"\".join(\n part.ljust(widths.get(column, 0))\n for column, part in enumerate(line)\n if widths.get(column, 0) or not self.omit_empty_columns\n ).rstrip()\n\n def write(self) -> list[str]:\n widths = dict[int, int]()\n all_lines = self._lines.copy()\n for parts in all_lines:\n if isinstance(parts, list):\n for column, part in enumerate(parts):\n widths[column] = max(widths.get(column, 0), len(part))\n\n for column, width in widths.items():\n if width == 0 and self.omit_empty_columns:\n continue\n if column < len(self._headers):\n width = max(width, len(self._headers[column]))\n widths[column] = width + self._padding.get(column, 1)\n\n if self._headers:\n all_lines.insert(0, self._headers)\n\n return [\n line if isinstance(line, str) else self._join_columns(line, widths)\n for line in all_lines\n ]\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/mir\/aligned_writer.py","language":"Python","license":"NOASSERTION","size":2943} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport attrs\n\nfrom puya import log\nfrom puya.errors import CodeError, InternalError\nfrom puya.ir import models as ir\nfrom puya.ir.types_ import AVMBytesEncoding\nfrom puya.ir.visitor import IRVisitor\nfrom puya.mir import models\nfrom puya.mir.context import ProgramMIRContext\nfrom puya.utils import biguint_bytes_eval\n\nlogger = log.get_logger(__name__)\n\n\n@attrs.define\nclass MemoryIRBuilder(IRVisitor[None]):\n context: ProgramMIRContext = attrs.field(on_setattr=attrs.setters.frozen)\n current_subroutine: ir.Subroutine\n is_main: bool\n current_ops: list[models.Op] = attrs.field(factory=list)\n terminator: models.ControlOp | None = None\n active_op: ir.Op | ir.ControlOp | None = None\n\n def _add_op(self, op: models.Op) -> None:\n self.current_ops.append(op)\n\n def _terminate(self, op: models.ControlOp) -> None:\n assert self.terminator is None\n self.terminator = op\n\n def _get_block_name(self, block: ir.BasicBlock) -> str:\n if block is self.current_subroutine.entry:\n return self.context.subroutine_names[self.current_subroutine]\n assert block in self.current_subroutine.body\n comment = (block.comment or \"block\").replace(\" \", \"_\")\n subroutine_name = self.context.subroutine_names[self.current_subroutine]\n return f\"{subroutine_name}_{comment}@{block.id}\"\n\n def visit_assignment(self, ass: ir.Assignment) -> None:\n ass.source.accept(self)\n # right most target is top of stack\n for target in reversed(ass.targets):\n try:\n param_idx = self.current_subroutine.parameters.index(target)\n except ValueError:\n self._add_op(\n models.AbstractStore(\n local_id=target.local_id,\n source_location=ass.source_location,\n atype=target.atype,\n )\n )\n else:\n index = param_idx - len(self.current_subroutine.parameters)\n self._add_op(\n models.StoreParam(\n local_id=target.local_id,\n index=index,\n source_location=ass.source_location,\n atype=target.atype,\n )\n )\n\n def visit_register(self, reg: ir.Register) -> None:\n produces = (reg.local_id,)\n if isinstance(self.active_op, ir.Assignment):\n if reg is self.active_op.source:\n (target,) = self.active_op.targets\n produces = (target.local_id,)\n elif (\n isinstance(self.active_op.source, ir.ValueTuple)\n and reg in self.active_op.source.values\n ):\n index = self.active_op.source.values.index(reg)\n target = self.active_op.targets[index]\n produces = (target.local_id,)\n try:\n param_idx = self.current_subroutine.parameters.index(reg)\n except ValueError:\n self._add_op(\n models.AbstractLoad(\n local_id=reg.local_id,\n produces=produces,\n source_location=(self.active_op or reg).source_location,\n atype=reg.atype,\n )\n )\n else:\n index = param_idx - len(self.current_subroutine.parameters)\n if produces[0] == reg.local_id:\n produces = (f\"{produces[0]} (copy)\",)\n self._add_op(\n models.LoadParam(\n local_id=reg.local_id,\n produces=produces,\n index=index,\n source_location=(self.active_op or reg).source_location,\n atype=reg.atype,\n )\n )\n\n def visit_undefined(self, val: ir.Undefined) -> None:\n self._add_op(\n models.Undefined(\n atype=val.atype,\n source_location=val.source_location,\n )\n )\n\n def visit_template_var(self, deploy_var: ir.TemplateVar) -> None:\n self._add_op(\n models.TemplateVar(\n name=deploy_var.name,\n atype=deploy_var.atype,\n source_location=deploy_var.source_location,\n )\n )\n\n def visit_uint64_constant(self, const: ir.UInt64Constant) -> None:\n self._add_op(\n models.Int(\n const.value if not const.teal_alias else const.teal_alias,\n source_location=const.source_location,\n )\n )\n\n def visit_biguint_constant(self, const: ir.BigUIntConstant) -> None:\n big_uint_bytes = biguint_bytes_eval(const.value)\n self._add_op(\n models.Byte(\n big_uint_bytes,\n source_location=const.source_location,\n encoding=AVMBytesEncoding.base16,\n )\n )\n\n def visit_bytes_constant(self, const: ir.BytesConstant) -> None:\n self._add_op(\n models.Byte(\n const.value, encoding=const.encoding, source_location=const.source_location\n )\n )\n\n def visit_address_constant(self, const: ir.AddressConstant) -> None:\n self._add_op(\n models.Address(\n const.value,\n source_location=const.source_location,\n )\n )\n\n def visit_method_constant(self, const: ir.MethodConstant) -> None:\n self._add_op(\n models.Method(\n const.value,\n source_location=const.source_location,\n )\n )\n\n def visit_intrinsic_op(self, intrinsic: ir.Intrinsic) -> None:\n discard_results = intrinsic is self.active_op\n\n if intrinsic.op.code.startswith(\"box_\"):\n try:\n box_key = intrinsic.args[0]\n except ValueError:\n raise InternalError(\"box key arg not found\", intrinsic.source_location) from None\n if isinstance(box_key, ir.BytesConstant) and not box_key.value:\n raise CodeError(\"AVM does not support empty box keys\", intrinsic.source_location)\n\n for arg in intrinsic.args:\n arg.accept(self)\n produces = len(intrinsic.op_signature.returns)\n self._add_op(\n models.IntrinsicOp(\n op_code=intrinsic.op.code,\n immediates=intrinsic.immediates,\n source_location=intrinsic.source_location,\n consumes=len(intrinsic.op_signature.args),\n produces=_produces_from_op(intrinsic.op.code, produces, self.active_op),\n error_message=intrinsic.error_message,\n )\n )\n if discard_results and produces:\n self._add_op(models.Pop(produces))\n\n def visit_invoke_subroutine(self, callsub: ir.InvokeSubroutine) -> None:\n discard_results = callsub is self.active_op\n target = callsub.target\n\n callsub_op = models.CallSub(\n target=self.context.subroutine_names[target],\n parameters=len(target.parameters),\n returns=len(target.returns),\n produces=_produces_from_op(\n self.context.subroutine_names[target], len(target.returns), self.active_op\n ),\n source_location=callsub.source_location,\n )\n\n # prepare args\n for arg in callsub.args:\n arg.accept(self)\n\n # call sub\n self._add_op(callsub_op)\n\n if discard_results and target.returns:\n num_returns = len(target.returns)\n self._add_op(models.Pop(num_returns))\n\n def visit_conditional_branch(self, branch: ir.ConditionalBranch) -> None:\n branch.condition.accept(self)\n self._terminate(\n models.ConditionalBranch(\n nonzero_target=self._get_block_name(branch.non_zero),\n zero_target=self._get_block_name(branch.zero),\n source_location=branch.source_location,\n )\n )\n\n def visit_goto(self, goto: ir.Goto) -> None:\n self._terminate(\n models.Goto(\n target=self._get_block_name(goto.target),\n source_location=goto.source_location,\n )\n )\n\n def visit_goto_nth(self, goto_nth: ir.GotoNth) -> None:\n block_labels = [self._get_block_name(block) for block in goto_nth.blocks]\n goto_nth.value.accept(self)\n self._terminate(\n models.Switch(\n switch_targets=block_labels,\n default_target=self._get_block_name(goto_nth.default),\n source_location=goto_nth.source_location,\n )\n )\n\n def visit_switch(self, switch: ir.Switch) -> None:\n blocks = list[str]()\n for case, block in switch.cases.items():\n case.accept(self)\n block_name = self._get_block_name(block)\n blocks.append(block_name)\n switch.value.accept(self)\n self._terminate(\n models.Match(\n match_targets=blocks,\n default_target=self._get_block_name(switch.default),\n source_location=switch.source_location,\n )\n )\n\n def visit_subroutine_return(self, retsub: ir.SubroutineReturn) -> None:\n for r in retsub.result:\n r.accept(self)\n if self.is_main:\n assert len(retsub.result) == 1\n self._terminate(models.ProgramExit(source_location=retsub.source_location))\n else:\n self._terminate(\n models.RetSub(returns=len(retsub.result), source_location=retsub.source_location)\n )\n\n def visit_program_exit(self, exit_: ir.ProgramExit) -> None:\n exit_.result.accept(self)\n self._terminate(models.ProgramExit(source_location=exit_.source_location))\n\n def visit_fail(self, fail: ir.Fail) -> None:\n self._terminate(\n models.Err(error_message=fail.error_message, source_location=fail.source_location)\n )\n\n def lower_block_to_mir(self, block: ir.BasicBlock) -> models.MemoryBasicBlock:\n self.current_ops = list[models.Op]()\n self.terminator = None\n for op in block.all_ops:\n assert not isinstance(op, ir.Phi)\n self.active_op = op\n op.accept(self)\n\n assert self.terminator is not None\n block_name = self._get_block_name(block)\n predecessors = [self._get_block_name(b) for b in block.predecessors]\n assert block.id is not None\n return models.MemoryBasicBlock(\n id=block.id,\n block_name=block_name,\n mem_ops=self.current_ops,\n terminator=self.terminator,\n predecessors=predecessors,\n source_location=block.source_location,\n )\n\n def visit_compiled_contract_reference(self, const: ir.CompiledContractReference) -> None:\n _unexpected_node(const)\n\n def visit_compiled_logicsig_reference(self, const: ir.CompiledLogicSigReference) -> None:\n _unexpected_node(const)\n\n def visit_value_tuple(self, tup: ir.ValueTuple) -> None:\n _unexpected_node(tup)\n\n def visit_itxn_constant(self, const: ir.ITxnConstant) -> None:\n _unexpected_node(const)\n\n def visit_inner_transaction_field(self, field: ir.InnerTransactionField) -> None:\n _unexpected_node(field)\n\n def visit_phi(self, phi: ir.Phi) -> None:\n _unexpected_node(phi)\n\n def visit_phi_argument(self, arg: ir.PhiArgument) -> None:\n _unexpected_node(arg)\n\n\ndef _unexpected_node(node: ir.IRVisitable) -> typing.Never:\n raise InternalError(\n f\"Encountered node of type {type(node).__name__!r} during codegen\"\n f\" - should have been eliminated in prior stages\",\n node.source_location,\n )\n\n\ndef _produces_from_op(\n prefix: str, size: int, maybe_assignment: ir.IRVisitable | None\n) -> Sequence[str]:\n produces = models.produces_from_desc(prefix, size)\n if isinstance(maybe_assignment, ir.Assignment):\n produces = [r.local_id for r in maybe_assignment.targets]\n return produces\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/mir\/builder.py","language":"Python","license":"NOASSERTION","size":12186} {"code":"from collections.abc import Mapping\n\nimport attrs\n\nfrom puya.context import ArtifactCompileContext\nfrom puya.ir import models as ir\nfrom puya.mir import models\nfrom puya.mir.vla import VariableLifetimeAnalysis\nfrom puya.utils import attrs_extend\n\n\n@attrs.define(kw_only=True)\nclass ProgramMIRContext(ArtifactCompileContext):\n program: ir.Program\n subroutine_names: Mapping[ir.Subroutine, str] = attrs.field(init=False)\n\n @subroutine_names.default\n def _get_short_subroutine_names(self) -> dict[ir.Subroutine, str]:\n \"\"\"Return a mapping of unique TEAL names for all subroutines in program, while attempting\n to use the shortest name possible\"\"\"\n names = {\"main\": self.program.main}\n for subroutine in self.program.subroutines:\n if subroutine.short_name and subroutine.short_name not in names:\n name = subroutine.short_name\n else:\n assert subroutine.id not in names\n name = subroutine.id\n names[name] = subroutine\n\n return {v: k for k, v in names.items()}\n\n def for_subroutine(self, subroutine: models.MemorySubroutine) -> \"SubroutineCodeGenContext\":\n return attrs_extend(SubroutineCodeGenContext, self, subroutine=subroutine)\n\n\n@attrs.define(frozen=False)\nclass SubroutineCodeGenContext(ProgramMIRContext):\n subroutine: models.MemorySubroutine\n _vla: VariableLifetimeAnalysis | None = None\n\n @property\n def vla(self) -> VariableLifetimeAnalysis:\n if self._vla is None:\n self._vla = VariableLifetimeAnalysis.analyze(self.subroutine)\n return self._vla\n\n def invalidate_vla(self) -> None:\n self._vla = None\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/mir\/context.py","language":"Python","license":"NOASSERTION","size":1685} {"code":"from puya.context import ArtifactCompileContext\nfrom puya.ir import models as ir\nfrom puya.mir import models\nfrom puya.mir.builder import MemoryIRBuilder\nfrom puya.mir.context import ProgramMIRContext\nfrom puya.mir.stack_allocation import global_stack_allocation\nfrom puya.utils import attrs_extend\n\n\ndef program_ir_to_mir(context: ArtifactCompileContext, program_ir: ir.Program) -> models.Program:\n ctx = attrs_extend(ProgramMIRContext, context, program=program_ir)\n\n result = models.Program(\n kind=program_ir.kind,\n main=_lower_subroutine_to_mir(ctx, program_ir.main, is_main=True),\n subroutines=[\n _lower_subroutine_to_mir(ctx, ir_sub, is_main=False)\n for ir_sub in program_ir.subroutines\n ],\n avm_version=program_ir.avm_version,\n )\n global_stack_allocation(ctx, result)\n return result\n\n\ndef _lower_subroutine_to_mir(\n context: ProgramMIRContext, subroutine: ir.Subroutine, *, is_main: bool\n) -> models.MemorySubroutine:\n builder = MemoryIRBuilder(context=context, current_subroutine=subroutine, is_main=is_main)\n body = [builder.lower_block_to_mir(block) for block in subroutine.body]\n signature = models.Signature(\n name=subroutine.id,\n parameters=[\n models.Parameter(name=p.name, local_id=p.local_id, atype=p.atype)\n for p in subroutine.parameters\n ],\n returns=[r.avm_type for r in subroutine.returns],\n )\n return models.MemorySubroutine(\n id=context.subroutine_names[subroutine],\n signature=signature,\n is_main=is_main,\n body=body,\n source_location=subroutine.source_location,\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/mir\/main.py","language":"Python","license":"NOASSERTION","size":1665} {"code":"from __future__ import annotations\n\nimport abc\nimport typing\nimport typing as t\nfrom functools import cached_property\n\nimport attrs\n\nfrom puya.avm import AVMType\nfrom puya.errors import InternalError\nfrom puya.ir.utils import format_bytes, format_error_comment\nfrom puya.program_refs import ProgramKind\n\nif t.TYPE_CHECKING:\n from collections.abc import Iterator, Mapping, Sequence\n\n from puya.ir.types_ import AVMBytesEncoding\n from puya.mir.visitor import MIRVisitor\n from puya.parse import SourceLocation\n\n_T = t.TypeVar(\"_T\")\n\n\n@attrs.frozen(kw_only=True, eq=False, str=False)\nclass BaseOp(abc.ABC):\n error_message: str | None = None\n source_location: SourceLocation | None = None\n consumes: int\n \"\"\"How many values are removed from the top of l-stack\n Does not take into account any manipulations lower in the stack e.g. from Load*Stack\"\"\"\n produces: Sequence[str]\n \"\"\"The local ids that are appended to the l-stack\n Does not take into account any manipulations lower in the stack e.g. from Store*Stack\"\"\"\n\n @abc.abstractmethod\n def accept(self, visitor: MIRVisitor[_T]) -> _T: ...\n\n\ndef _is_single_item(_: object, __: object, value: Sequence[str]) -> None:\n assert len(value) == 1, \"expected single item\"\n\n\n@attrs.frozen(eq=False)\nclass Op(BaseOp, abc.ABC):\n @abc.abstractmethod\n def __str__(self) -> str: ...\n\n\n@attrs.frozen(eq=False)\nclass Int(Op):\n value: int | str\n consumes: int = attrs.field(default=0, init=False)\n produces: Sequence[str] = attrs.field(validator=_is_single_item)\n\n @produces.default\n def _produces(self) -> Sequence[str]:\n return (str(self.value),)\n\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_int(self)\n\n def __str__(self) -> str:\n return f\"int {self.value}\"\n\n\n@attrs.frozen(eq=False)\nclass Byte(Op):\n value: bytes\n encoding: AVMBytesEncoding\n consumes: int = attrs.field(default=0, init=False)\n produces: Sequence[str] = attrs.field(validator=_is_single_item)\n\n @produces.default\n def _produces(self) -> Sequence[str]:\n return (format_bytes(self.value, self.encoding),)\n\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_byte(self)\n\n def __str__(self) -> str:\n return f\"byte {format_bytes(self.value, self.encoding)}\"\n\n\n@attrs.frozen(eq=False)\nclass Undefined(Op):\n atype: typing.Literal[AVMType.bytes, AVMType.uint64]\n consumes: int = attrs.field(default=0, init=False)\n produces: Sequence[str] = attrs.field(validator=_is_single_item)\n\n @produces.default\n def _produces(self) -> Sequence[str]:\n return (\"undefined\",)\n\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_undefined(self)\n\n def __str__(self) -> str:\n return \"undefined\"\n\n\n@attrs.frozen(eq=False)\nclass TemplateVar(Op):\n name: str\n atype: AVMType\n op_code: typing.Literal[\"int\", \"byte\"] = attrs.field(init=False)\n consumes: int = attrs.field(default=0, init=False)\n produces: Sequence[str] = attrs.field(validator=_is_single_item)\n\n @produces.default\n def _produces(self) -> Sequence[str]:\n return (self.name,)\n\n @op_code.default\n def _default_opcode(self) -> typing.Literal[\"int\", \"byte\"]:\n match self.atype:\n case AVMType.bytes:\n return \"byte\"\n case AVMType.uint64:\n return \"int\"\n case _:\n raise InternalError(\n f\"Unsupported atype for TemplateVar: {self.atype}\", self.source_location\n )\n\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_template_var(self)\n\n def __str__(self) -> str:\n return f\"{self.op_code} {self.name}\"\n\n\n@attrs.frozen(eq=False)\nclass Address(Op):\n value: str\n consumes: int = attrs.field(default=0, init=False)\n produces: Sequence[str] = attrs.field(validator=_is_single_item)\n\n @produces.default\n def _produces(self) -> Sequence[str]:\n return (f\"Address({self.value})\",)\n\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_address(self)\n\n def __str__(self) -> str:\n return f'addr \"{self.value}\"'\n\n\n@attrs.frozen(eq=False)\nclass Method(Op):\n value: str\n consumes: int = attrs.field(default=0, init=False)\n produces: Sequence[str] = attrs.field(validator=_is_single_item)\n\n @produces.default\n def _produces(self) -> Sequence[str]:\n return (f\"Method({self.value})\",)\n\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_method(self)\n\n def __str__(self) -> str:\n return f\"method {self.value}\"\n\n\n@attrs.frozen(eq=False)\nclass Comment(Op):\n comment: str\n consumes: int = attrs.field(default=0, init=False)\n produces: Sequence[str] = attrs.field(default=(), init=False)\n\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_comment(self)\n\n def __str__(self) -> str:\n return f\"\/\/ {self.comment}\"\n\n\n@attrs.frozen(kw_only=True, eq=False)\nclass StoreOp(Op, abc.ABC):\n \"\"\"An op for storing values\"\"\"\n\n local_id: str\n atype: AVMType = attrs.field()\n\n @atype.validator\n def _validate_not_any(self, _attribute: object, atype: AVMType) -> None:\n if atype is AVMType.any:\n raise InternalError(f\"Register has type any: {self}\", self.source_location)\n\n\n@attrs.frozen(kw_only=True, eq=False)\nclass LoadOp(Op, abc.ABC):\n \"\"\"An op for loading values\"\"\"\n\n local_id: str\n atype: AVMType = attrs.field()\n\n @atype.validator\n def _validate_not_any(self, _attribute: object, atype: AVMType) -> None:\n if atype is AVMType.any:\n raise InternalError(f\"Register has type any: {self}\", self.source_location)\n\n\n@attrs.frozen(eq=False)\nclass AbstractStore(StoreOp):\n consumes: int = attrs.field(default=1, init=False)\n produces: Sequence[str] = attrs.field(default=(), init=False)\n\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_abstract_store(self)\n\n def __str__(self) -> str:\n return f\"v-store {self.local_id}\"\n\n\n@attrs.frozen(eq=False)\nclass AbstractLoad(LoadOp):\n consumes: int = attrs.field(default=0, init=False)\n produces: Sequence[str] = attrs.field(validator=_is_single_item)\n\n @produces.default\n def _produces(self) -> Sequence[str]:\n return (self.local_id,)\n\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_abstract_load(self)\n\n def __str__(self) -> str:\n return f\"v-load {self.local_id}\"\n\n\n@attrs.frozen(eq=False, kw_only=True)\nclass StoreLStack(StoreOp):\n depth: int = attrs.field(validator=attrs.validators.ge(0))\n copy: bool\n consumes: int = attrs.field(default=0, init=False)\n produces: Sequence[str] = attrs.field()\n\n @produces.default\n def _produces(self) -> Sequence[str]:\n return (f\"{self.local_id} (copy)\",) if self.copy else ()\n\n @produces.validator\n def _validate_produces(self, _: object, value: Sequence[str]) -> None:\n assert len(value) == (1 if self.copy else 0), \"invalid produces size\"\n\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_store_l_stack(self)\n\n def __str__(self) -> str:\n op = \"l-store-copy\" if self.copy else \"l-store\"\n return f\"{op} {self.local_id} {self.depth}\"\n\n\n@attrs.frozen(eq=False)\nclass LoadLStack(LoadOp):\n copy: bool\n consumes: int = attrs.field(init=False, default=0)\n produces: Sequence[str] = attrs.field(validator=_is_single_item)\n # depth can only be defined after koopmans pass and dead store removal\n depth: int | None = None\n\n @produces.default\n def _produces(self) -> Sequence[str]:\n produces = self.local_id\n if self.copy:\n produces += \" (copy)\"\n return (produces,)\n\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_load_l_stack(self)\n\n def __str__(self) -> str:\n depth = \"\" if self.depth is None else f\" {self.depth}\"\n op = \"l-load-copy\" if self.copy else \"l-load\"\n return f\"{op} {self.local_id}{depth}\"\n\n\n@attrs.frozen(eq=False)\nclass StoreXStack(StoreOp):\n depth: int = attrs.field(validator=attrs.validators.ge(0))\n consumes: int = attrs.field(default=1, init=False)\n produces: Sequence[str] = attrs.field(default=(), init=False)\n\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_store_x_stack(self)\n\n def __str__(self) -> str:\n return f\"x-store {self.local_id}\"\n\n\n@attrs.frozen(eq=False)\nclass LoadXStack(LoadOp):\n depth: int = attrs.field(validator=attrs.validators.ge(0))\n consumes: int = attrs.field(default=0, init=False)\n produces: Sequence[str] = attrs.field(validator=_is_single_item)\n\n @produces.default\n def _produces(self) -> Sequence[str]:\n return (self.local_id,)\n\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_load_x_stack(self)\n\n def __str__(self) -> str:\n return f\"x-load {self.local_id}\"\n\n\n@attrs.frozen(eq=False)\nclass StoreFStack(StoreOp):\n depth: int = attrs.field(validator=attrs.validators.ge(0))\n frame_index: int = attrs.field(validator=attrs.validators.ge(0))\n insert: bool = False\n consumes: int = attrs.field(default=1, init=False)\n produces: Sequence[str] = attrs.field(default=(), init=False)\n\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_store_f_stack(self)\n\n def __str__(self) -> str:\n return f\"f-store {self.local_id}\"\n\n\n@attrs.frozen(eq=False)\nclass LoadFStack(LoadOp):\n depth: int = attrs.field(validator=attrs.validators.ge(0))\n frame_index: int = attrs.field(validator=attrs.validators.ge(0))\n consumes: int = attrs.field(default=0, init=False)\n produces: Sequence[str] = attrs.field(validator=_is_single_item)\n\n @produces.default\n def _produces(self) -> Sequence[str]:\n return (f\"{self.local_id} (copy)\",)\n\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_load_f_stack(self)\n\n def __str__(self) -> str:\n return f\"f-load {self.local_id}\"\n\n\n@attrs.frozen(eq=False)\nclass LoadParam(LoadOp):\n index: int\n consumes: int = attrs.field(default=0, init=False)\n produces: Sequence[str] = attrs.field(validator=_is_single_item)\n\n @produces.default\n def _produces(self) -> Sequence[str]:\n return (f\"{self.local_id} (copy)\",)\n\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_load_param(self)\n\n def __str__(self) -> str:\n return f\"p-load {self.local_id}\"\n\n\n@attrs.frozen(eq=False)\nclass StoreParam(StoreOp):\n index: int\n consumes: int = attrs.field(default=1, init=False)\n produces: Sequence[str] = attrs.field(default=(), init=False)\n\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_store_param(self)\n\n def __str__(self) -> str:\n return f\"p-store {self.local_id}\"\n\n\n@attrs.frozen(eq=False)\nclass Pop(Op):\n n: int\n consumes: int = attrs.field(init=False)\n produces: Sequence[str] = attrs.field(default=(), init=False)\n\n @consumes.default\n def _consumes(self) -> int:\n return self.n\n\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_pop(self)\n\n def __str__(self) -> str:\n return f\"pop {self.n}\"\n\n\n@attrs.frozen(eq=False)\nclass Allocate(Op):\n bytes_vars: Sequence[str]\n uint64_vars: Sequence[str]\n consumes: int = attrs.field(default=0, init=False)\n produces: Sequence[str] = attrs.field(default=(), init=False)\n\n @property\n def allocate_on_entry(self) -> Sequence[str]:\n return [*self.bytes_vars, *self.uint64_vars]\n\n @property\n def num_bytes(self) -> int:\n return len(self.bytes_vars)\n\n @property\n def num_uints(self) -> int:\n return len(self.uint64_vars)\n\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_allocate(self)\n\n def __str__(self) -> str:\n return f\"allocate {len(self.allocate_on_entry)} to stack\"\n\n\n@attrs.frozen(eq=False)\nclass CallSub(Op):\n target: str\n parameters: int\n returns: int\n consumes: int = attrs.field(init=False)\n produces: Sequence[str] = attrs.field()\n\n @consumes.default\n def _consumes(self) -> int:\n return self.parameters\n\n @produces.validator\n def _validate_produces(self, _: object, value: Sequence[str]) -> None:\n assert len(value) == self.returns, \"invalid produces size\"\n\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_callsub(self)\n\n def __str__(self) -> str:\n return f\"callsub {self.target}\"\n\n\n@attrs.frozen(eq=False)\nclass IntrinsicOp(Op):\n \"\"\"An Op that does something other than just manipulating memory\"\"\"\n\n # TODO: use enum values for these ops\n op_code: str\n immediates: Sequence[str | int] = attrs.field(default=(), converter=tuple[str | int, ...])\n\n def __attrs_post_init__(self) -> None:\n if self.op_code in (\"b\", \"bz\", \"bnz\", \"switch\", \"match\", \"retsub\", \"err\", \"return\"):\n raise InternalError(\n f\"Branching op {self.op_code} should map to explicit MIR ControlOp\",\n self.source_location,\n )\n\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_intrinsic(self)\n\n def __str__(self) -> str:\n result = [self.op_code, *map(str, self.immediates)]\n if self.error_message:\n result.append(\"\/\/\")\n result.append(format_error_comment(self.op_code, self.error_message))\n return \" \".join(result)\n\n\n@attrs.frozen(eq=False)\nclass ControlOp(BaseOp, abc.ABC):\n @abc.abstractmethod\n def targets(self) -> Sequence[str]: ...\n\n @abc.abstractmethod\n def _str_components(self) -> tuple[str, ...]: ...\n\n @typing.final\n def __str__(self) -> str:\n result = tuple(self._str_components())\n if self.error_message:\n result += (\"\/\/\", self.error_message)\n return \" \".join(result)\n\n\n@attrs.frozen(eq=False)\nclass RetSub(ControlOp):\n returns: int\n fx_height: int = 0\n # l-stack is discarded after this op\n consumes: int = attrs.field(default=0, init=False)\n produces: Sequence[str] = attrs.field(default=(), init=False)\n\n @typing.override\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_retsub(self)\n\n @typing.override\n def targets(self) -> Sequence[str]:\n return ()\n\n @typing.override\n def _str_components(self) -> tuple[str, ...]:\n return (\"retsub\",)\n\n\n@attrs.frozen(eq=False)\nclass ProgramExit(ControlOp):\n consumes: int = attrs.field(default=1, init=False)\n produces: Sequence[str] = attrs.field(default=(), init=False)\n\n @typing.override\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_program_exit(self)\n\n @typing.override\n def targets(self) -> Sequence[str]:\n return ()\n\n @typing.override\n def _str_components(self) -> tuple[str, ...]:\n return (\"return\",)\n\n\n@attrs.frozen(eq=False)\nclass Err(ControlOp):\n consumes: int = attrs.field(default=0, init=False)\n produces: Sequence[str] = attrs.field(default=(), init=False)\n\n @typing.override\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_err(self)\n\n @typing.override\n def targets(self) -> Sequence[str]:\n return ()\n\n @typing.override\n def _str_components(self) -> tuple[str, ...]:\n return (\"err\",)\n\n\n@attrs.frozen(eq=False)\nclass Goto(ControlOp):\n consumes: int = attrs.field(default=0, init=False)\n produces: Sequence[str] = attrs.field(default=(), init=False)\n target: str\n\n @typing.override\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_goto(self)\n\n @typing.override\n def targets(self) -> Sequence[str]:\n return (self.target,)\n\n @typing.override\n def _str_components(self) -> tuple[str, ...]:\n return \"b\", self.target\n\n\n@attrs.frozen(eq=False)\nclass ConditionalBranch(ControlOp):\n consumes: int = attrs.field(default=1, init=False)\n produces: Sequence[str] = attrs.field(default=(), init=False)\n zero_target: str\n nonzero_target: str\n\n @typing.override\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_conditional_branch(self)\n\n @typing.override\n def targets(self) -> Sequence[str]:\n return self.zero_target, self.nonzero_target\n\n @typing.override\n def _str_components(self) -> tuple[str, ...]:\n return \"bz\", self.zero_target, \";\", \"b\", self.nonzero_target\n\n\n@attrs.frozen(eq=False)\nclass Switch(ControlOp):\n consumes: int = attrs.field(default=1, init=False)\n produces: Sequence[str] = attrs.field(default=(), init=False)\n switch_targets: Sequence[str] = attrs.field(converter=tuple[str, ...])\n default_target: str\n\n @typing.override\n def targets(self) -> Sequence[str]:\n return *self.switch_targets, self.default_target\n\n @typing.override\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_switch(self)\n\n @typing.override\n def _str_components(self) -> tuple[str, ...]:\n return \"switch\", *self.switch_targets, \";\", \"b\", self.default_target\n\n\n@attrs.frozen(eq=False)\nclass Match(ControlOp):\n produces: Sequence[str] = attrs.field(default=(), init=False)\n match_targets: Sequence[str] = attrs.field(converter=tuple[str, ...])\n consumes: int = attrs.field(init=False)\n default_target: str\n\n @consumes.default\n def _consumes(self) -> int:\n return len(self.match_targets) + 1\n\n @typing.override\n def targets(self) -> Sequence[str]:\n return *self.match_targets, self.default_target\n\n @typing.override\n def accept(self, visitor: MIRVisitor[_T]) -> _T:\n return visitor.visit_match(self)\n\n @typing.override\n def _str_components(self) -> tuple[str, ...]:\n return \"match\", *self.match_targets, \";\", \"b\", self.default_target\n\n\n@attrs.define(eq=False, repr=False, kw_only=True)\nclass MemoryBasicBlock:\n id: int\n block_name: str\n mem_ops: list[Op]\n terminator: ControlOp\n predecessors: list[str]\n source_location: SourceLocation\n # the ordering of values on the stack is used by debug maps\n # the assumption is lower levels won't change the order of variables in the stack\n # however they can introduce changes that do that ordering more efficiently\n x_stack_in: Sequence[str] | None = None\n \"\"\"local_ids on x-stack on entry to a block\"\"\"\n x_stack_out: Sequence[str] | None = None\n \"\"\"local_ids on x-stack on exit from a block\"\"\"\n f_stack_in: Sequence[str] = attrs.field(factory=list)\n \"\"\"local_ids on f-stack on entry to a block\"\"\"\n f_stack_out: Sequence[str] = attrs.field(factory=list)\n \"\"\"local_ids on f-stack on exit from a block\"\"\"\n\n @property\n def ops(self) -> Sequence[BaseOp]:\n return *self.mem_ops, self.terminator\n\n def __repr__(self) -> str:\n return self.block_name\n\n @property\n def entry_stack_height(self) -> int:\n return len(self.f_stack_in) + len(self.x_stack_in or ())\n\n @property\n def exit_stack_height(self) -> int:\n return len(self.f_stack_out) + len(self.x_stack_out or ())\n\n @property\n def successors(self) -> Sequence[str]:\n return self.terminator.targets()\n\n\n@attrs.frozen(kw_only=True)\nclass Parameter:\n name: str\n local_id: str\n atype: AVMType\n\n\n@attrs.frozen(str=False)\nclass Signature:\n name: str\n parameters: Sequence[Parameter]\n returns: Sequence[AVMType]\n\n def __str__(self) -> str:\n params = \", \".join(f\"{p.name}: {p.atype.name}\" for p in self.parameters)\n returns = \", \".join(str(r.name) for r in self.returns)\n return f\"{self.name}({params}) -> {returns or 'void'}:\"\n\n\n@attrs.define\nclass MemorySubroutine:\n \"\"\"A lower form of IR that is concerned with memory assignment (both stack and scratch)\"\"\"\n\n id: str\n is_main: bool\n signature: Signature\n body: Sequence[MemoryBasicBlock]\n source_location: SourceLocation | None\n\n @cached_property\n def block_map(self) -> Mapping[str, MemoryBasicBlock]:\n return {b.block_name: b for b in self.body}\n\n def get_block(self, block_name: str) -> MemoryBasicBlock:\n return self.block_map[block_name]\n\n\n@attrs.define\nclass Program:\n kind: ProgramKind\n main: MemorySubroutine\n subroutines: list[MemorySubroutine]\n avm_version: int\n\n @property\n def all_subroutines(self) -> Iterator[MemorySubroutine]:\n yield self.main\n yield from self.subroutines\n\n\ndef produces_from_desc(desc: str, size: int) -> Sequence[str]:\n desc = f\"{{{desc}}}\"\n if size > 1:\n produces = [f\"{desc}.{n}\" for n in range(size)]\n elif size == 1:\n produces = [desc]\n else:\n produces = []\n return produces\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/mir\/models.py","language":"Python","license":"NOASSERTION","size":20948} {"code":"import textwrap\n\nimport attrs\n\nfrom puya import log\nfrom puya.context import ArtifactCompileContext, CompileContext\nfrom puya.mir import models\nfrom puya.mir.aligned_writer import AlignedWriter\nfrom puya.mir.stack import Stack\nfrom puya.parse import SourceLocation\n\nlogger = log.get_logger(__name__)\n\n\ndef output_memory_ir(\n ctx: ArtifactCompileContext, program: models.Program, *, qualifier: str\n) -> None:\n output_path = ctx.build_output_path(program.kind, qualifier, \"mir\")\n if output_path is None:\n return\n writer = AlignedWriter()\n writer.add_header(\"\/\/ Op\")\n writer.add_header(\"Stack (out)\", 4)\n for subroutine in program.all_subroutines:\n writer.append_line(f\"\/\/ {subroutine.signature}\")\n for block in subroutine.body:\n stack = Stack.begin_block(subroutine, block)\n last_location = None\n writer.append(f\"{block.block_name}:\")\n writer.append(stack.full_stack_desc)\n writer.new_line()\n with writer.indent():\n for op in block.ops:\n last_location = _output_src_comment(\n ctx, writer, last_location, op.source_location\n )\n op_str = str(op)\n op.accept(stack)\n # some ops can be very long (generally due to labels)\n # in those (rare?) cases bypass the column alignment\n if len(op_str) > 80:\n writer.append_line(\n writer.current_indent + op_str + \" \" + stack.full_stack_desc\n )\n else:\n writer.append(op_str)\n writer.append(stack.full_stack_desc)\n writer.new_line()\n writer.new_line()\n writer.new_line()\n writer.new_line()\n output_path.write_text(\"\\n\".join(writer.write()), \"utf8\")\n\n\ndef _output_src_comment(\n ctx: CompileContext,\n writer: AlignedWriter,\n last_loc: SourceLocation | None,\n op_loc: SourceLocation | None,\n) -> SourceLocation | None:\n if op_loc:\n whole_lines_location = attrs.evolve(op_loc, column=None, end_column=None)\n if whole_lines_location != last_loc:\n last_loc = whole_lines_location\n src = ctx.try_get_source(whole_lines_location)\n if src is not None:\n writer.append(f\"\/\/ {whole_lines_location}\")\n writer.new_line()\n lines = textwrap.dedent(\"\\n\".join(src)).splitlines()\n for line in lines:\n writer.append(f\"\/\/ {line.rstrip()}\")\n writer.new_line()\n return last_loc\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/mir\/output.py","language":"Python","license":"NOASSERTION","size":2717} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport attrs\n\nfrom puya.mir import models\nfrom puya.mir.visitor import MIRVisitor\n\n\n@attrs.define\nclass Stack(MIRVisitor[None]):\n parameters: Sequence[str]\n _f_stack: list[str]\n \"\"\"f-stack holds variables above the current frame\"\"\"\n _x_stack: list[str]\n \"\"\"x-stack holds variable that are carried between blocks\"\"\"\n _l_stack: list[str] = attrs.field(factory=list)\n \"\"\"l-stack holds variables that are used within a block\"\"\"\n\n @classmethod\n def begin_block(\n cls, subroutine: models.MemorySubroutine, block: models.MemoryBasicBlock\n ) -> typing.Self:\n return cls(\n parameters=[p.local_id for p in subroutine.signature.parameters],\n f_stack=list(block.f_stack_in),\n x_stack=list(block.x_stack_in or ()), # x-stack might not be assigned yet\n )\n\n @property\n def f_stack(self) -> Sequence[str]:\n return self._f_stack\n\n @property\n def x_stack(self) -> Sequence[str]:\n return self._x_stack\n\n @property\n def l_stack(self) -> Sequence[str]:\n return self._l_stack\n\n @property\n def xl_height(self) -> int:\n return len(self._l_stack) + len(self._x_stack)\n\n @property\n def fxl_height(self) -> int:\n return len(self._f_stack) + len(self._l_stack) + len(self._x_stack)\n\n @property\n def full_stack_desc(self) -> str:\n stack_descs = []\n if self.parameters:\n stack_descs.append(\"(\ud835\udd61) \" + \",\".join(self.parameters)) # noqa: RUF001\n if self._f_stack:\n stack_descs.append(\"(\ud835\udd57) \" + \",\".join(self._f_stack)) # noqa: RUF001\n if self._x_stack:\n stack_descs.append(\"(\ud835\udd4f) \" + \",\".join(self._x_stack)) # noqa: RUF001\n stack_descs.append(\",\".join(self._l_stack))\n return \" | \".join(stack_descs)\n\n def _get_f_stack_dig_bury(self, value: str) -> int:\n return (\n len(self._f_stack)\n + len(self._x_stack)\n + len(self._l_stack)\n - self._f_stack.index(value)\n - 1\n )\n\n def visit_int(self, const: models.Int) -> None:\n self._apply_lstack_effects(const)\n\n def visit_byte(self, const: models.Byte) -> None:\n self._apply_lstack_effects(const)\n\n def visit_undefined(self, const: models.Undefined) -> None:\n self._apply_lstack_effects(const)\n\n def visit_template_var(self, const: models.TemplateVar) -> None:\n self._apply_lstack_effects(const)\n\n def visit_address(self, const: models.Address) -> None:\n self._apply_lstack_effects(const)\n\n def visit_method(self, const: models.Method) -> None:\n self._apply_lstack_effects(const)\n\n def visit_comment(self, _: models.Comment) -> None:\n pass\n\n def visit_abstract_store(self, store: models.AbstractStore) -> None:\n self._apply_lstack_effects(store)\n\n def visit_abstract_load(self, load: models.AbstractLoad) -> None:\n self._apply_lstack_effects(load)\n\n def _store_f_stack(self, store: models.StoreFStack) -> None:\n local_id = store.local_id\n # must calculate bury offsets BEFORE modifying l-stack\n assert local_id in self._f_stack, f\"{local_id} not in f-stack\"\n bury = self._get_f_stack_dig_bury(local_id)\n assert bury == store.depth, f\"expected {bury=} == {store.depth=}\"\n self._apply_lstack_effects(store)\n\n def _insert_f_stack(self, store: models.StoreFStack) -> None:\n local_id = store.local_id\n assert local_id not in self._f_stack, f\"{local_id} already in f-stack\"\n # inserting something at the top of the f-stack\n # is equivalent to inserting at the bottom of the x-stack\n cover = len(self._x_stack) + len(self._l_stack) - 1\n assert cover == store.depth, f\"expected {cover=} == {store.depth=}\"\n self._f_stack.append(local_id)\n self._apply_lstack_effects(store)\n\n def visit_store_f_stack(self, store: models.StoreFStack) -> None:\n assert self._l_stack, f\"l-stack is empty, can not store {store.local_id} to f-stack\"\n if store.insert:\n self._insert_f_stack(store)\n else:\n self._store_f_stack(store)\n\n def visit_load_f_stack(self, load: models.LoadFStack) -> None:\n local_id = load.local_id\n assert local_id in self._f_stack, f\"{local_id} not found in f-stack\"\n dig = self._get_f_stack_dig_bury(local_id)\n assert dig == load.depth, f\"expected {dig=} == {load.depth=}\"\n self._apply_lstack_effects(load)\n\n def visit_store_x_stack(self, store: models.StoreXStack) -> None:\n local_id = store.local_id\n assert self._l_stack, f\"l-stack too small to store {local_id} to x-stack\"\n\n cover = len(self._x_stack) + len(self._l_stack) - 1\n assert cover == store.depth, f\"expected {cover=} == {store.depth=}\"\n self._x_stack.insert(0, local_id)\n self._apply_lstack_effects(store)\n\n def visit_load_x_stack(self, load: models.LoadXStack) -> None:\n local_id = load.local_id\n assert local_id in self._x_stack, f\"{local_id} not found in x-stack\"\n index = self._x_stack.index(local_id)\n uncover = len(self._l_stack) + len(self._x_stack) - index - 1\n assert uncover == load.depth, f\"expected {uncover=} == {load.depth=}\"\n self._x_stack.pop(index)\n self._apply_lstack_effects(load)\n\n def visit_store_l_stack(self, store: models.StoreLStack) -> None:\n cover = store.depth\n local_id = store.local_id\n assert cover < len(\n self._l_stack\n ), f\"l-stack too small to store (cover {cover}) {store.local_id} to l-stack\"\n index = len(self._l_stack) - cover - 1\n self._l_stack.pop()\n self._l_stack.insert(index, local_id)\n self._apply_lstack_effects(store)\n\n def visit_load_l_stack(self, load: models.LoadLStack) -> None:\n local_id = load.local_id\n uncover = load.depth\n if uncover is None: # during l-stack construction depth is not fixed\n index = self._l_stack.index(local_id)\n else:\n index = len(self._l_stack) - uncover - 1\n if not load.copy:\n self._l_stack.pop(index)\n self._apply_lstack_effects(load)\n\n def visit_load_param(self, load: models.LoadParam) -> None:\n assert load.local_id in self.parameters, f\"{load.local_id} is not a parameter\"\n self._apply_lstack_effects(load)\n\n def visit_store_param(self, store: models.StoreParam) -> None:\n assert store.local_id in self.parameters, f\"{store.local_id} is not a parameter\"\n self._apply_lstack_effects(store)\n\n def visit_allocate(self, allocate: models.Allocate) -> None:\n self._f_stack.extend(allocate.allocate_on_entry)\n\n def visit_pop(self, pop: models.Pop) -> None:\n self._apply_lstack_effects(pop)\n\n def visit_callsub(self, callsub: models.CallSub) -> None:\n self._apply_lstack_effects(callsub)\n\n def visit_retsub(self, retsub: models.RetSub) -> None:\n assert len(self._l_stack) == retsub.returns, (\n f\"Inconsistent l-stack height for retsub,\"\n f\" expected {retsub.returns}, actual: {len(self._l_stack)}\"\n )\n\n # retsub moves return values down below the frame to the stack height before the sub was\n # called and discards anything above.\n # represent this in the virtual stack with a new stack state with only the current\n # l-stack (i.e. discard all values in parameters, f-stack and x-stack)\n self.parameters = []\n self._f_stack = []\n self._x_stack = []\n\n def visit_conditional_branch(self, op: models.ConditionalBranch) -> None:\n self._apply_lstack_effects(op)\n\n def visit_err(self, op: models.Err) -> None:\n self._apply_lstack_effects(op)\n\n def visit_goto(self, op: models.Goto) -> None:\n self._apply_lstack_effects(op)\n\n def visit_match(self, op: models.Match) -> None:\n self._apply_lstack_effects(op)\n\n def visit_program_exit(self, op: models.ProgramExit) -> None:\n self._apply_lstack_effects(op)\n\n def visit_switch(self, op: models.Switch) -> None:\n self._apply_lstack_effects(op)\n\n def visit_intrinsic(self, intrinsic: models.IntrinsicOp) -> None:\n self._apply_lstack_effects(intrinsic)\n\n def _apply_lstack_effects(self, op: models.BaseOp) -> None:\n assert len(self._l_stack) >= op.consumes, f\"l-stack too small for {op}\"\n start = len(self._l_stack) - op.consumes\n self._l_stack[start:] = op.produces\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/mir\/stack.py","language":"Python","license":"NOASSERTION","size":8580} {"code":"from puya.mir import models\nfrom puya.mir.context import ProgramMIRContext, SubroutineCodeGenContext\nfrom puya.mir.output import output_memory_ir\nfrom puya.mir.stack_allocation.f_stack import f_stack_allocation\nfrom puya.mir.stack_allocation.l_stack import l_stack_allocation\nfrom puya.mir.stack_allocation.peephole import peephole_optimization_single_pass\nfrom puya.mir.stack_allocation.x_stack import x_stack_allocation\n\n# Note: implementation of http:\/\/www.euroforth.org\/ef06\/shannon-bailey06.pdf\n\n\ndef global_stack_allocation(ctx: ProgramMIRContext, program: models.Program) -> None:\n for desc, method in {\n \"lstack\": l_stack_allocation,\n \"lstack.opt\": _peephole_optimization,\n \"xstack\": x_stack_allocation,\n \"xstack.opt\": _peephole_optimization,\n \"fstack\": f_stack_allocation,\n \"fstack.opt\": _peephole_optimization,\n }.items():\n for mir_sub in program.all_subroutines:\n sub_ctx = ctx.for_subroutine(mir_sub)\n method(sub_ctx)\n if ctx.options.output_memory_ir:\n output_memory_ir(ctx, program, qualifier=desc)\n if ctx.options.output_memory_ir:\n output_memory_ir(ctx, program, qualifier=\"\")\n\n\ndef _peephole_optimization(ctx: SubroutineCodeGenContext) -> None:\n # replace sequences of stack manipulations with shorter ones\n vla_modified = False\n for block in ctx.subroutine.body:\n result = peephole_optimization_single_pass(ctx, block)\n vla_modified = vla_modified or result.vla_modified\n if vla_modified:\n ctx.invalidate_vla()\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/mir\/stack_allocation\/__init__.py","language":"Python","license":"NOASSERTION","size":1566} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport attrs\n\nfrom puya import log\nfrom puya.avm import AVMType\nfrom puya.errors import InternalError\nfrom puya.mir import models as mir\nfrom puya.mir.context import SubroutineCodeGenContext\nfrom puya.mir.stack import Stack\nfrom puya.utils import attrs_extend\n\nlogger = log.get_logger(__name__)\n\n\ndef _get_lazy_fstack(subroutine: mir.MemorySubroutine) -> dict[str, mir.AbstractStore]:\n # TODO: consider more than the entry block\n entry = subroutine.body[0]\n # if entry is re-entrant then can't lazy allocate anything\n if entry.predecessors:\n return {}\n result = dict[str, mir.AbstractStore]()\n for op in entry.ops:\n if isinstance(op, mir.AbstractStore):\n result.setdefault(op.local_id, op)\n return result\n\n\ndef _get_local_id_types(subroutine: mir.MemorySubroutine) -> dict[str, AVMType]:\n variable_mapping = dict[str, AVMType]()\n for block in subroutine.body:\n for op in block.ops:\n if isinstance(op, mir.AbstractStore):\n try:\n existing_type = variable_mapping[op.local_id]\n except KeyError:\n existing_type = op.atype\n variable_mapping[op.local_id] = existing_type | op.atype\n return variable_mapping\n\n\ndef _get_allocate_op(\n subroutine: mir.MemorySubroutine, all_variables: Sequence[str]\n) -> mir.Allocate:\n # determine variables to allocate at beginning of frame,\n # and order them so bytes are listed first, followed by uints\n byte_vars = []\n uint64_vars = []\n variable_type_mapping = _get_local_id_types(subroutine)\n for variable in all_variables:\n match variable_type_mapping.get(variable):\n case AVMType.uint64:\n uint64_vars.append(variable)\n case AVMType.bytes:\n byte_vars.append(variable)\n case AVMType.any:\n raise InternalError(\n \"Encountered AVM type any on preamble construction\",\n subroutine.source_location,\n )\n case None:\n # shouldn't occur, undefined variables should still have an Undefined entry\n # with a type\n raise InternalError(f\"Undefined register: {variable}\", subroutine.source_location)\n case unexpected:\n typing.assert_never(unexpected)\n return mir.Allocate(bytes_vars=byte_vars, uint64_vars=uint64_vars)\n\n\ndef f_stack_allocation(ctx: SubroutineCodeGenContext) -> None:\n all_variables = ctx.vla.all_variables\n if not all_variables:\n return\n\n subroutine = ctx.subroutine\n first_store_ops = _get_lazy_fstack(subroutine)\n allocate_on_first_store = list(first_store_ops)\n\n unsorted_pre_allocate = [x for x in all_variables if x not in first_store_ops]\n if unsorted_pre_allocate:\n allocate = _get_allocate_op(subroutine, unsorted_pre_allocate)\n allocate_at_entry = allocate.allocate_on_entry\n subroutine.body[0].mem_ops.insert(0, allocate)\n else:\n allocate_at_entry = []\n logger.debug(f\"{subroutine.signature.name} f-stack entry: {allocate_at_entry}\")\n logger.debug(f\"{subroutine.signature.name} f-stack on first store: {allocate_on_first_store}\")\n\n all_f_stack = [*allocate_at_entry, *first_store_ops.keys()]\n subroutine.body[0].f_stack_out = all_f_stack\n for block in subroutine.body[1:]:\n block.f_stack_in = block.f_stack_out = all_f_stack\n\n removed_virtual = False\n for block in subroutine.body:\n stack = Stack.begin_block(subroutine, block)\n for index, op in enumerate(block.mem_ops):\n match op:\n case mir.AbstractStore() as store:\n insert = op in first_store_ops.values()\n if insert:\n depth = stack.xl_height - 1\n else:\n depth = stack.fxl_height - stack.f_stack.index(store.local_id) - 1\n\n block.mem_ops[index] = op = attrs_extend(\n mir.StoreFStack,\n store,\n depth=depth,\n frame_index=stack.fxl_height - depth - 1,\n insert=insert,\n )\n removed_virtual = True\n case mir.AbstractLoad() as load:\n depth = stack.fxl_height - stack.f_stack.index(load.local_id) - 1\n block.mem_ops[index] = op = attrs_extend(\n mir.LoadFStack,\n load,\n depth=depth,\n frame_index=stack.fxl_height - depth - 1,\n )\n removed_virtual = True\n op.accept(stack)\n match block.terminator:\n case mir.RetSub() as retsub:\n block.terminator = attrs.evolve(\n retsub, fx_height=len(stack.f_stack) + len(stack.x_stack)\n )\n if removed_virtual:\n ctx.invalidate_vla()\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/mir\/stack_allocation\/f_stack.py","language":"Python","license":"NOASSERTION","size":5074} {"code":"import itertools\n\nimport attrs\n\nfrom puya import log\nfrom puya.mir import models as mir\nfrom puya.mir.context import SubroutineCodeGenContext\nfrom puya.mir.stack import Stack\n\nlogger = log.get_logger(__name__)\n\n\n@attrs.define\nclass UsagePair:\n a: mir.AbstractLoad | mir.AbstractStore\n b: mir.AbstractLoad\n a_index: int\n b_index: int\n\n @staticmethod\n def by_distance(pair: \"UsagePair\") -> tuple[int, int, int]:\n return pair.b_index - pair.a_index, pair.a_index, pair.b_index\n\n\ndef l_stack_allocation(ctx: SubroutineCodeGenContext) -> None:\n # the following is basically koopmans algorithm\n # done as part of http:\/\/www.euroforth.org\/ef06\/shannon-bailey06.pdf\n # see also https:\/\/users.ece.cmu.edu\/~koopman\/stack_compiler\/stack_co.html#appendix\n for block in ctx.subroutine.body:\n usage_pairs = _find_usage_pairs(block)\n _copy_usage_pairs(ctx, block, usage_pairs)\n for block in ctx.subroutine.body:\n _dead_store_removal(ctx, block)\n if ctx.options.optimization_level:\n _implicit_store_removal(block)\n # update vla after dead store removal\n ctx.invalidate_vla()\n # calculate load depths now that l-stack allocations are done\n for block in ctx.subroutine.body:\n _calculate_load_depths(ctx, block)\n\n\ndef _find_usage_pairs(block: mir.MemoryBasicBlock) -> list[UsagePair]:\n # find usage pairs of variables within the block\n # the first element of the pair is an op that defines or uses a variable\n # the second element of the pair is an op that uses the variable\n # return pairs in ascending order, based on the number of instruction between each pair\n variables = dict[str, list[tuple[int, mir.AbstractStore | mir.AbstractLoad]]]()\n for index, op in enumerate(block.ops):\n match op:\n case mir.AbstractStore(local_id=local_id) | mir.AbstractLoad(local_id=local_id):\n variables.setdefault(local_id, []).append((index, op))\n\n pairs = list[UsagePair]()\n for uses in variables.values():\n # pairwise iteration means an op can only be in at most 2 pairs\n for (a_index, a), (b_index, b) in itertools.pairwise(uses):\n if isinstance(b, mir.AbstractStore):\n continue # skip redefines, if they are used they will be picked up in next pair\n pairs.append(UsagePair(a=a, b=b, a_index=a_index, b_index=b_index))\n\n return sorted(pairs, key=UsagePair.by_distance)\n\n\ndef _copy_usage_pairs(\n ctx: SubroutineCodeGenContext, block: mir.MemoryBasicBlock, pairs: list[UsagePair]\n) -> None:\n # 1. copy define or use to bottom of l-stack\n # 2. replace usage with instruction to rotate the value from the bottom of l-stack to the top\n\n # to copy: dup, cover {stack_height}\n # to rotate: uncover {stack_height} - 1\n replaced_ops = dict[mir.StoreOp | mir.LoadOp, mir.LoadOp]()\n for pair in pairs:\n # note: pairs may refer to ops that have been replaced by an earlier iteration\n a = replaced_ops.get(pair.a, pair.a)\n b = replaced_ops.get(pair.b, pair.b)\n local_id = a.local_id\n # step 1. copy define or use to bottom of stack\n\n # redetermine index as block ops may have changed\n a_index = block.mem_ops.index(a)\n\n # insert replacement before store, or after load\n insert_index = a_index if isinstance(a, mir.AbstractStore) else a_index + 1\n stack = Stack.begin_block(ctx.subroutine, block)\n for op in block.mem_ops[:insert_index]:\n op.accept(stack)\n dup = mir.StoreLStack(\n depth=len(stack.l_stack) - 1,\n local_id=local_id,\n # leave a copy for the original consumer of this value which is either:\n # a.) the virtual store we are inserting before\n # b.) whatever came after the virtual load we are inserting after\n # The copy will be eliminated during dead store removal if no longer required\n copy=True,\n source_location=a.source_location,\n atype=a.atype,\n )\n block.mem_ops.insert(insert_index, dup)\n logger.debug(f\"Inserted {block.block_name}.ops[{insert_index}]: '{dup}'\")\n\n # step 2. replace b usage with instruction to rotate the value from the bottom of the stack\n # determine index of b, as inserts may have shifted its location\n b_index = block.mem_ops.index(b)\n\n uncover = mir.LoadLStack(\n # can not determine depth yet\n # as it depends on any other l-stack operations between the store and this load\n # which could change until after dead store removal is complete\n depth=None,\n local_id=local_id,\n copy=False,\n source_location=b.source_location,\n atype=b.atype,\n )\n # replace op\n block.mem_ops[b_index] = uncover\n\n # remember replacement in case it is part of another pair\n # an op can only be at most in 2 pairs, so don't need to do this recursively\n replaced_ops[b] = uncover\n logger.debug(f\"Replaced {block.block_name}.ops[{b_index}]: '{b}' with '{uncover}'\")\n\n\ndef _dead_store_removal(ctx: SubroutineCodeGenContext, block: mir.MemoryBasicBlock) -> None:\n ops = block.mem_ops\n op_idx = 0\n while op_idx < len(ops) - 1:\n window = slice(op_idx, op_idx + 2)\n a, b = ops[window]\n if (\n isinstance(a, mir.StoreLStack)\n and a.copy\n and isinstance(b, mir.AbstractStore)\n and b.local_id not in ctx.vla.get_live_out_variables(b)\n ):\n # StoreLStack is used to:\n # 1.) create copy of the value to be immediately stored via virtual store\n # 2.) rotate the value to the bottom of the stack for use in a later op in this block\n # If it is a dead store, then the 1st scenario is no longer needed\n # and instead just need to ensure the value is moved to the bottom of the stack\n a = attrs.evolve(a, copy=False, produces=())\n ops[window] = [a]\n elif (\n isinstance(a, mir.LoadLStack)\n and not a.copy\n and isinstance(b, mir.StoreLStack)\n and b.copy\n and a.local_id == b.local_id\n ):\n a = attrs.evolve(\n a,\n copy=True,\n produces=(f\"{a.local_id} (copy)\",),\n )\n ops[window] = [a]\n op_idx += 1\n\n\ndef _implicit_store_removal(block: mir.MemoryBasicBlock) -> None:\n ops = block.mem_ops\n op_idx = 0\n while op_idx < len(ops):\n op = ops[op_idx]\n # see if ops immediately after this op are all storing to the l-stack what this op produces\n next_op_idx = op_idx + 1\n maybe_remove_window = slice(next_op_idx, next_op_idx + len(op.produces))\n maybe_remove = [\n maybe_store\n for maybe_store in ops[maybe_remove_window]\n if isinstance(maybe_store, mir.StoreLStack)\n and not maybe_store.copy\n and maybe_store.local_id in op.produces\n ]\n # if they all match then this means all values are implicitly on the l-stack\n # and we can safely remove the store ops\n if len(maybe_remove) == len(op.produces):\n ops[maybe_remove_window] = []\n op_idx = next_op_idx\n\n\ndef _calculate_load_depths(ctx: SubroutineCodeGenContext, block: mir.MemoryBasicBlock) -> None:\n stack = Stack.begin_block(ctx.subroutine, block)\n for idx, op in enumerate(block.mem_ops):\n if isinstance(op, mir.LoadLStack):\n local_id_index = stack.l_stack.index(op.local_id)\n block.mem_ops[idx] = attrs.evolve(op, depth=len(stack.l_stack) - local_id_index - 1)\n op.accept(stack)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/mir\/stack_allocation\/l_stack.py","language":"Python","license":"NOASSERTION","size":7791} {"code":"from collections.abc import Sequence\n\nimport attrs\n\nfrom puya.mir import models as mir\nfrom puya.mir.context import SubroutineCodeGenContext\n\n\ndef optimize_pair(\n ctx: SubroutineCodeGenContext,\n a: mir.Op,\n b: mir.Op,\n) -> Sequence[mir.Op] | None:\n \"\"\"Given a pair of ops, returns which ops should be kept including replacements\"\"\"\n # this function has been optimized to reduce the number of isinstance checks,\n # consider this when making any modifications\n\n # move local_ids to produces of previous op where possible\n if (\n isinstance(b, mir.StoreLStack | mir.StoreXStack | mir.StoreFStack)\n and len(a.produces)\n and a.produces[-1] != b.local_id\n ):\n a = attrs.evolve(a, produces=(*a.produces[:-1], b.local_id))\n return a, b\n\n # remove redundant stores and loads\n if a.produces and a.produces[-1] == _get_local_id_alias(b):\n return (a,)\n\n if isinstance(b, mir.AbstractStore) and b.local_id not in ctx.vla.get_live_out_variables(b):\n # note l-stack dead store removal occurs during l-stack allocation\n # this handles any other cases\n return a, mir.Pop(n=1, source_location=b.source_location)\n\n if isinstance(a, mir.LoadOp) and isinstance(b, mir.StoreOp) and a.local_id == b.local_id:\n match a, b:\n case mir.LoadXStack(), mir.StoreXStack():\n return ()\n case mir.LoadFStack(), mir.StoreFStack():\n return ()\n case mir.AbstractLoad(), mir.AbstractStore():\n # this is used see test_cases\/bug_load_store_load_store\n return ()\n return None\n\n\n@attrs.define(kw_only=True)\nclass PeepholeResult:\n modified: bool\n vla_modified: bool\n\n\ndef peephole_optimization_single_pass(\n ctx: SubroutineCodeGenContext, block: mir.MemoryBasicBlock\n) -> PeepholeResult:\n result = block.mem_ops\n op_idx = 0\n modified = False\n vla_modified = False\n while op_idx < len(result) - 1:\n window = slice(op_idx, op_idx + 2)\n curr_op, next_op = result[window]\n pair_result = optimize_pair(ctx, curr_op, next_op)\n if pair_result is not None:\n modified = True\n result[window] = pair_result\n # check if VLA needs updating\n vla_modified = (\n vla_modified\n or (\n curr_op not in pair_result\n and isinstance(curr_op, mir.AbstractStore | mir.AbstractLoad)\n )\n or (\n next_op not in pair_result\n and isinstance(next_op, mir.AbstractStore | mir.AbstractLoad)\n )\n )\n else: # if nothing optimized, then advance\n op_idx += 1\n return PeepholeResult(modified=modified, vla_modified=vla_modified)\n\n\ndef _get_local_id_alias(op: mir.BaseOp) -> str | None:\n \"\"\"Returns the local_id of a memory op if it has no effect\n apart from renaming the top variable on the stack\"\"\"\n if isinstance(op, mir.StoreLStack | mir.LoadLStack) and not op.copy and not op.depth:\n return op.local_id\n # TODO: the following can only be done if the movement between l-stack and the other stack\n # is captured somehow (also check assumption that it needs to be captured...)\n # if isinstance(op, mir.StoreXStack | mir.LoadXStack) and not op.depth:\n # return op.local_id\n # if isinstance(op, mir.StoreFStack) and op.insert and not op.depth:\n # return op.local_id\n return None\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/mir\/stack_allocation\/peephole.py","language":"Python","license":"NOASSERTION","size":3527} {"code":"import itertools\nfrom collections.abc import Iterable, Sequence, Set\n\nimport attrs\n\nfrom puya import log\nfrom puya.errors import InternalError\nfrom puya.mir import models as mir\nfrom puya.mir.context import SubroutineCodeGenContext\nfrom puya.mir.stack import Stack\n\nlogger = log.get_logger(__name__)\n\n\n@attrs.define(eq=False, repr=False)\nclass BlockRecord:\n block: mir.MemoryBasicBlock\n local_references: list[mir.AbstractStore | mir.AbstractLoad]\n live_in: Set[str]\n live_out: Set[str]\n children: \"list[BlockRecord]\" = attrs.field(factory=list)\n parents: \"list[BlockRecord]\" = attrs.field(factory=list)\n co_parents: \"list[BlockRecord]\" = attrs.field(factory=list)\n siblings: \"list[BlockRecord]\" = attrs.field(factory=list)\n\n x_stack_in: Sequence[str] | None = None\n x_stack_out: Sequence[str] | None = None\n\n def __repr__(self) -> str:\n # due to recursive nature of BlockRecord, provide str implementation to\n # simplify output\n return f\"BlockRecord({self.block})\"\n\n @staticmethod\n def by_index(block: \"BlockRecord\") -> int:\n return block.block.id\n\n\n@attrs.frozen\nclass EdgeSet:\n out_blocks: Sequence[BlockRecord] = attrs.field(converter=tuple[BlockRecord, ...])\n in_blocks: Sequence[BlockRecord] = attrs.field(converter=tuple[BlockRecord, ...])\n\n\ndef sort_by_appearance(\n variables: Set[str], block: mir.MemoryBasicBlock, *, load: bool = True\n) -> Sequence[str]:\n appearance = list[str]()\n block_ops = block.ops if load else reversed(block.ops)\n if load:\n virtual_ops = (o.local_id for o in block_ops if isinstance(o, mir.AbstractLoad))\n else:\n virtual_ops = (o.local_id for o in block_ops if isinstance(o, mir.AbstractStore))\n for local_id in virtual_ops:\n if local_id in variables and local_id not in appearance:\n appearance.append(local_id)\n # don't keep searching once we are done\n if len(appearance) == len(variables):\n break\n return appearance\n\n\ndef len_and_value(value: tuple[str, ...]) -> tuple[int, tuple[str, ...]]:\n return len(value), value\n\n\ndef find_shared_x_stack(x_stack_candidates: Sequence[Sequence[str]]) -> Sequence[str]:\n \"\"\"Find a common subsequence that is shared by all x-stacks\"\"\"\n cache = dict[tuple[tuple[str, ...], tuple[str, ...]], tuple[str, ...]]()\n\n def lcs(s1: tuple[str, ...], s2: tuple[str, ...]) -> tuple[str, ...]:\n key = (s1, s2)\n result = cache.get(key)\n if result is None:\n i = len(s1)\n j = len(s2)\n if i == 0 or j == 0:\n result = ()\n elif s1[-1] == s2[-1]:\n result = (*lcs(s1[:-1], s2[:-1]), s1[-1])\n else:\n result = max(lcs(s1[:-1], s2), lcs(s1, s2[:-1]), key=len_and_value)\n cache[key] = result\n return result\n\n shared, *others = sorted({tuple(s) for s in x_stack_candidates}, key=len_and_value)\n for other in others:\n shared = lcs(shared, other)\n return shared\n\n\ndef get_x_stack_load_ops(record: BlockRecord) -> set[mir.AbstractLoad]:\n block = record.block\n assert block.x_stack_in is not None\n\n remaining = set(block.x_stack_in)\n load_ops = []\n for ref in record.local_references:\n if isinstance(ref, mir.AbstractLoad) and ref.local_id in remaining:\n remaining.remove(ref.local_id)\n load_ops.append(ref)\n\n if remaining:\n raise InternalError(\n f\"Failed to move {', '.join(remaining)} from the x-stack\",\n location=block.source_location,\n )\n\n return set(load_ops)\n\n\ndef get_x_stack_store_ops(record: BlockRecord) -> set[mir.AbstractStore]:\n block = record.block\n assert block.x_stack_out is not None\n\n remaining = set(block.x_stack_out)\n store_ops = []\n for ref in reversed(record.local_references):\n if isinstance(ref, mir.AbstractStore) and ref.local_id in remaining:\n remaining.remove(ref.local_id)\n store_ops.append(ref)\n\n if remaining:\n raise InternalError(\n f\"Failed to copy {', '.join(remaining)} to the x-stack\",\n location=block.source_location,\n )\n\n return set(store_ops)\n\n\ndef add_x_stack_ops(ctx: SubroutineCodeGenContext, record: BlockRecord) -> None:\n block = record.block\n # determine ops to replace\n load_ops = get_x_stack_load_ops(record)\n store_ops = get_x_stack_store_ops(record)\n\n stack = Stack.begin_block(ctx.subroutine, block)\n for index, op in enumerate(block.mem_ops):\n if op in store_ops:\n assert isinstance(op, mir.AbstractStore)\n # can replace virtual store op because only variables that could be fully\n # scheduled are on the x-stack\n block.mem_ops[index] = op = mir.StoreXStack(\n local_id=op.local_id,\n depth=stack.xl_height - 1, # store to bottom\n atype=op.atype,\n source_location=op.source_location,\n )\n elif op in load_ops:\n assert isinstance(op, mir.AbstractLoad)\n block.mem_ops[index] = op = mir.LoadXStack(\n local_id=op.local_id,\n depth=stack.xl_height - stack.x_stack.index(op.local_id) - 1,\n atype=op.atype,\n source_location=op.source_location,\n )\n op.accept(stack)\n\n\ndef add_x_stack_ops_to_edge_sets(\n ctx: SubroutineCodeGenContext, edge_sets: Sequence[EdgeSet]\n) -> None:\n records = dict.fromkeys(\n b\n for edge_set in edge_sets\n for b in itertools.chain(edge_set.out_blocks, edge_set.in_blocks)\n if b.x_stack_in or b.x_stack_out\n )\n for record in records:\n assert record.x_stack_in is not None\n assert record.x_stack_out is not None\n record.block.x_stack_in = record.x_stack_in\n record.block.x_stack_out = record.x_stack_out\n add_x_stack_ops(ctx, record)\n\n\ndef _unique_ordered_blocks(blocks: Iterable[BlockRecord]) -> list[BlockRecord]:\n return sorted(set(blocks), key=BlockRecord.by_index)\n\n\ndef get_edge_set(block: BlockRecord) -> EdgeSet | None:\n out_blocks = _unique_ordered_blocks(itertools.chain((block,), block.co_parents))\n # keep expanding out_blocks (and consequently in_blocks) until out_blocks stabilize\n while True:\n in_blocks = _unique_ordered_blocks(s for p in out_blocks for s in p.children)\n new_out_blocks = _unique_ordered_blocks(p for s in in_blocks for p in s.parents)\n if new_out_blocks == out_blocks:\n break\n out_blocks = new_out_blocks\n\n return EdgeSet(out_blocks, in_blocks) if in_blocks else None\n\n\ndef get_edge_sets(ctx: SubroutineCodeGenContext) -> Sequence[EdgeSet]:\n subroutine = ctx.subroutine\n vla = ctx.vla\n records = {\n block: BlockRecord(\n block=block,\n local_references=[\n op for op in block.ops if isinstance(op, mir.AbstractStore | mir.AbstractLoad)\n ],\n live_in=vla.get_live_in_variables(block.ops[0]),\n live_out=vla.get_live_out_variables(block.ops[-1]),\n )\n for block in subroutine.body\n }\n\n # given blocks 1,2,3,4,5,6 and 7\n # edges: 1->5, 2->4, 2->5, 2->6, 3->5, 7->6, 7->8\n #\n # e.g 1 2 3 7\n # \\\/|\\\/ \/ \\\n # \/ \\|\/ \\ \/ \\\n # 4 5 6 8\n #\n # consider 2\n # 4, 5 & 6 are children\n # 1 & 3 are co-parents of 5, 7 is a co-parent of 6\n # 1, 2, 3 and 7 form the out_blocks of an edge set\n # 4, 5 & 6 are the in_blocks of the same edge set\n\n # 1. first pass\n # populate children and parents\n blocks = [records[b] for b in subroutine.body]\n for block in blocks:\n block.children = [records[subroutine.get_block(c)] for c in block.block.successors]\n for child in block.children:\n child.parents.append(block)\n\n # 2. second pass - boundary mapping\n for block in blocks:\n # determine siblings\n for parent in block.parents:\n for child in parent.children:\n if child is not block and child not in block.siblings:\n block.siblings.append(child)\n\n # determine co-parents\n for child in block.children:\n for parent in child.parents:\n if parent is not block and parent not in block.co_parents:\n block.co_parents.append(parent)\n\n edge_sets = dict[EdgeSet, None]()\n for block in blocks:\n # keep expanding edge set until it stabilizes\n edge_set = get_edge_set(block)\n if edge_set:\n edge_sets[edge_set] = None\n else:\n block.x_stack_out = ()\n\n if not block.parents:\n block.x_stack_in = ()\n\n return list(edge_sets.keys())\n\n\ndef schedule_sets(ctx: SubroutineCodeGenContext, edge_sets: Sequence[EdgeSet]) -> None:\n # determine all blocks referencing variables, so we can track if all references to a\n # variable are scheduled to x-stack\n stores = dict[str, set[mir.MemoryBasicBlock]]()\n loads = dict[str, set[mir.MemoryBasicBlock]]()\n vla = ctx.vla\n for variable in vla.all_variables:\n stores[variable] = vla.get_store_blocks(variable)\n loads[variable] = vla.get_load_blocks(variable)\n\n for edge_set in edge_sets:\n in_blocks = edge_set.in_blocks\n out_blocks = edge_set.out_blocks\n\n # get potential l-stacks (unordered)\n l_stacks = [\n *(b.live_out for b in out_blocks),\n *(b.live_in for b in in_blocks),\n ]\n\n # determine shared l-stack variables for this edge_set\n # determine all valid x-stacks (ordered)\n first, *others = l_stacks\n common_locals = frozenset(first).intersection(*others)\n\n # TODO: better results might be possible if we allow reordering of x-stack\n x_stack_candidates = [\n *(sort_by_appearance(common_locals, b.block, load=False) for b in out_blocks),\n *(sort_by_appearance(common_locals, b.block, load=True) for b in in_blocks),\n ]\n\n # find an x_stack for this EdgeSet\n x_stack = find_shared_x_stack(x_stack_candidates)\n\n for block in out_blocks:\n assert block.x_stack_out is None\n block.x_stack_out = x_stack\n for x in x_stack:\n stores[x].remove(block.block)\n\n for block in in_blocks:\n assert block.x_stack_in is None\n block.x_stack_in = x_stack\n for x in x_stack:\n loads[x].remove(block.block)\n\n # adjust final x-stacks based on what could be fully scheduled\n variables_not_fully_scheduled = {\n var for var, blocks in itertools.chain(stores.items(), loads.items()) if len(blocks) > 0\n }\n variables_successfully_scheduled = sorted(stores.keys() - variables_not_fully_scheduled)\n for block in {b for es in edge_sets for b in itertools.chain((*es.out_blocks, *es.in_blocks))}:\n assert block.x_stack_out is not None\n assert block.x_stack_in is not None\n block.x_stack_out = tuple(\n x for x in block.x_stack_out if x in variables_successfully_scheduled\n )\n block.x_stack_in = tuple(\n x for x in block.x_stack_in if x in variables_successfully_scheduled\n )\n\n if variables_successfully_scheduled:\n ctx.invalidate_vla()\n logger.debug(\n f\"Allocated {len(variables_successfully_scheduled)} \"\n f\"variable\/s to x-stack: {', '.join(variables_successfully_scheduled)}\"\n )\n\n\ndef validate_pair(parent: BlockRecord, child: BlockRecord) -> bool:\n parent_x = parent.x_stack_out\n child_x = child.x_stack_in\n assert parent_x is not None\n assert child_x is not None\n if parent_x != child_x:\n logger.error(\n f\"x-stacks do not match for {parent.block} -> {child.block}: \"\n f\"{', '.join(parent_x)} -> {', '.join(child_x)}\"\n )\n return False\n if parent_x:\n logger.debug(f\"shared x-stack for {parent.block} -> {child.block}: {', '.join(parent_x)}\")\n return True\n\n\ndef validate_x_stacks(edge_sets: Sequence[EdgeSet]) -> bool:\n ok = True\n for edge_set in edge_sets:\n for parent in edge_set.out_blocks:\n for child in edge_set.in_blocks:\n ok = validate_pair(parent, child) and ok\n return ok\n\n\ndef x_stack_allocation(ctx: SubroutineCodeGenContext) -> None:\n # this is basically baileys algorithm\n edge_sets = get_edge_sets(ctx)\n if not edge_sets:\n # nothing to do\n return\n\n logger.debug(f\"Found {len(edge_sets)} edge set\/s for {ctx.subroutine.signature.name}\")\n schedule_sets(ctx, edge_sets)\n\n if not validate_x_stacks(edge_sets):\n raise InternalError(\"Could not schedule x-stack\")\n\n add_x_stack_ops_to_edge_sets(ctx, edge_sets)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/mir\/stack_allocation\/x_stack.py","language":"Python","license":"NOASSERTION","size":12878} {"code":"from __future__ import annotations\n\nimport abc\nimport typing\n\nif typing.TYPE_CHECKING:\n from puya.mir import models\n\n\nclass MIRVisitor[T](abc.ABC):\n @abc.abstractmethod\n def visit_int(self, push: models.Int) -> T: ...\n\n @abc.abstractmethod\n def visit_byte(self, push: models.Byte) -> T: ...\n\n @abc.abstractmethod\n def visit_undefined(self, push: models.Undefined) -> T: ...\n\n @abc.abstractmethod\n def visit_comment(self, comment: models.Comment) -> T: ...\n\n @abc.abstractmethod\n def visit_store_l_stack(self, store: models.StoreLStack) -> T: ...\n\n @abc.abstractmethod\n def visit_load_l_stack(self, load: models.LoadLStack) -> T: ...\n\n @abc.abstractmethod\n def visit_store_x_stack(self, store: models.StoreXStack) -> T: ...\n\n @abc.abstractmethod\n def visit_load_x_stack(self, load: models.LoadXStack) -> T: ...\n\n @abc.abstractmethod\n def visit_store_f_stack(self, store: models.StoreFStack) -> T: ...\n\n @abc.abstractmethod\n def visit_load_f_stack(self, load: models.LoadFStack) -> T: ...\n\n @abc.abstractmethod\n def visit_load_param(self, load: models.LoadParam) -> T: ...\n\n @abc.abstractmethod\n def visit_store_param(self, load: models.StoreParam) -> T: ...\n\n @abc.abstractmethod\n def visit_abstract_store(self, store: models.AbstractStore) -> T: ...\n\n @abc.abstractmethod\n def visit_abstract_load(self, load: models.AbstractLoad) -> T: ...\n\n @abc.abstractmethod\n def visit_allocate(self, allocate: models.Allocate) -> T: ...\n\n @abc.abstractmethod\n def visit_pop(self, pop: models.Pop) -> T: ...\n\n @abc.abstractmethod\n def visit_callsub(self, callsub: models.CallSub) -> T: ...\n\n @abc.abstractmethod\n def visit_intrinsic(self, intrinsic: models.IntrinsicOp) -> T: ...\n\n @abc.abstractmethod\n def visit_retsub(self, retsub: models.RetSub) -> T: ...\n\n @abc.abstractmethod\n def visit_program_exit(self, op: models.ProgramExit) -> T: ...\n\n @abc.abstractmethod\n def visit_err(self, op: models.Err) -> T: ...\n\n @abc.abstractmethod\n def visit_goto(self, op: models.Goto) -> T: ...\n\n @abc.abstractmethod\n def visit_conditional_branch(self, op: models.ConditionalBranch) -> T: ...\n\n @abc.abstractmethod\n def visit_switch(self, op: models.Switch) -> T: ...\n\n @abc.abstractmethod\n def visit_match(self, op: models.Match) -> T: ...\n\n @abc.abstractmethod\n def visit_address(self, addr: models.Address) -> T: ...\n\n @abc.abstractmethod\n def visit_method(self, method: models.Method) -> T: ...\n\n @abc.abstractmethod\n def visit_template_var(self, deploy_var: models.TemplateVar) -> T: ...\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/mir\/visitor.py","language":"Python","license":"NOASSERTION","size":2641} {"code":"import itertools\nimport typing\nfrom collections.abc import Sequence, Set\nfrom functools import cached_property\n\nimport attrs\n\nfrom puya.mir import models\nfrom puya.utils import StableSet\n\n\n@attrs.define(kw_only=True)\nclass _OpLifetime:\n block: models.MemoryBasicBlock\n used: StableSet[str] = attrs.field(on_setattr=attrs.setters.frozen)\n defined: StableSet[str] = attrs.field(on_setattr=attrs.setters.frozen)\n successors: list[typing.Self] = attrs.field(factory=list)\n predecessors: list[typing.Self] = attrs.field(factory=list)\n\n live_in: StableSet[str] = attrs.field(factory=StableSet)\n live_out: StableSet[str] = attrs.field(factory=StableSet)\n\n\n@attrs.define\nclass VariableLifetimeAnalysis:\n \"\"\"Performs VLA analysis for a subroutine, providing a mapping of ops to sets of live local_ids\n see https:\/\/www.classes.cs.uchicago.edu\/archive\/2004\/spring\/22620-1\/docs\/liveness.pdf\"\"\"\n\n subroutine: models.MemorySubroutine\n _op_lifetimes: dict[models.BaseOp, _OpLifetime] = attrs.field(init=False)\n\n @cached_property\n def all_variables(self) -> Sequence[str]:\n return sorted(\n {v for live in self._op_lifetimes.values() for v in (*live.defined, *live.used)}\n )\n\n @_op_lifetimes.default\n def _op_lifetimes_factory(self) -> dict[models.BaseOp, _OpLifetime]:\n result = dict[models.BaseOp, _OpLifetime]()\n block_map = {b.block_name: b.ops[0] for b in self.subroutine.body}\n for block in self.subroutine.body:\n for op in block.ops:\n used = StableSet[str]()\n defined = StableSet[str]()\n if isinstance(op, models.AbstractStore):\n defined.add(op.local_id)\n elif isinstance(op, models.AbstractLoad):\n used.add(op.local_id)\n result[op] = _OpLifetime(\n block=block,\n used=used,\n defined=defined,\n )\n for block in self.subroutine.body:\n for op, next_op in itertools.zip_longest(block.ops, block.ops[1:]):\n if isinstance(op, models.ControlOp):\n assert next_op is None\n # note: control ops that end the current subroutine don't have any logical\n # successors\n successors = [result[block_map[s]] for s in op.targets()]\n else:\n assert next_op is not None\n successors = [result[next_op]]\n op_lifetime = result[op]\n op_lifetime.successors = successors\n for s in successors:\n s.predecessors.append(op_lifetime)\n return result\n\n def get_live_out_variables(self, op: models.BaseOp) -> Set[str]:\n return self._op_lifetimes[op].live_out\n\n def get_live_in_variables(self, op: models.BaseOp) -> Set[str]:\n return self._op_lifetimes[op].live_in\n\n def get_store_blocks(self, variable: str) -> set[models.MemoryBasicBlock]:\n return {op.block for op in self._op_lifetimes.values() if variable in op.defined}\n\n def get_load_blocks(self, variable: str) -> set[models.MemoryBasicBlock]:\n return {op.block for op in self._op_lifetimes.values() if variable in op.used}\n\n @classmethod\n def analyze(cls, subroutine: models.MemorySubroutine) -> typing.Self:\n analysis = cls(subroutine)\n analysis._analyze() # noqa: SLF001\n return analysis\n\n def _analyze(self) -> None:\n changed = list(self._op_lifetimes.values())\n while changed:\n orig_changed = changed\n changed = []\n for n in orig_changed:\n # For OUT, find out the union of previous variables\n # in the IN set for each succeeding node of n.\n\n # out[n] = U s \u2208 succ[n] in[s]\n live_out = StableSet[str]()\n for s in n.successors:\n live_out |= s.live_in\n\n # in[n] = use[n] U (out[n] - def [n])\n live_in = n.used | (live_out - n.defined)\n\n if live_out != n.live_out or live_in != n.live_in:\n n.live_in = live_in\n n.live_out = live_out\n changed.extend(n.predecessors)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/mir\/vla.py","language":"Python","license":"NOASSERTION","size":4310} {"code":"import enum\nfrom collections.abc import Mapping\nfrom functools import cached_property\n\nimport attrs\n\nfrom puya.algo_constants import MAINNET_AVM_VERSION\n\n\nclass LocalsCoalescingStrategy(enum.StrEnum):\n root_operand = enum.auto()\n root_operand_excluding_args = enum.auto()\n aggressive = enum.auto()\n\n\n@attrs.frozen(kw_only=True)\nclass PuyaOptions:\n output_teal: bool = False\n output_source_map: bool = False\n output_arc32: bool = False\n output_arc56: bool = False\n output_ssa_ir: bool = False\n output_optimization_ir: bool = False\n output_destructured_ir: bool = False\n output_memory_ir: bool = False\n output_bytecode: bool = False\n debug_level: int = 1\n optimization_level: int = 1\n target_avm_version: int = MAINNET_AVM_VERSION\n cli_template_definitions: Mapping[str, int | bytes] = attrs.field(factory=dict)\n template_vars_prefix: str = \"TMPL_\"\n # TODO: the below is probably not scalable as a set of optimisation on\/off flags,\n # but it'll do for now\n locals_coalescing_strategy: LocalsCoalescingStrategy = LocalsCoalescingStrategy.root_operand\n\n @cached_property\n def template_variables(self) -> Mapping[str, int | bytes]:\n return {self.template_vars_prefix + k: v for k, v in self.cli_template_definitions.items()}\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/options.py","language":"Python","license":"NOASSERTION","size":1299} {"code":"import functools\nimport typing\nfrom collections.abc import Iterable\nfrom pathlib import Path\n\nimport attrs\n\nfrom puya.utils import make_path_relative_to_cwd\n\n\n@attrs.frozen(kw_only=True, repr=False, str=False)\nclass SourceLocation:\n file: Path | None = attrs.field()\n line: int = attrs.field(validator=attrs.validators.ge(1))\n end_line: int = attrs.field()\n comment_lines: int = attrs.field(default=0, validator=attrs.validators.ge(0))\n \"\"\"the number of lines preceding `line` to take as a comment\"\"\"\n column: int | None = attrs.field(\n default=None, validator=attrs.validators.optional(attrs.validators.ge(0))\n )\n end_column: int | None = attrs.field(\n default=None, validator=attrs.validators.optional(attrs.validators.ge(1))\n )\n\n @file.validator\n def _file_validator(self, _attribute: object, value: Path) -> None:\n # this check is simply to make sure relative paths aren't accidentally passed in.\n # so we use root rather than is_absolute(), because that requires a drive on Windows,\n # which we naturally don't supply for synthetic paths such as embedded lib.\n if value is not None and not value.root:\n raise ValueError(f\"source file locations cannot be relative, got {value}\")\n\n @end_line.default\n def _end_line_default(self) -> int:\n return self.line\n\n @end_line.validator\n def _end_line_validator(self, _attribute: object, value: int) -> None:\n if value < self.line:\n raise ValueError(f\"end_line = {value} is before start line = {self.line}\")\n\n @end_column.validator\n def _end_column_validator(self, _attribute: object, value: int | None) -> None:\n if (\n self.end_line == self.line\n and value is not None\n and self.column is not None\n and value <= self.column\n ):\n raise ValueError(\n f\"source location end column = {value} is before start column = {self.column}\"\n )\n\n @property\n def line_count(self) -> int:\n return self.end_line - self.line + 1\n\n def __str__(self) -> str:\n relative_path = make_path_relative_to_cwd(self.file) if self.file else \"INTERNAL\"\n result = f\"{relative_path}:{self.line}\"\n if self.end_line != self.line:\n result += f\"-{self.end_line}\"\n return result\n\n def __repr__(self) -> str:\n result = str(self)\n if self.column is not None:\n result += f\":{self.column}\"\n if self.end_column is not None:\n result += f\"-{self.end_column}\"\n return result\n\n def with_comments(self) -> \"SourceLocation\":\n if self.comment_lines == 0:\n return self\n return attrs.evolve(\n self,\n line=self.line - self.comment_lines,\n column=None,\n comment_lines=0,\n )\n\n def try_merge(self, other: \"SourceLocation | None\") -> \"SourceLocation\":\n \"\"\"Attempt to merge this source location with another, if they are either adjacent\n or overlapping in lines. If not, the source location is returned unmodified.\"\"\"\n if other is None or other.file != self.file:\n return self\n file = self.file\n # if they both start at the same line, not only is there overlap,\n # but things are also much simpler\n if self.line == other.line:\n line = self.line\n # expand to the largest end_line\n end_line = max(self.end_line, other.end_line)\n # in theory this should be the same value, but just in case, we can take the max\n comment_lines = max(self.comment_lines, other.comment_lines)\n # if either location is not column-bounded, then the result shouldn't be either\n # otherwise take the minimum of the columns, since the line numbers are the same\n if self.column is None or other.column is None:\n column = None\n else:\n column = min(self.column, other.column)\n else:\n # if they don't start on the same line, one must start first\n first, second = (self, other) if self.line < other.line else (other, self)\n line_after_first = first.end_line + 1\n # TODO: maybe consider fetching the source to exclude blank lines?\n if line_after_first < second.line:\n return self\n # first starts first, so... that's where we start\n line = first.line\n # whilst we know first starts before second,\n # it's also possible that first ends after second\n end_line = max(second.end_line, first.end_line)\n # naturally, comment line count needs to come from the first location\n comment_lines = first.comment_lines\n # same first starting column\n column = first.column\n # the logic for computing the end_column is the same regardless of whether\n # they start on the same line or not\n if self.end_line == other.end_line:\n # if either location is not end_column-bounded, then the result shouldn't be either\n # otherwise take the maximum of the end_columns, since the line numbers are the same\n if self.end_column is None or other.end_column is None:\n end_column = None\n else:\n end_column = max(self.end_column, other.end_column)\n elif self.end_line > other.end_line:\n # if self ends last, take it's end column\n end_column = self.end_column\n else:\n # otherwise other ends last, so take it's end column\n end_column = other.end_column\n\n return SourceLocation(\n file=file,\n line=line,\n end_line=end_line,\n comment_lines=comment_lines,\n column=column,\n end_column=end_column,\n )\n\n\n@typing.overload\ndef sequential_source_locations_merge(sources: Iterable[SourceLocation]) -> SourceLocation: ...\n\n\n@typing.overload\ndef sequential_source_locations_merge(\n sources: Iterable[SourceLocation | None],\n) -> SourceLocation | None: ...\n\n\ndef sequential_source_locations_merge(\n sources: Iterable[SourceLocation | None],\n) -> SourceLocation | None:\n \"\"\"Given a sequence of SourceLocations, try merging them one at a one in order.\n\n If all sources are None, then None is returned.\n\n If there are no sources, then a TypeError will be raised.\n \"\"\"\n return functools.reduce(_try_merge_source_locations, sources)\n\n\ndef _try_merge_source_locations(\n source: SourceLocation | None, merge: SourceLocation | None\n) -> SourceLocation | None:\n if source is None:\n return merge\n return source.try_merge(merge)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/parse.py","language":"Python","license":"NOASSERTION","size":6777} {"code":"import abc\nimport enum\nimport typing\n\nimport attrs\n\n\nclass ContractReference(str): # can't use typing.NewType with pattern matching\n __slots__ = ()\n\n\nclass LogicSigReference(str): # can't use typing.NewType with pattern matching\n __slots__ = ()\n\n\nclass ProgramKind(enum.StrEnum):\n approval = \"approval\"\n clear_state = \"clear\"\n logic_signature = \"lsig\"\n\n\nclass ProgramReference(abc.ABC):\n @property\n @abc.abstractmethod\n def kind(self) -> ProgramKind: ...\n\n @property\n @abc.abstractmethod\n def reference(self) -> ContractReference | LogicSigReference: ...\n\n @property\n @abc.abstractmethod\n def id(self) -> str: ...\n\n\n@attrs.frozen\nclass LogicSigProgramReference(ProgramReference):\n kind: typing.Literal[ProgramKind.logic_signature] = attrs.field(\n default=ProgramKind.logic_signature, init=False\n )\n reference: LogicSigReference\n\n @property\n def id(self) -> str:\n return self.reference\n\n\n@attrs.frozen\nclass ContractProgramReference(ProgramReference):\n kind: typing.Literal[ProgramKind.approval, ProgramKind.clear_state]\n reference: ContractReference\n program_name: str\n\n @property\n def id(self) -> str:\n return f\"{self.reference}.{self.program_name}\"\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/program_refs.py","language":"Python","license":"NOASSERTION","size":1246} {"code":"","repo_name":"algorandfoundation\/puya","path":"src\/puya\/teal\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport attrs\n\nfrom puya.errors import InternalError\nfrom puya.teal import models\n\n_T = typing.TypeVar(\"_T\", bound=models.TealOp)\n\n\ndef preserve_stack_manipulations(\n ops: list[_T],\n window: slice,\n new: Sequence[_T],\n) -> None:\n \"\"\"Replaces window of ops with new, preserving any stack manipulations from original window\n\n new is not empty: added to last op in new\n new is empty, window starts after first index: appended to prior op\n new is empty, window ends before last index: prepended to subsequent op\n \"\"\"\n if not new:\n # expand window to include at least 1 op\n if window.start > 0:\n # expand window to prior op\n window = slice(window.start - 1, window.stop)\n new = [ops[window.start]]\n elif window.stop < len(ops): # must be start of a block\n # expand window to subsequent op\n new = [ops[window.stop]]\n window = slice(window.start, window.stop + 1)\n else:\n # can this even happen? if it does, maybe attach to block instead?\n raise InternalError(\"could not preserve stack manipulations\")\n\n # clear existing stack_manipulations on new sequence\n new = [attrs.evolve(op, stack_manipulations=()) for op in new]\n # add original stack manipulations to last op in new sequence\n new[-1] = attrs.evolve(\n new[-1],\n stack_manipulations=[sm for op in ops[window] for sm in op.stack_manipulations],\n )\n # replace original ops with new ops\n ops[window] = new\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/teal\/_util.py","language":"Python","license":"NOASSERTION","size":1583} {"code":"import typing\nfrom itertools import zip_longest\n\nimport attrs\n\nfrom puya.avm import AVMType\nfrom puya.errors import InternalError\nfrom puya.ir.types_ import AVMBytesEncoding\nfrom puya.mir import models as mir\nfrom puya.mir.visitor import MIRVisitor\nfrom puya.teal import models as teal\n\n\n@attrs.frozen\nclass TealBuilder(MIRVisitor[None]):\n next_block_label: str | None\n use_frame: bool\n label_stack: list[str]\n ops: list[teal.TealOp] = attrs.field(factory=list)\n\n @classmethod\n def build_subroutine(cls, mir_sub: mir.MemorySubroutine) -> teal.TealSubroutine:\n result = teal.TealSubroutine(\n is_main=mir_sub.is_main,\n signature=mir_sub.signature,\n blocks=[],\n source_location=mir_sub.source_location,\n )\n entry_block = mir_sub.body[0]\n label_stack = [entry_block.block_name]\n blocks_by_label = {\n b.block_name: (b, None if next_b is None else next_b.block_name)\n for b, next_b in zip_longest(mir_sub.body, mir_sub.body[1:])\n }\n while label_stack:\n label = label_stack.pop()\n mir_block, next_block_label = blocks_by_label.pop(label, (None, None))\n if mir_block is None:\n continue\n builder = cls(\n next_block_label=next_block_label,\n use_frame=not mir_sub.is_main,\n label_stack=label_stack,\n )\n if mir_block is entry_block and not mir_sub.is_main:\n builder.ops.append(\n teal.Proto(\n parameters=len(mir_sub.signature.parameters),\n returns=len(mir_sub.signature.returns),\n source_location=mir_sub.source_location,\n )\n )\n for op in mir_block.ops:\n op.accept(builder)\n teal_block = teal.TealBlock(\n label=mir_block.block_name,\n ops=builder.ops,\n x_stack_in=mir_block.x_stack_in or (),\n entry_stack_height=mir_block.entry_stack_height,\n exit_stack_height=mir_block.exit_stack_height,\n )\n teal_block.validate_stack_height()\n result.blocks.append(teal_block)\n return result\n\n def _add_op(self, op: teal.TealOp) -> None:\n self.ops.append(op)\n\n def visit_int(self, const: mir.Int) -> None:\n self._add_op(\n teal.Int(\n const.value,\n stack_manipulations=_lstack_manipulations(const),\n source_location=const.source_location,\n )\n )\n\n def visit_byte(self, const: mir.Byte) -> None:\n self._add_op(\n teal.Byte(\n const.value,\n const.encoding,\n stack_manipulations=_lstack_manipulations(const),\n source_location=const.source_location,\n )\n )\n\n def visit_undefined(self, push: mir.Undefined) -> None:\n match push.atype:\n case AVMType.uint64:\n self._add_op(\n teal.Byte(\n b\"\",\n AVMBytesEncoding.utf8,\n stack_manipulations=_lstack_manipulations(push),\n source_location=push.source_location,\n )\n )\n case AVMType.bytes:\n self._add_op(\n teal.Int(\n 0,\n stack_manipulations=_lstack_manipulations(push),\n source_location=push.source_location,\n )\n )\n case unexpected:\n typing.assert_never(unexpected)\n\n def visit_template_var(self, const: mir.TemplateVar) -> None:\n self._add_op(\n teal.TemplateVar(\n name=const.name,\n op_code=const.op_code,\n stack_manipulations=_lstack_manipulations(const),\n source_location=const.source_location,\n )\n )\n\n def visit_address(self, const: mir.Address) -> None:\n self._add_op(\n teal.Address(\n const.value,\n stack_manipulations=_lstack_manipulations(const),\n source_location=const.source_location,\n )\n )\n\n def visit_method(self, const: mir.Method) -> None:\n self._add_op(\n teal.Method(\n const.value,\n stack_manipulations=_lstack_manipulations(const),\n source_location=const.source_location,\n )\n )\n\n def visit_comment(self, _comment: mir.Comment) -> None:\n pass\n\n def visit_abstract_store(self, store: mir.AbstractStore) -> typing.Never:\n raise InternalError(\n \"AbstractStore op encountered during TEAL generation\", store.source_location\n )\n\n def visit_abstract_load(self, load: mir.AbstractLoad) -> typing.Never:\n raise InternalError(\n \"AbstractLoad op encountered during TEAL generation\", load.source_location\n )\n\n def _store_f_stack(self, store: mir.StoreFStack) -> None:\n local_id = store.local_id\n source_location = store.source_location\n define = teal.StackDefine(local_id)\n if self.use_frame:\n op: teal.TealOp = teal.FrameBury(\n store.frame_index,\n stack_manipulations=[*_lstack_manipulations(store), define],\n source_location=source_location,\n )\n else:\n op = teal.Bury(\n store.depth,\n stack_manipulations=[*_lstack_manipulations(store), define],\n source_location=source_location,\n )\n self._add_op(op)\n\n def _insert_f_stack(self, store: mir.StoreFStack) -> None:\n local_id = store.local_id\n source_location = store.source_location\n self._add_op(\n teal.Cover(\n store.depth,\n stack_manipulations=[\n *_lstack_manipulations(store),\n teal.StackInsert(store.depth, local_id),\n teal.StackDefine(local_id),\n ],\n source_location=source_location,\n )\n )\n\n def visit_store_f_stack(self, store: mir.StoreFStack) -> None:\n if store.insert:\n self._insert_f_stack(store)\n else:\n self._store_f_stack(store)\n\n def visit_load_f_stack(self, load: mir.LoadFStack) -> None:\n sm = _lstack_manipulations(load)\n loc = load.source_location\n if self.use_frame: # and load.depth:\n op: teal.TealOp = teal.FrameDig(\n n=load.frame_index, stack_manipulations=sm, source_location=loc\n )\n else:\n op = teal.Dig(n=load.depth, stack_manipulations=sm, source_location=loc)\n self._add_op(op)\n\n def visit_store_x_stack(self, store: mir.StoreXStack) -> None:\n self._add_op(\n teal.Cover(\n store.depth,\n stack_manipulations=[\n *_lstack_manipulations(store),\n teal.StackInsert(store.depth, store.local_id),\n teal.StackDefine(store.local_id),\n ],\n source_location=store.source_location,\n )\n )\n\n def visit_load_x_stack(self, load: mir.LoadXStack) -> None:\n self._add_op(\n teal.Uncover(\n load.depth,\n stack_manipulations=[\n teal.StackPop(load.depth),\n *_lstack_manipulations(load),\n ],\n source_location=load.source_location,\n )\n )\n\n def visit_store_l_stack(self, store: mir.StoreLStack) -> None:\n if store.copy:\n self._add_op(\n teal.Dup(\n stack_manipulations=[\n # re-alias top of stack\n teal.StackConsume(1),\n *_lstack_manipulations(store),\n # actual dup\n teal.StackExtend([f\"{store.local_id} (copy)\"]),\n ],\n source_location=store.source_location,\n ),\n )\n cover = store.depth\n if store.copy:\n cover += 1\n self._add_op(\n teal.Cover(\n cover,\n stack_manipulations=[\n teal.StackConsume(1),\n # store\n teal.StackInsert(cover, store.local_id),\n teal.StackDefine([store.local_id]),\n ],\n source_location=store.source_location,\n )\n )\n\n def visit_load_l_stack(self, load: mir.LoadLStack) -> None:\n uncover = load.depth\n assert uncover is not None, \"expected l-stack depths to be assigned\"\n if load.copy:\n self._add_op(\n teal.Dig(\n uncover,\n stack_manipulations=_lstack_manipulations(load),\n source_location=load.source_location,\n )\n )\n else:\n self._add_op(\n teal.Uncover(\n uncover,\n stack_manipulations=[teal.StackPop(uncover), *_lstack_manipulations(load)],\n source_location=load.source_location,\n )\n )\n\n def visit_load_param(self, load: mir.LoadParam) -> None:\n self._add_op(\n teal.FrameDig(\n load.index,\n source_location=load.source_location,\n stack_manipulations=_lstack_manipulations(load),\n )\n )\n\n def visit_store_param(self, store: mir.StoreParam) -> None:\n self._add_op(\n teal.FrameBury(\n store.index,\n stack_manipulations=_lstack_manipulations(store),\n source_location=store.source_location,\n )\n )\n\n def visit_allocate(self, allocate: mir.Allocate) -> None:\n bad_bytes_value = teal.Int(\n 0,\n source_location=allocate.source_location,\n )\n bad_uint_value = teal.Byte(\n value=b\"\",\n encoding=AVMBytesEncoding.utf8,\n source_location=allocate.source_location,\n )\n\n for idx, local_id in enumerate(allocate.allocate_on_entry):\n bad_value = bad_bytes_value if idx < allocate.num_bytes else bad_uint_value\n self._add_op(\n attrs.evolve(\n bad_value,\n stack_manipulations=[teal.StackExtend([local_id])],\n )\n )\n\n def visit_pop(self, pop: mir.Pop) -> None:\n self._add_op(\n teal.PopN(\n n=pop.n,\n stack_manipulations=_lstack_manipulations(pop),\n source_location=pop.source_location,\n )\n )\n\n def visit_callsub(self, callsub: mir.CallSub) -> None:\n self._add_op(\n teal.CallSub(\n target=callsub.target,\n consumes=callsub.parameters,\n produces=callsub.returns,\n stack_manipulations=_lstack_manipulations(callsub),\n source_location=callsub.source_location,\n )\n )\n\n def visit_retsub(self, retsub: mir.RetSub) -> None:\n fx_height = retsub.fx_height\n if retsub.returns < fx_height:\n # move returns to base of frame in order\n for n in reversed(range(retsub.returns)):\n self._add_op(teal.FrameBury(n, source_location=retsub.source_location))\n else:\n # f-stack + x-stack is smaller than number of returns, so move it out of the way\n n = retsub.returns + fx_height - 1\n for _ in range(fx_height):\n self._add_op(teal.Uncover(n, source_location=retsub.source_location))\n self._add_op(\n teal.RetSub(\n consumes=retsub.returns,\n source_location=retsub.source_location,\n )\n )\n\n def visit_program_exit(self, op: mir.ProgramExit) -> None:\n self._add_op(\n teal.Return(\n error_message=op.error_message,\n stack_manipulations=_lstack_manipulations(op),\n source_location=op.source_location,\n )\n )\n\n def visit_err(self, op: mir.Err) -> None:\n self._add_op(\n teal.Err(\n error_message=op.error_message,\n stack_manipulations=_lstack_manipulations(op),\n source_location=op.source_location,\n )\n )\n\n def visit_goto(self, op: mir.Goto) -> None:\n self._add_op(\n teal.Branch(\n target=op.target,\n error_message=op.error_message,\n stack_manipulations=_lstack_manipulations(op),\n source_location=op.source_location,\n )\n )\n self.label_stack.append(op.target)\n\n def visit_conditional_branch(self, op: mir.ConditionalBranch) -> None:\n condition_op: type[teal.BranchNonZero | teal.BranchZero]\n if op.nonzero_target == self.next_block_label:\n condition_op = teal.BranchZero\n condition_op_target = op.zero_target\n other_target = op.nonzero_target\n else:\n condition_op = teal.BranchNonZero\n condition_op_target = op.nonzero_target\n other_target = op.zero_target\n\n self._add_op(\n condition_op(\n target=condition_op_target,\n error_message=op.error_message,\n stack_manipulations=_lstack_manipulations(op),\n source_location=op.source_location,\n )\n )\n self.label_stack.append(condition_op_target)\n self._add_op(\n teal.Branch(\n target=other_target,\n error_message=\"\",\n stack_manipulations=[],\n source_location=op.source_location,\n )\n )\n self.label_stack.append(other_target)\n\n def visit_switch(self, op: mir.Switch) -> None:\n self._add_op(\n teal.Switch(\n targets=op.switch_targets,\n error_message=op.error_message,\n stack_manipulations=_lstack_manipulations(op),\n source_location=op.source_location,\n )\n )\n self.label_stack.extend(op.switch_targets)\n self._add_op(\n teal.Branch(\n target=op.default_target,\n error_message=\"\",\n stack_manipulations=[],\n source_location=op.source_location,\n )\n )\n self.label_stack.append(op.default_target)\n\n def visit_match(self, op: mir.Match) -> None:\n self._add_op(\n teal.Match(\n targets=op.match_targets,\n error_message=op.error_message,\n stack_manipulations=_lstack_manipulations(op),\n source_location=op.source_location,\n )\n )\n self.label_stack.extend(op.match_targets)\n self._add_op(\n teal.Branch(\n target=op.default_target,\n error_message=\"\",\n stack_manipulations=[],\n source_location=op.source_location,\n )\n )\n self.label_stack.append(op.default_target)\n\n def visit_intrinsic(self, intrinsic: mir.IntrinsicOp) -> None:\n self._add_op(\n teal.Intrinsic(\n op_code=intrinsic.op_code,\n immediates=intrinsic.immediates,\n error_message=intrinsic.error_message,\n consumes=intrinsic.consumes,\n produces=len(intrinsic.produces),\n stack_manipulations=_lstack_manipulations(intrinsic),\n source_location=intrinsic.source_location,\n )\n )\n\n\ndef _lstack_manipulations(op: mir.BaseOp) -> list[teal.StackManipulation]:\n result = list[teal.StackManipulation]()\n if op.consumes:\n result.append(teal.StackConsume(op.consumes))\n if op.produces:\n result.append(teal.StackExtend(op.produces))\n result.append(teal.StackDefine(op.produces))\n return result\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/teal\/builder.py","language":"Python","license":"NOASSERTION","size":16431} {"code":"from puya import log\nfrom puya.context import CompileContext\nfrom puya.mir import models as mir\nfrom puya.teal import models as teal_models\nfrom puya.teal.builder import TealBuilder\nfrom puya.teal.optimize.main import optimize_teal_program\n\nlogger = log.get_logger(__name__)\n\n\ndef mir_to_teal(context: CompileContext, program_mir: mir.Program) -> teal_models.TealProgram:\n main = TealBuilder.build_subroutine(program_mir.main)\n subroutines = [TealBuilder.build_subroutine(mir_sub) for mir_sub in program_mir.subroutines]\n teal = teal_models.TealProgram(\n avm_version=program_mir.avm_version,\n main=main,\n subroutines=subroutines,\n )\n optimize_teal_program(context, teal)\n return teal\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/teal\/main.py","language":"Python","license":"NOASSERTION","size":723} {"code":"import abc\nimport typing\nfrom collections.abc import Iterable, Mapping, Sequence\n\nimport attrs\n\nfrom puya.avm import OnCompletionAction, TransactionType\nfrom puya.errors import InternalError\nfrom puya.ir.types_ import AVMBytesEncoding\nfrom puya.ir.utils import format_bytes, format_error_comment\nfrom puya.mir import models as mir\nfrom puya.parse import SourceLocation\nfrom puya.utils import valid_bytes, valid_int64\n\nMAX_NUMBER_CONSTANTS = 256\nTEAL_ALIASES = {\n **{e.name: e.value for e in OnCompletionAction},\n **{e.name: e.value for e in TransactionType},\n}\n\n\n@attrs.frozen\nclass StackConsume:\n n: int\n\n\n@attrs.frozen\nclass StackExtend:\n local_ids: Sequence[str]\n\n\n@attrs.frozen\nclass StackInsert:\n depth: int\n local_id: str\n\n\n@attrs.frozen\nclass StackPop:\n depth: int\n\n\n@attrs.frozen\nclass StackDefine:\n local_ids: Sequence[str]\n\n\nStackManipulation = StackConsume | StackExtend | StackDefine | StackInsert | StackPop\n\n\n@attrs.frozen(kw_only=True)\nclass TealOp:\n op_code: str\n consumes: int\n produces: int\n source_location: SourceLocation | None = attrs.field(eq=False)\n comment: str | None = None\n \"\"\"A comment that is always emitted after the op in TEAL\"\"\"\n error_message: str | None = None\n \"\"\"Error message to display if program fails at this op\"\"\"\n stack_manipulations: Sequence[StackManipulation] = attrs.field(\n default=(),\n converter=tuple[StackManipulation, ...],\n eq=False,\n )\n\n @property\n def immediates(self) -> Sequence[int | str]:\n return ()\n\n def teal(self) -> str:\n teal_args = [self.op_code, *map(str, self.immediates)]\n if self.comment or self.error_message:\n error_message = (\n format_error_comment(self.op_code, self.error_message)\n if self.error_message\n else \"\"\n )\n comment_lines = error_message.splitlines()\n comment_lines += (self.comment or \"\").splitlines()\n comment = \"\\n\/\/\".join(comment_lines)\n teal_args.append(f\"\/\/ {comment}\")\n return \" \".join(teal_args)\n\n @property\n def stack_height_delta(self) -> int:\n return self.produces - self.consumes\n\n\n@attrs.frozen\nclass Dup(TealOp):\n op_code: str = attrs.field(default=\"dup\", init=False)\n consumes: int = attrs.field(default=1, init=False)\n produces: int = attrs.field(default=2, init=False)\n\n\n@attrs.frozen\nclass Dup2(TealOp):\n op_code: str = attrs.field(default=\"dup2\", init=False)\n consumes: int = attrs.field(default=2, init=False)\n produces: int = attrs.field(default=4, init=False)\n\n\n@attrs.frozen\nclass Pop(TealOp):\n op_code: str = attrs.field(default=\"pop\", init=False)\n consumes: int = attrs.field(default=1, init=False)\n produces: int = attrs.field(default=0, init=False)\n\n\n@attrs.frozen\nclass TealOpN(TealOp):\n n: int = attrs.field(validator=[attrs.validators.ge(0), attrs.validators.le(255)])\n\n @property\n def immediates(self) -> Sequence[int | str]:\n return (self.n,)\n\n\n@attrs.frozen\nclass TealOpUInt8(TealOpN):\n n: int = attrs.field(validator=[attrs.validators.ge(0), attrs.validators.le(255)])\n\n\n@attrs.frozen\nclass TealOpInt8(TealOpN):\n n: int = attrs.field(validator=[attrs.validators.ge(-128), attrs.validators.le(127)])\n\n\n@attrs.frozen\nclass Cover(TealOpUInt8):\n op_code: str = attrs.field(default=\"cover\", init=False)\n consumes: int = attrs.field(init=False)\n produces: int = attrs.field(init=False)\n\n @consumes.default\n def _consumes(self) -> int:\n return self.n + 1\n\n @produces.default\n def _produces(self) -> int:\n return self.n + 1\n\n\n@attrs.frozen\nclass Uncover(TealOpUInt8):\n op_code: str = attrs.field(default=\"uncover\", init=False)\n consumes: int = attrs.field(init=False)\n produces: int = attrs.field(init=False)\n\n @consumes.default\n def _consumes(self) -> int:\n return self.n + 1\n\n @produces.default\n def _produces(self) -> int:\n return self.n + 1\n\n\n@attrs.frozen\nclass Swap(TealOp):\n op_code: str = attrs.field(default=\"swap\", init=False)\n consumes: int = 2\n produces: int = 2\n\n\n@attrs.frozen\nclass Dig(TealOpUInt8):\n op_code: str = attrs.field(default=\"dig\", init=False)\n consumes: int = attrs.field(init=False)\n produces: int = attrs.field(init=False)\n\n @consumes.default\n def _consumes(self) -> int:\n return self.n + 1\n\n @produces.default\n def _produces(self) -> int:\n return self.n + 2\n\n\n@attrs.frozen\nclass Bury(TealOpUInt8):\n op_code: str = attrs.field(default=\"bury\", init=False)\n consumes: int = attrs.field(init=False)\n produces: int = attrs.field(init=False)\n\n @consumes.default\n def _consumes(self) -> int:\n return self.n\n\n @produces.default\n def _produces(self) -> int:\n return self.n - 1\n\n\ndef _valid_uint64(node: TealOp, _attribute: object, value: int) -> None:\n if not valid_int64(value):\n raise InternalError(\n \"Invalid UInt64 value\",\n node.source_location,\n )\n\n\ndef _valid_bytes(node: TealOp, _attribute: object, value: bytes) -> None:\n if not valid_bytes(value):\n raise InternalError(\"Invalid Bytes value\", node.source_location)\n\n\ndef _valid_ref(node: TealOp, _attribute: object, value: int) -> None:\n if value < 0 or value >= MAX_NUMBER_CONSTANTS:\n raise InternalError(\n \"Invalid constant reference\",\n node.source_location,\n )\n\n\n@attrs.frozen\nclass IntBlock(TealOp):\n op_code: str = attrs.field(default=\"intcblock\", init=False)\n constants: Mapping[int | str, SourceLocation | None]\n consumes: int = attrs.field(default=0, init=False)\n produces: int = attrs.field(default=0, init=False)\n\n @property\n def immediates(self) -> Sequence[int | str]:\n return tuple(self.constants)\n\n\n@attrs.frozen\nclass IntC(TealOp):\n index: int = attrs.field(validator=_valid_ref)\n op_code: str = attrs.field(init=False)\n consumes: int = attrs.field(default=0, init=False)\n produces: int = attrs.field(default=1, init=False)\n\n @op_code.default\n def _op_code(self) -> str:\n if self.index < 4:\n return f\"intc_{self.index}\"\n else:\n return \"intc\"\n\n @property\n def immediates(self) -> Sequence[int]:\n if self.index < 4:\n return ()\n else:\n return (self.index,)\n\n\n@attrs.frozen\nclass PushInt(TealOp):\n op_code: str = attrs.field(default=\"pushint\", init=False)\n value: int = attrs.field(validator=_valid_uint64)\n consumes: int = attrs.field(default=0, init=False)\n produces: int = attrs.field(default=1, init=False)\n\n @property\n def immediates(self) -> Sequence[int]:\n return (self.value,)\n\n\n@attrs.frozen\nclass PushInts(TealOp):\n op_code: str = attrs.field(default=\"pushints\", init=False)\n values: list[int] = attrs.field(validator=attrs.validators.deep_iterable(_valid_uint64))\n consumes: int = attrs.field(default=0, init=False)\n produces: int = attrs.field(init=False)\n\n @produces.default\n def _produces(self) -> int:\n return len(self.values)\n\n @property\n def immediates(self) -> Sequence[int]:\n return self.values\n\n\n@attrs.frozen\nclass BytesBlock(TealOp):\n op_code: str = attrs.field(default=\"bytecblock\", init=False)\n constants: Mapping[bytes | str, tuple[AVMBytesEncoding, SourceLocation | None]]\n consumes: int = attrs.field(default=0, init=False)\n produces: int = attrs.field(default=0, init=False)\n\n @property\n def immediates(self) -> Sequence[str]:\n return tuple(\n _encoded_bytes(c, es[0]) if isinstance(c, bytes) else c\n for c, es in self.constants.items()\n )\n\n\n@attrs.frozen\nclass BytesC(TealOp):\n index: int = attrs.field(validator=_valid_ref)\n op_code: str = attrs.field(init=False)\n consumes: int = attrs.field(default=0, init=False)\n produces: int = attrs.field(default=1, init=False)\n\n @op_code.default\n def _op_code(self) -> str:\n if self.index < 4:\n return f\"bytec_{self.index}\"\n else:\n return \"bytec\"\n\n @property\n def immediates(self) -> Sequence[int]:\n if self.index < 4:\n return ()\n else:\n return (self.index,)\n\n\n@attrs.frozen\nclass PushBytes(TealOp):\n op_code: str = attrs.field(default=\"pushbytes\", init=False)\n value: bytes = attrs.field(validator=_valid_bytes)\n # exclude encoding from equality so for example 0x and \"\" can be combined\n encoding: AVMBytesEncoding = attrs.field(eq=False)\n consumes: int = attrs.field(default=0, init=False)\n produces: int = attrs.field(default=1, init=False)\n\n @property\n def immediates(self) -> Sequence[str]:\n return (_encoded_bytes(self.value, self.encoding),)\n\n\n@attrs.frozen\nclass PushBytess(TealOp):\n op_code: str = attrs.field(default=\"pushbytess\", init=False)\n values: Sequence[tuple[bytes, AVMBytesEncoding]] = attrs.field()\n consumes: int = attrs.field(default=0, init=False)\n produces: int = attrs.field(init=False)\n\n @produces.default\n def _produces(self) -> int:\n return len(self.values)\n\n @values.validator\n def _values_validator(\n self, _: object, value: Sequence[tuple[bytes, AVMBytesEncoding]]\n ) -> None:\n if not all(valid_bytes(b) for b, _ in value):\n raise InternalError(\"invalid bytes value\", self.source_location)\n\n @property\n def immediates(self) -> Sequence[str]:\n return tuple(_encoded_bytes(c, e) for c, e in self.values)\n\n\n@attrs.frozen\nclass FrameDig(TealOpInt8):\n op_code: str = attrs.field(default=\"frame_dig\", init=False)\n consumes: int = attrs.field(default=0, init=False)\n produces: int = attrs.field(default=1, init=False)\n\n\n@attrs.frozen\nclass FrameBury(TealOpInt8):\n op_code: str = attrs.field(default=\"frame_bury\", init=False)\n consumes: int = attrs.field(default=1, init=False)\n produces: int = attrs.field(default=0, init=False)\n\n\n@attrs.frozen\nclass Int(TealOp):\n value: int | str\n op_code: str = attrs.field(default=\"int\", init=False)\n consumes: int = attrs.field(default=0, init=False)\n produces: int = attrs.field(default=1, init=False)\n\n @property\n def immediates(self) -> Sequence[int | str]:\n return (self.value,)\n\n\n@attrs.frozen\nclass PopN(TealOpUInt8):\n op_code: str = attrs.field(default=\"popn\", init=False)\n consumes: int = attrs.field(init=False)\n produces: int = attrs.field(default=0, init=False)\n\n @consumes.default\n def _consumes(self) -> int:\n return self.n\n\n\n@attrs.frozen\nclass DupN(TealOpUInt8):\n op_code: str = attrs.field(default=\"dupn\", init=False)\n consumes: int = attrs.field(default=1, init=False)\n produces: int = attrs.field(init=False)\n\n @produces.default\n def _produces(self) -> int:\n return self.n + 1\n\n\n@attrs.frozen\nclass Proto(TealOp):\n parameters: int\n returns: int\n op_code: str = attrs.field(default=\"proto\", init=False)\n consumes: int = attrs.field(default=0, init=False)\n produces: int = attrs.field(default=0, init=False)\n\n @property\n def immediates(self) -> Sequence[int | str]:\n return self.parameters, self.returns\n\n\n@attrs.frozen\nclass Byte(TealOp):\n value: bytes\n # exclude encoding from equality so for example 0x and \"\" can be combined\n encoding: AVMBytesEncoding = attrs.field(eq=False)\n op_code: str = attrs.field(default=\"byte\", init=False)\n consumes: int = attrs.field(default=0, init=False)\n produces: int = attrs.field(default=1, init=False)\n\n @property\n def immediates(self) -> Sequence[int | str]:\n return (_encoded_bytes(self.value, self.encoding),)\n\n\n@attrs.frozen\nclass TemplateVar(TealOp):\n name: str\n op_code: typing.Literal[\"int\", \"byte\"]\n consumes: int = attrs.field(default=0, init=False)\n produces: int = attrs.field(default=1, init=False)\n\n @property\n def immediates(self) -> Sequence[int | str]:\n return (self.name,)\n\n\n@attrs.frozen\nclass Address(TealOp):\n value: str\n op_code: str = attrs.field(default=\"addr\", init=False)\n consumes: int = attrs.field(default=0, init=False)\n produces: int = attrs.field(default=1, init=False)\n\n @property\n def immediates(self) -> Sequence[int | str]:\n return (self.value,)\n\n\n@attrs.frozen\nclass Method(TealOp):\n value: str\n op_code: str = attrs.field(default=\"method\", init=False)\n consumes: int = attrs.field(default=0, init=False)\n produces: int = attrs.field(default=1, init=False)\n\n @property\n def immediates(self) -> Sequence[int | str]:\n return (f'\"{self.value}\"',)\n\n\n@attrs.frozen\nclass Intrinsic(TealOp):\n immediates: Sequence[int | str]\n\n\n@attrs.frozen\nclass ControlOp(TealOp, abc.ABC):\n @property\n @abc.abstractmethod\n def targets(self) -> Sequence[str]: ...\n\n\n@attrs.frozen\nclass RetSub(ControlOp):\n op_code: str = attrs.field(default=\"retsub\", init=False)\n produces: int = attrs.field(default=0, init=False)\n\n @property\n def targets(self) -> Sequence[str]:\n return ()\n\n\n@attrs.frozen\nclass Return(ControlOp):\n op_code: str = attrs.field(default=\"return\", init=False)\n consumes: int = attrs.field(default=1, init=False)\n produces: int = attrs.field(default=0, init=False)\n\n @property\n def targets(self) -> Sequence[str]:\n return ()\n\n\n@attrs.frozen\nclass Err(ControlOp):\n op_code: str = attrs.field(default=\"err\", init=False)\n consumes: int = attrs.field(default=0, init=False)\n produces: int = attrs.field(default=0, init=False)\n\n @property\n def targets(self) -> Sequence[str]:\n return ()\n\n\n@attrs.frozen\nclass Branch(ControlOp):\n target: str\n op_code: str = attrs.field(default=\"b\", init=False)\n consumes: int = attrs.field(default=0, init=False)\n produces: int = attrs.field(default=0, init=False)\n\n @property\n def immediates(self) -> Sequence[int | str]:\n return (self.target,)\n\n @property\n def targets(self) -> Sequence[str]:\n return (self.target,)\n\n\n@attrs.frozen\nclass BranchNonZero(ControlOp):\n target: str\n op_code: str = attrs.field(default=\"bnz\", init=False)\n consumes: int = attrs.field(default=1, init=False)\n produces: int = attrs.field(default=0, init=False)\n\n @property\n def immediates(self) -> Sequence[int | str]:\n return (self.target,)\n\n @property\n def targets(self) -> Sequence[str]:\n return (self.target,)\n\n\n@attrs.frozen\nclass BranchZero(ControlOp):\n target: str\n op_code: str = attrs.field(default=\"bz\", init=False)\n consumes: int = attrs.field(default=1, init=False)\n produces: int = attrs.field(default=0, init=False)\n\n @property\n def immediates(self) -> Sequence[int | str]:\n return (self.target,)\n\n @property\n def targets(self) -> Sequence[str]:\n return (self.target,)\n\n\n@attrs.frozen\nclass Switch(ControlOp):\n targets: Sequence[str] = attrs.field(converter=tuple[str, ...])\n op_code: str = attrs.field(default=\"switch\", init=False)\n consumes: int = attrs.field(default=1, init=False)\n produces: int = attrs.field(default=0, init=False)\n\n @property\n def immediates(self) -> Sequence[int | str]:\n return self.targets\n\n\n@attrs.frozen\nclass Match(ControlOp):\n targets: Sequence[str] = attrs.field(converter=tuple[str, ...])\n op_code: str = attrs.field(default=\"match\", init=False)\n consumes: int = attrs.field(init=False)\n produces: int = attrs.field(default=0, init=False)\n\n @consumes.default\n def _consumes(self) -> int:\n return len(self.targets) + 1\n\n @property\n def immediates(self) -> Sequence[int | str]:\n return self.targets\n\n\n@attrs.frozen\nclass CallSub(TealOp):\n target: str\n op_code: str = attrs.field(default=\"callsub\", init=False)\n\n @property\n def immediates(self) -> Sequence[int | str]:\n return (self.target,)\n\n\n@attrs.frozen\nclass TealBlock:\n label: str\n ops: list[TealOp]\n x_stack_in: Sequence[str]\n entry_stack_height: int = attrs.field(validator=attrs.validators.ge(0))\n exit_stack_height: int = attrs.field(validator=attrs.validators.ge(0))\n\n def validate_stack_height(self) -> None:\n stack_height = self.entry_stack_height\n for op in self.ops:\n stack_height -= op.consumes\n if stack_height < 0:\n raise InternalError(\"Access below stack height\", op.source_location)\n stack_height += op.produces\n expected_exit_height = self.exit_stack_height\n if stack_height != expected_exit_height and not (\n self.ops and self.ops[-1].op_code in (\"return\", \"retsub\", \"err\")\n ):\n raise InternalError(\n f\"Stack size at block {self.label} exit is {stack_height},\"\n f\" expected {expected_exit_height}\",\n self.ops[-1].source_location,\n )\n\n\n@attrs.frozen\nclass TealSubroutine:\n is_main: bool\n signature: mir.Signature\n blocks: list[TealBlock]\n source_location: SourceLocation | None\n\n\n@attrs.define\nclass TealProgram:\n avm_version: int\n main: TealSubroutine\n subroutines: list[TealSubroutine]\n\n @property\n def all_subroutines(self) -> Iterable[TealSubroutine]:\n yield self.main\n yield from self.subroutines\n\n\ndef _encoded_bytes(value: bytes, encoding: AVMBytesEncoding) -> str:\n # not all encodings can handle an empty bytes, so use base16 if bytes is empty\n if not value and encoding in (AVMBytesEncoding.base32, AVMBytesEncoding.base64):\n encoding = AVMBytesEncoding.base16\n bytes_str = format_bytes(value, encoding)\n if encoding in (\n AVMBytesEncoding.utf8,\n AVMBytesEncoding.base16,\n AVMBytesEncoding.unknown,\n ):\n return bytes_str\n hint = encoding.name\n return f\"{hint}({bytes_str})\"\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/teal\/models.py","language":"Python","license":"NOASSERTION","size":17843} {"code":"","repo_name":"algorandfoundation\/puya","path":"src\/puya\/teal\/optimize\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"LOAD_OP_CODES = frozenset(\n [\n \"addr\",\n \"arg\",\n *(f\"arg_{i}\" for i in range(4)),\n \"byte\",\n *(f\"bytec_{i}\" for i in range(4)), # valid as long as we don't push through a bytecblock\n \"gaid\",\n \"gload\",\n # global OpcodeBudget could be affected by shuffling,\n # but we don't guarantee ordering of stack manipulations\n \"global\",\n \"gtxn\",\n \"gtxna\",\n \"int\",\n *(f\"intc_{i}\" for i in range(4)), # valid as long as we don't push through an intcblock\n \"load\", # valid as long as we don't push through a store\/stores\n \"method\",\n \"pushbytes\",\n \"pushint\",\n \"txn\",\n \"txna\",\n # below are valid as long as we don't push through an itxn_submit\n \"gitxn\",\n \"gitxna\",\n \"itxn\",\n \"itxna\",\n ]\n)\nLOAD_OP_CODES_INCL_OFFSET = frozenset(\n [\n *LOAD_OP_CODES,\n \"dig\",\n \"frame_dig\",\n ]\n)\nSTORE_OPS_INCL_OFFSET = frozenset(\n [\n \"app_global_del\",\n # \"bury\", TODO: this one is very hard, and doesn't show up in any of our examples\n # \"assert\", TODO: enable this but only for O2 or higher\n \"frame_bury\",\n \"itxn_field\",\n \"pop\",\n \"store\",\n ]\n)\n\nCOMMUTATIVE_OPS = frozenset(\n [\n \"+\",\n \"*\",\n \"&\",\n \"&&\",\n \"|\",\n \"||\",\n \"^\",\n \"==\",\n \"!=\",\n \"b*\",\n \"b+\",\n \"b&\",\n \"b|\",\n \"b^\",\n \"b==\",\n \"b!=\",\n \"addw\",\n \"mulw\",\n ]\n)\n\nORDERING_OPS = frozenset([\"<\", \"<=\", \">\", \">=\", \"b<\", \"b<=\", \"b>\", \"b>=\"])\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/teal\/optimize\/_data.py","language":"Python","license":"NOASSERTION","size":1645} {"code":"import itertools\nimport typing\nfrom collections.abc import Sequence\n\nfrom puya.parse import sequential_source_locations_merge\nfrom puya.teal import models\n\n\ndef combine_pushes(program: models.TealProgram) -> None:\n for block in itertools.chain.from_iterable(sub.blocks for sub in program.all_subroutines):\n pushes = list[models.PushInt | models.PushBytes]()\n result = list[models.TealOp]()\n for op in block.ops:\n if _is_different_push_type(pushes, op):\n result.append(_combine_ops(pushes))\n pushes = []\n if isinstance(op, models.PushInt | models.PushBytes):\n pushes.append(op)\n else:\n result.append(op)\n if pushes:\n result.append(_combine_ops(pushes))\n block.ops[:] = result\n\n\ndef _is_different_push_type(\n consecutive: list[models.PushInt | models.PushBytes], next_op: models.TealOp\n) -> bool:\n return bool(consecutive) and type(consecutive[-1]) is not type(next_op)\n\n\ndef _combine_ops(consecutive: Sequence[models.PushInt | models.PushBytes]) -> models.TealOp:\n if len(consecutive) == 1:\n return consecutive[0]\n loc = sequential_source_locations_merge(op.source_location for op in consecutive)\n stack_manipulations = list(\n itertools.chain.from_iterable(op.stack_manipulations for op in consecutive)\n )\n if isinstance(consecutive[0], models.PushInt):\n consecutive = typing.cast(Sequence[models.PushInt], consecutive)\n return models.PushInts(\n values=[v.value for v in consecutive],\n stack_manipulations=stack_manipulations,\n source_location=loc,\n comment=_comment_ops(consecutive),\n )\n else:\n consecutive = typing.cast(Sequence[models.PushBytes], consecutive)\n return models.PushBytess(\n values=[(v.value, v.encoding) for v in consecutive],\n stack_manipulations=stack_manipulations,\n source_location=loc,\n comment=_comment_ops(consecutive),\n )\n\n\ndef _comment_ops(consecutive: Sequence[models.PushInt | models.PushBytes]) -> str:\n return \", \".join(\n map(str, ((v.comment or \" \".join(map(str, v.immediates))) for v in consecutive))\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/teal\/optimize\/combine_pushes.py","language":"Python","license":"NOASSERTION","size":2258} {"code":"import itertools\nimport typing\nfrom collections import Counter\n\nfrom puya.errors import CodeError, InternalError\nfrom puya.ir.types_ import AVMBytesEncoding\nfrom puya.parse import SourceLocation\nfrom puya.teal import models\nfrom puya.utils import Address, coalesce, method_selector_hash, unique\n\n_T = typing.TypeVar(\"_T\")\n\n\ndef gather_program_constants(program: models.TealProgram) -> None:\n # collect constants & template vars\n all_ints = list[int | str]()\n all_bytes = list[bytes | str]()\n bytes_encodings = dict[bytes | str, AVMBytesEncoding]()\n tmpl_locs = dict[bytes | int | str, SourceLocation | None]()\n\n # collect constants\n for block in itertools.chain.from_iterable(sub.blocks for sub in program.all_subroutines):\n for idx, op in enumerate(block.ops):\n # replace Method & Address constants with Byte before gathering\n match op:\n case models.Method(value=method_value):\n op = block.ops[idx] = models.Byte(\n value=method_selector_hash(method_value),\n encoding=AVMBytesEncoding.base16,\n comment=op.teal(),\n stack_manipulations=op.stack_manipulations,\n source_location=op.source_location,\n )\n case models.Address(value=address_value, source_location=loc):\n address = Address.parse(address_value)\n if not address.is_valid:\n raise InternalError(f\"Invalid address literal: {address_value}\", loc)\n op = block.ops[idx] = models.Byte(\n value=address.public_key,\n encoding=AVMBytesEncoding.base32,\n comment=op.teal(),\n stack_manipulations=op.stack_manipulations,\n source_location=op.source_location,\n )\n match op:\n case models.Int(value=int_or_alias):\n all_ints.append(_resolve_teal_alias(int_or_alias))\n case models.Byte(value=bytes_value) as byte:\n all_bytes.append(bytes_value)\n # preserve bytes encoding if it matches\n if bytes_encodings.setdefault(bytes_value, byte.encoding) != byte.encoding:\n bytes_encodings[bytes_value] = AVMBytesEncoding.base16\n # put template vars in constant blocks regardless of optimization level\n case models.TemplateVar(name=name, op_code=op_code):\n # capture first defined tmpl location\n tmpl_locs[name] = tmpl_locs.get(name) or op.source_location\n match op_code:\n case \"int\":\n all_ints.append(name)\n case \"byte\":\n all_bytes.append(name)\n bytes_encodings[name] = AVMBytesEncoding.base16\n case _:\n typing.assert_never(op_code)\n\n all_templates = unique(val for val in (*all_ints, *all_bytes) if isinstance(val, str))\n int_block = _sort_and_filter_constants(all_ints)\n byte_block = _sort_and_filter_constants(all_bytes)\n\n assert all(\n t in int_block or t in byte_block for t in all_templates\n ), \"expected all template variables to be in constant block\"\n # insert constant blocks\n entry_block = program.main.blocks[0]\n if byte_block:\n entry_block.ops.insert(\n 0,\n models.BytesBlock(\n constants={b: (bytes_encodings[b], tmpl_locs.get(b)) for b in byte_block},\n source_location=None,\n ),\n )\n if int_block:\n entry_block.ops.insert(\n 0,\n models.IntBlock(\n constants={i: tmpl_locs.get(i) for i in int_block}, source_location=None\n ),\n )\n\n # replace constants and template vars with constant load ops\n for block in itertools.chain.from_iterable(sub.blocks for sub in program.all_subroutines):\n for idx, op in enumerate(block.ops):\n match op:\n case models.Int(value=int_value):\n comment = coalesce(\n op.comment,\n int_value if isinstance(int_value, str) else None,\n str(int_value),\n )\n int_value = _resolve_teal_alias(int_value)\n try:\n const_index = int_block[int_value]\n except KeyError:\n block.ops[idx] = models.PushInt(\n value=int_value,\n stack_manipulations=op.stack_manipulations,\n source_location=op.source_location,\n comment=comment,\n )\n else:\n block.ops[idx] = models.IntC(\n index=const_index,\n stack_manipulations=op.stack_manipulations,\n source_location=op.source_location,\n comment=comment,\n )\n case models.Byte(value=bytes_value) as byte_op:\n try:\n const_index = byte_block[bytes_value]\n except KeyError:\n block.ops[idx] = models.PushBytes(\n value=bytes_value,\n encoding=byte_op.encoding,\n stack_manipulations=op.stack_manipulations,\n source_location=op.source_location,\n comment=op.comment,\n )\n else:\n block.ops[idx] = models.BytesC(\n index=const_index,\n stack_manipulations=op.stack_manipulations,\n source_location=op.source_location,\n comment=op.comment or \" \".join(map(str, op.immediates)),\n )\n case models.TemplateVar(name=name, op_code=op_code):\n match op_code:\n case \"int\":\n block.ops[idx] = models.IntC(\n index=int_block[name],\n stack_manipulations=op.stack_manipulations,\n source_location=op.source_location,\n comment=op.comment or name,\n )\n case \"byte\":\n block.ops[idx] = models.BytesC(\n index=byte_block[name],\n stack_manipulations=op.stack_manipulations,\n source_location=op.source_location,\n comment=op.comment or name,\n )\n case _:\n typing.assert_never(op_code)\n\n\ndef _sort_and_filter_constants(values: list[_T | str]) -> dict[_T | str, int]:\n value_frequencies = {\n value: freq\n for value, freq in Counter(values).most_common()\n if (freq > 1 or isinstance(value, str))\n }\n # filter constants based on their size * frequency when used as a constant vs inline\n freq_idx = 0\n ordered_values = list(value_frequencies)\n while freq_idx < len(ordered_values):\n value = ordered_values[freq_idx]\n if not isinstance(value, str):\n encoded_size = _encoded_size(value)\n const_usage_size = 1 if freq_idx < 4 else 2\n inline_usage_size = 1 + encoded_size\n freq = value_frequencies[value]\n # include constant block size in consideration if only one value\n block_size = 2 if len(ordered_values) == 1 else 0\n inline = inline_usage_size * freq\n const = const_usage_size * freq + encoded_size + block_size\n if inline <= const:\n ordered_values.pop(freq_idx)\n continue\n freq_idx += 1\n\n # ensure any template variables that sit beyond MAX_NUMBER_CONSTANTS are always included\n overflow_template_vars = [\n value for value in ordered_values[models.MAX_NUMBER_CONSTANTS :] if isinstance(value, str)\n ]\n if len(overflow_template_vars) > models.MAX_NUMBER_CONSTANTS:\n # this doesn't have to be an error as the only consequence of not having all template vars\n # in the constant block is that it breaks the debug mapping assumptions\n # however for now it is easier to just fail, as this many template variables is unlikely\n raise CodeError(f\"cannot exceed {models.MAX_NUMBER_CONSTANTS} template values\")\n constants = (\n *ordered_values[: models.MAX_NUMBER_CONSTANTS - len(overflow_template_vars)],\n *overflow_template_vars,\n )\n assert len(constants) <= models.MAX_NUMBER_CONSTANTS, \"constant block size exceeded\"\n return {value: index for index, value in enumerate(constants)}\n\n\ndef _encoded_size(value: object) -> int:\n # varuint encodes 7 bits per byte\n if isinstance(value, int):\n # max accounts for 0, which still requires at least 1 byte\n return max(1, (value.bit_length() + 6) \/\/ 7)\n elif isinstance(value, bytes):\n return _encoded_size(len(value)) + len(value)\n else:\n raise TypeError(f\"unencodable type: {value!r}\")\n\n\ndef _resolve_teal_alias(value: int | str) -> int:\n return models.TEAL_ALIASES[value] if isinstance(value, str) else value\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/teal\/optimize\/constant_block.py","language":"Python","license":"NOASSERTION","size":9764} {"code":"import attrs\n\nfrom puya.parse import sequential_source_locations_merge\nfrom puya.teal import models\nfrom puya.teal._util import preserve_stack_manipulations\nfrom puya.teal.optimize._data import LOAD_OP_CODES\n\n\ndef perform_constant_stack_shuffling(block: models.TealBlock) -> bool:\n result = block.ops.copy()\n loads = list[models.TealOp]()\n loads_modified = modified = False\n start_idx = idx = 0\n while idx < len(result):\n op = result[idx]\n if _is_constant_load(op):\n if not loads:\n start_idx = idx\n loads_modified = False\n loads.append(op)\n elif loads and op.op_code in (\"dup\", \"dupn\"):\n modified = loads_modified = True\n (n,) = op.immediates or (1,)\n assert isinstance(n, int)\n # extend loads with n copies of the last load\n loads.extend([attrs.evolve(loads[-1], source_location=op.source_location)] * n)\n elif loads:\n match op:\n case models.Uncover(n=n) if n < len(loads):\n modified = loads_modified = True\n uncovered = loads.pop(-(n + 1))\n loads.append(uncovered)\n case models.Cover(n=n) if n < len(loads):\n modified = loads_modified = True\n covered = loads.pop()\n loads.insert(len(loads) - n, covered)\n case _:\n if loads_modified:\n window = slice(start_idx, idx)\n preserve_stack_manipulations(result, window, loads)\n idx = start_idx + len(loads)\n loads = []\n idx += 1\n\n if loads_modified and loads:\n window = slice(start_idx, len(result))\n preserve_stack_manipulations(result, window, loads)\n block.ops[:] = result\n return modified\n\n\ndef constant_dupn_insertion(block: models.TealBlock) -> bool:\n result = list[models.TealOp]()\n loads = list[models.TealOp]()\n modified = False\n for op in block.ops:\n if loads and op == loads[0]:\n loads.append(op)\n else:\n if loads:\n modified = _collapse_loads(loads) or modified\n result.extend(loads)\n loads = []\n if _is_constant_load(op):\n loads.append(op)\n else:\n result.append(op)\n if loads:\n modified = _collapse_loads(loads) or modified\n result.extend(loads)\n block.ops[:] = result\n return modified\n\n\ndef constant_dup2_insertion(block: models.TealBlock) -> bool:\n result = block.ops\n modified = False\n idx = 0\n while (idx + 4) <= len(block.ops):\n load_a, load_b, load_a2, load_b2 = block.ops[idx : idx + 4]\n if (\n _is_constant_load(load_a)\n and _is_constant_load(load_b)\n and (load_a, load_b) == (load_a2, load_b2)\n ):\n loc = sequential_source_locations_merge(\n (load_a2.source_location, load_b2.source_location)\n )\n dup2 = models.Dup2(source_location=loc)\n preserve_stack_manipulations(result, slice(idx + 2, idx + 4), [dup2])\n modified = True\n idx += 3\n else:\n idx += 1\n block.ops[:] = result\n return modified\n\n\ndef _collapse_loads(loads: list[models.TealOp]) -> bool:\n n = len(loads) - 1\n if n < 1:\n return False\n\n dup_source_location = sequential_source_locations_merge(op.source_location for op in loads[1:])\n if n == 1:\n dup_op: models.TealOp = models.Dup(source_location=dup_source_location)\n else:\n dup_op = models.DupN(n=n, source_location=dup_source_location)\n\n preserve_stack_manipulations(loads, slice(1, None), [dup_op])\n return True\n\n\ndef _is_constant_load(op: models.TealOp) -> bool:\n return op.op_code in LOAD_OP_CODES or (isinstance(op, models.FrameDig) and op.n < 0)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/teal\/optimize\/constant_stack_shuffling.py","language":"Python","license":"NOASSERTION","size":3968} {"code":"import itertools\nfrom collections import defaultdict\n\nimport attrs\n\nfrom puya import log\nfrom puya.context import CompileContext\nfrom puya.teal import models\nfrom puya.teal._util import preserve_stack_manipulations\nfrom puya.teal.optimize.combine_pushes import combine_pushes\nfrom puya.teal.optimize.constant_block import gather_program_constants\nfrom puya.teal.optimize.constant_stack_shuffling import (\n constant_dup2_insertion,\n constant_dupn_insertion,\n perform_constant_stack_shuffling,\n)\nfrom puya.teal.optimize.peephole import peephole\nfrom puya.teal.optimize.repeated_rotations import simplify_repeated_rotation_ops, simplify_swap_ops\nfrom puya.teal.optimize.repeated_rotations_search import repeated_rotation_ops_search\n\nlogger = log.get_logger(__name__)\n\n\ndef optimize_teal_program(context: CompileContext, teal_program: models.TealProgram) -> None:\n for teal_sub in teal_program.all_subroutines:\n _optimize_subroutine(context, teal_sub)\n before = [_get_all_stack_manipulations(sub) for sub in teal_program.subroutines]\n gather_program_constants(teal_program)\n if context.options.optimization_level > 0:\n combine_pushes(teal_program)\n after = [_get_all_stack_manipulations(sub) for sub in teal_program.subroutines]\n assert before == after, \"expected stack manipulations to be preserved after optimization\"\n\n\ndef _get_all_stack_manipulations(sub: models.TealSubroutine) -> list[models.StackManipulation]:\n return [sm for block in sub.blocks for op in block.ops for sm in op.stack_manipulations]\n\n\ndef _optimize_subroutine(context: CompileContext, teal_sub: models.TealSubroutine) -> None:\n logger.debug(\n f\"optimizing TEAL subroutine {teal_sub.signature}\", location=teal_sub.source_location\n )\n before = _get_all_stack_manipulations(teal_sub)\n for teal_block in teal_sub.blocks:\n _optimize_block(teal_block, level=context.options.optimization_level)\n teal_block.validate_stack_height()\n after = _get_all_stack_manipulations(teal_sub)\n assert before == after, \"expected stack manipulations to be preserved after optimization\"\n if context.options.optimization_level > 0:\n # at this point, blocks should still be almost \"basic\"\n # - control flow should only enter at the start of a block.\n # - control flow should only leave at the end of the block (although this might be\n # spread over multiple ops in the case of say a switch or match)\n # - the final op must be an unconditional control flow op (e.g. retusb, b, return, err)\n _inline_jump_chains(teal_sub)\n # now all blocks that are just a b should have been inlined\/removed.\n # any single-op blocks left must be non-branching control ops, ie ops\n # that terminate either exit the program or the subroutine.\n # inlining these are only possible when they are unconditionally branched to,\n # thus this still maintains the \"almost basic\" structure as outlined above.\n _inline_single_op_blocks(teal_sub)\n _inline_singly_referenced_blocks(teal_sub)\n _remove_jump_fallthroughs(teal_sub)\n\n\ndef _optimize_block(block: models.TealBlock, *, level: int) -> None:\n modified = True\n while modified:\n modified = False\n if level > 0:\n modified = perform_constant_stack_shuffling(block) or modified\n modified = simplify_repeated_rotation_ops(block) or modified\n modified = peephole(block, level) or modified\n\n # we don't do dup\/dupn collapse in the above loop, but after it.\n # it's easier to deal with expanded dup\/dupn instructions above when looking at\n # stack shuffling etc, but once it's done we save ops \/ program size by collapsing them\n constant_dupn_insertion(block)\n constant_dup2_insertion(block)\n if level >= 2:\n # this is a brute-force search which can be slow at times,\n # so it's only done once and only at higher optimisation levels\n block.ops[:] = repeated_rotation_ops_search(block.ops)\n\n # simplifying uncover\/cover 1 to swap is easier to do after other rotation optimizations\n simplify_swap_ops(block)\n\n\ndef _inline_jump_chains(teal_sub: models.TealSubroutine) -> None:\n # build a map of any blocks that are just an unconditional branch to their targets\n jumps = dict[str, str]()\n for block_idx, block in enumerate(teal_sub.blocks.copy()):\n match block.ops:\n case [models.Branch(target=target_label) as b]:\n if b.stack_manipulations:\n logger.debug(\n \"not inlining jump-block due to stack manipulations\",\n location=b.source_location,\n )\n else:\n jumps[block.label] = target_label\n logger.debug(f\"removing jump-chain block {block.label}\")\n teal_sub.blocks.pop(block_idx)\n # now back-propagate any chains\n replacements = dict[str, str]()\n for src, target in jumps.items():\n while True:\n try:\n target = jumps[target]\n except KeyError:\n break\n replacements[src] = target\n logger.debug(f\"branching to {src} will be replaced with {target}\")\n for block in teal_sub.blocks:\n for op_idx, op in enumerate(block.ops):\n if isinstance(op, models.Branch | models.BranchNonZero | models.BranchZero):\n if op.target in replacements:\n block.ops[op_idx] = attrs.evolve(op, target=replacements[op.target])\n elif isinstance(op, models.Switch | models.Match):\n block.ops[op_idx] = attrs.evolve(\n op, targets=[replacements.get(t, t) for t in op.targets]\n )\n\n\ndef _inline_single_op_blocks(teal_sub: models.TealSubroutine) -> None:\n # TODO: this should only encounter exiting ops, so we don't need a traversal to find unused,\n # just keep track of predecessors??\n single_op_blocks = {b.label: b.ops for b in teal_sub.blocks if len(b.ops) == 1}\n modified = False\n for teal_block, next_block in itertools.zip_longest(teal_sub.blocks, teal_sub.blocks[1:]):\n match teal_block.ops[-1]:\n case models.Branch(target=target_label) as branch_op if (\n (replace_ops := single_op_blocks.get(target_label))\n and (next_block is None or target_label != next_block.label)\n ):\n modified = True\n (replace_op,) = replace_ops\n # we shouldn't encounter any branching ops, since any block that\n # is just an unconditional branch has already been inlined, and\n # at this point blocks should still have an unconditional exit as the final op,\n # which rules out bz\/bnz\/match\/switch, leaving only exiting ops\n # like retsub, return, or err.\n # this also means we can keep track of which blocks to eliminate without having\n # to do a traversal, thus the assertion\n assert isinstance(replace_op, models.ControlOp) and not replace_op.targets\n logger.debug(\n f\"replacing `{branch_op.teal()}` with `{replace_op.teal()}`\",\n location=branch_op.source_location,\n )\n preserve_stack_manipulations(teal_block.ops, slice(-1, None), replace_ops)\n if modified:\n # if any were inlined, they may no longer be referenced and thus removable\n _remove_unreachable_blocks(teal_sub)\n\n\ndef _remove_unreachable_blocks(teal_sub: models.TealSubroutine) -> None:\n entry = teal_sub.blocks[0]\n to_visit = [entry]\n unreachable_blocks_by_label = {b.label: b for b in teal_sub.blocks[1:]}\n while to_visit:\n current_block = to_visit.pop()\n for op in current_block.ops:\n if isinstance(op, models.ControlOp):\n to_visit.extend(\n target\n for target_label in op.targets\n if (target := unreachable_blocks_by_label.pop(target_label, None))\n )\n if unreachable_blocks_by_label:\n logger.debug(f\"removing unreachable blocks: {list(map(str, unreachable_blocks_by_label))}\")\n teal_sub.blocks[:] = [\n b for b in teal_sub.blocks if b.label not in unreachable_blocks_by_label\n ]\n\n\ndef _inline_singly_referenced_blocks(teal_sub: models.TealSubroutine) -> None:\n predecessors = defaultdict[str, list[str]](list)\n predecessors[teal_sub.blocks[0].label].append(\"\")\n for block in teal_sub.blocks:\n for op in block.ops:\n if isinstance(op, models.ControlOp):\n for target_label in op.targets:\n predecessors[target_label].append(block.label)\n\n pairs = dict[str, str]()\n inlineable = set[str]()\n for block in teal_sub.blocks:\n match block.ops[-1]:\n case models.Branch(target=target_label):\n target_predecessors = predecessors[target_label]\n if len(target_predecessors) == 1:\n assert target_predecessors == [block.label]\n pairs[block.label] = target_label\n inlineable.add(target_label)\n\n blocks_by_label = {b.label: b for b in teal_sub.blocks}\n result = list[models.TealBlock]()\n for block in teal_sub.blocks:\n this_label = block.label\n if this_label not in inlineable:\n result.append(block)\n while (next_label := pairs.get(this_label)) is not None:\n logger.debug(f\"inlining single reference block {next_label} into {block.label}\")\n next_block = blocks_by_label[next_label]\n preserve_stack_manipulations(block.ops, slice(-1, None), next_block.ops)\n this_label = next_label\n teal_sub.blocks[:] = result\n\n\ndef _remove_jump_fallthroughs(teal_sub: models.TealSubroutine) -> None:\n for block, next_block in zip(teal_sub.blocks, teal_sub.blocks[1:], strict=False):\n match block.ops[-1]:\n # we guard against having stack manipulations but only one op, thus nowhere to put\n # them, but this should only occur in O0 as in higher levels, blocks with just a b\n # will already be inlined\n case models.Branch(\n target=target_label, stack_manipulations=sm\n ) if target_label == next_block.label and (len(block.ops) > 1 or not sm):\n logger.debug(f\"removing explicit jump to fall-through block {next_block.label}\")\n block.ops.pop()\n if block.ops: # guard is only for O0 case\n block.ops[-1] = attrs.evolve(\n block.ops[-1],\n stack_manipulations=(*block.ops[-1].stack_manipulations, *sm),\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/teal\/optimize\/main.py","language":"Python","license":"NOASSERTION","size":10888} {"code":"import attrs\n\nfrom puya.teal import models\nfrom puya.teal._util import preserve_stack_manipulations\nfrom puya.teal.optimize._data import (\n COMMUTATIVE_OPS,\n LOAD_OP_CODES,\n LOAD_OP_CODES_INCL_OFFSET,\n ORDERING_OPS,\n STORE_OPS_INCL_OFFSET,\n)\nfrom puya.utils import invert_ordered_binary_op\n\n\ndef peephole(block: models.TealBlock, opt_level: int) -> bool:\n start_idx = 0\n stack_height = block.entry_stack_height\n any_modified = False\n result = block.ops.copy()\n while start_idx < len(result):\n modified = False\n window: slice | None = None\n if opt_level > 0 and not modified and start_idx < len(result) - 3:\n window = slice(start_idx, start_idx + 4)\n new_values, modified = _optimize_quadruplet(*result[window])\n if opt_level > 0 and not modified and start_idx < len(result) - 2:\n window = slice(start_idx, start_idx + 3)\n new_values, modified = _optimize_triplet(*result[window], stack_height=stack_height)\n if not modified and start_idx < len(result) - 1:\n window = slice(start_idx, start_idx + 2)\n new_values, modified = _optimize_pair(*result[window])\n if not modified:\n window = slice(start_idx, start_idx + 1)\n new_values, modified = optimize_single(*result[window])\n if modified:\n assert window is not None\n any_modified = True\n preserve_stack_manipulations(result, window, new_values)\n else:\n stack_height += result[start_idx].stack_height_delta\n start_idx += 1 # go to next\n block.ops[:] = result\n return any_modified\n\n\ndef is_redundant_rotate(a: models.TealOp, b: models.TealOp) -> bool:\n match a, b:\n case models.Cover(n=a_n), models.Uncover(n=b_n) if a_n == b_n:\n return True\n case models.Uncover(n=a_n), models.Cover(n=b_n) if a_n == b_n:\n return True\n\n return is_stack_swap(a) and is_stack_swap(b)\n\n\ndef is_stack_swap(op: models.TealOp) -> bool:\n return op.op_code == \"swap\" or (op.op_code in (\"cover\", \"uncover\") and op.immediates[0] == 1)\n\n\ndef optimize_single(a: models.TealOp) -> tuple[list[models.TealOp], bool]:\n if a.op_code in (\"cover\", \"uncover\") and a.immediates == (0,):\n return [], True\n if a.op_code == \"dig\" and a.immediates == (0,):\n return [\n models.Dup(\n source_location=a.source_location,\n stack_manipulations=a.stack_manipulations,\n )\n ], True\n if a.op_code == \"popn\" and a.immediates == (1,):\n return [\n models.Pop(\n source_location=a.source_location,\n stack_manipulations=a.stack_manipulations,\n )\n ], True\n return [a], False\n\n\ndef _optimize_pair(a: models.TealOp, b: models.TealOp) -> tuple[list[models.TealOp], bool]:\n if is_redundant_rotate(a, b):\n return [], True\n\n if is_stack_swap(a):\n # `swap; pop` -> `bury 1`\n if b.op_code == \"pop\":\n return [models.Bury(n=1, source_location=b.source_location)], True\n if b.op_code in COMMUTATIVE_OPS:\n return [b], True\n if b.op_code in ORDERING_OPS:\n inverse_ordering_op = invert_ordered_binary_op(b.op_code)\n return [attrs.evolve(b, op_code=inverse_ordering_op)], True\n\n match a, b:\n # `frame_dig n; frame_bury n` is redundant\n case models.FrameDig(n=dig_n), models.FrameBury(n=bury_n) if dig_n == bury_n:\n return [], True\n # `frame_bury n; frame_dig n` can be simplified to dup; frame_bury n\n case models.FrameBury(n=dig_n), models.FrameDig(n=bury_n) if dig_n == bury_n:\n return [models.Dup(source_location=None), a], True\n # `dup; swap` -> `dup`\n case models.TealOp(op_code=\"dup\" | \"dupn\"), maybe_swap if is_stack_swap(maybe_swap):\n return [a], True\n # combine consecutive dup\/dupn's\n case models.TealOp(op_code=\"dup\" | \"dupn\"), models.TealOp(op_code=\"dup\" | \"dupn\"):\n (n1,) = a.immediates or (1,)\n assert isinstance(n1, int)\n (n2,) = b.immediates or (1,)\n assert isinstance(n2, int)\n return [models.DupN(n=n1 + n2, source_location=a.source_location)], True\n # combine consecutive pop\/popn's\n case models.TealOp(op_code=\"pop\" | \"popn\"), models.TealOp(op_code=\"pop\" | \"popn\"):\n (n1,) = a.immediates or (1,)\n assert isinstance(n1, int)\n (n2,) = b.immediates or (1,)\n assert isinstance(n2, int)\n return [models.PopN(n=n1 + n2, source_location=a.source_location)], True\n # `dig 1; dig 1` -> `dup2`\n case models.TealOpUInt8(op_code=\"dig\", n=1), models.TealOpUInt8(op_code=\"dig\", n=1):\n return [models.Dup2(source_location=a.source_location or b.source_location)], True\n return [a, b], False\n\n\ndef _optimize_triplet(\n a: models.TealOp, b: models.TealOp, c: models.TealOp, *, stack_height: int\n) -> tuple[list[models.TealOp], bool]:\n if _frame_digs_overlap_with_ops(stack_height, a, b, c):\n return [a, b, c], False\n\n # `'cover 3; cover 3; swap` -> `uncover 2; uncover 3`\n if (\n is_stack_swap(c)\n and (a.op_code == \"cover\" and a.immediates[0] == 3)\n and (b.op_code == \"cover\" and b.immediates[0] == 3)\n ):\n return [\n models.Uncover(n=2, source_location=a.source_location),\n models.Uncover(n=3, source_location=b.source_location),\n ], True\n\n # `swap; (consumes=0, produces=1); uncover 2` -> `(consume=0, produces=1); swap`\n if (\n is_stack_swap(a)\n and (c.op_code == \"uncover\" and c.immediates[0] == 2)\n and (\n b.op_code in LOAD_OP_CODES_INCL_OFFSET\n # only count digs if they go below the swap\n and (b.op_code != \"dig\" or int(b.immediates[0]) >= 2)\n )\n ):\n return [b, a], True\n\n # ; ; swap -> ; \n if (\n is_stack_swap(c)\n and a.op_code in LOAD_OP_CODES_INCL_OFFSET\n and b.op_code in LOAD_OP_CODES_INCL_OFFSET\n # cant swap dig 0, which will become a dup anyway\n and (not isinstance(b, models.Dig) or b.n)\n ):\n if isinstance(a, models.Dig):\n a = attrs.evolve(a, n=a.n + 1)\n if isinstance(b, models.Dig):\n new_n = b.n - 1\n if new_n == 0:\n b = models.Dup(source_location=b.source_location)\n else:\n b = attrs.evolve(b, n=new_n)\n return [b, a], True\n\n # swap; ; -> ; \n if (\n is_stack_swap(a)\n and b.op_code in STORE_OPS_INCL_OFFSET\n and c.op_code in STORE_OPS_INCL_OFFSET\n ):\n height_below_swap = stack_height - 2\n if not (\n (b.op_code == \"frame_bury\" and int(b.immediates[0]) >= height_below_swap)\n or (c.op_code == \"frame_bury\" and int(c.immediates[0]) >= height_below_swap)\n or (\n # can't swap ops if store order is important\n # e.g. itxn_field ApplicationArgs or frame_bury -1\n b.op_code in (\"frame_bury\", \"itxn_field\")\n and b.op_code == c.op_code\n and b.immediates == c.immediates\n )\n ):\n return [c, b], True\n\n match a, b, c:\n # `uncover 2; swap; uncover 2` is equivalent to `swap`\n case models.Uncover(n=2), maybe_swap, models.Uncover(n=2) if is_stack_swap(maybe_swap):\n return [maybe_swap], True\n # `dup; cover 2; swap` can be replaced by `dup; uncover 2`\n case models.Dup(), models.Cover(n=2), maybe_swap if is_stack_swap(maybe_swap):\n return [\n a,\n models.Uncover(n=2, source_location=b.source_location or c.source_location),\n ], True\n\n # `uncover n; dup; cover n+1` can be replaced with `dig n`\n # this occurs when the x-stack becomes the l-stack\n if (\n a.op_code == \"uncover\"\n and b.op_code == \"dup\"\n and c.op_code == \"cover\"\n and isinstance((n := a.immediates[0]), int)\n and (n + 1) == c.immediates[0]\n ):\n return [\n models.Dig(\n n=n, source_location=a.source_location or b.source_location or c.source_location\n )\n ], True\n return [a, b, c], False\n\n\ndef _frame_digs_overlap_with_ops(stack_height: int, *ops: models.TealOp) -> bool:\n \"\"\"\n Check to see if there is a frame_dig in the sequence that could be impacted\n if ops were re-ordered\/eliminated\/otherwise optimized.\n \"\"\"\n curr_height = min_stack_height = stack_height\n for op in ops:\n if op.op_code == \"frame_dig\":\n n = op.immediates[0]\n assert isinstance(n, int)\n if n >= min_stack_height:\n return True\n curr_height -= op.consumes\n min_stack_height = min(curr_height, min_stack_height)\n curr_height += op.produces\n return False\n\n\ndef _optimize_quadruplet(\n a: models.TealOp, b: models.TealOp, c: models.TealOp, d: models.TealOp\n) -> tuple[list[models.TealOp], bool]:\n # `swap; ; swap; uncover 2` -> `dig|uncover n; cover 2`\n if (\n is_stack_swap(a)\n and (\n b.op_code in LOAD_OP_CODES\n or (b.op_code in (\"dig\", \"uncover\") and int(b.immediates[0]) >= 2)\n or (b.op_code == \"frame_dig\" and int(b.immediates[0]) < 0)\n )\n and is_stack_swap(c)\n and (d.op_code == \"uncover\" and d.immediates[0] == 2)\n ):\n return [b, models.Cover(n=2, source_location=d.source_location)], True\n return [a, b, c, d], False\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/teal\/optimize\/peephole.py","language":"Python","license":"NOASSERTION","size":9736} {"code":"from collections.abc import Sequence\n\nfrom puya.teal import models\nfrom puya.teal._util import preserve_stack_manipulations\n\n\ndef _simplify_repeated_rotation_ops(\n maybe_simplify: list[models.Cover | models.Uncover],\n) -> tuple[Sequence[models.Cover | models.Uncover], bool]:\n first = maybe_simplify[0]\n is_cover = isinstance(first, models.Cover)\n n = first.n\n number_of_ops = len(maybe_simplify)\n number_of_inverse = n + 1 - number_of_ops\n while number_of_inverse < 0:\n number_of_inverse += n + 1\n if number_of_inverse >= number_of_ops:\n return maybe_simplify, False\n inverse_op: models.Cover | models.Uncover = (\n models.Uncover(n=n, source_location=first.source_location)\n if is_cover\n else models.Cover(n=n, source_location=first.source_location)\n )\n simplified = [inverse_op] * number_of_inverse\n return simplified, True\n\n\ndef simplify_repeated_rotation_ops(block: models.TealBlock) -> bool:\n result = block.ops.copy()\n maybe_simplify = list[models.Cover | models.Uncover]()\n modified = False\n end_idx = 0\n while end_idx < len(result):\n op = result[end_idx]\n if isinstance(op, models.Cover | models.Uncover) and (\n not maybe_simplify or op == maybe_simplify[0]\n ):\n maybe_simplify.append(op)\n else:\n if maybe_simplify:\n maybe_simplified, modified_ = _simplify_repeated_rotation_ops(maybe_simplify)\n modified = modified or modified_\n preserve_stack_manipulations(\n result, slice(end_idx - len(maybe_simplify), end_idx), maybe_simplified\n )\n end_idx += len(maybe_simplified) - len(maybe_simplify)\n maybe_simplify = []\n if isinstance(op, models.Cover | models.Uncover):\n maybe_simplify.append(op)\n end_idx += 1\n if maybe_simplify:\n maybe_simplified, modified_ = _simplify_repeated_rotation_ops(maybe_simplify)\n modified = modified or modified_\n idx = len(result)\n preserve_stack_manipulations(\n result, slice(idx - len(maybe_simplify), idx), maybe_simplified\n )\n block.ops[:] = result\n return modified\n\n\ndef simplify_swap_ops(block: models.TealBlock) -> bool:\n result = list[models.TealOp]()\n modified = False\n for op in block.ops:\n if isinstance(op, models.Cover | models.Uncover) and (op.n == 1):\n modified = True\n result.append(\n models.Swap(\n source_location=op.source_location, stack_manipulations=op.stack_manipulations\n )\n )\n else:\n result.append(op)\n block.ops[:] = result\n return modified\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/teal\/optimize\/repeated_rotations.py","language":"Python","license":"NOASSERTION","size":2766} {"code":"import functools\nimport itertools\nimport typing\nfrom collections.abc import Sequence\n\nimport attrs\n\nfrom puya import log\nfrom puya.teal import models\nfrom puya.teal._util import preserve_stack_manipulations\n\nTealOpSequence = tuple[models.TealOpUInt8, ...]\nlogger = log.get_logger(__name__)\n\n\nclass InvalidOpSequenceError(Exception):\n pass\n\n\n@attrs.define\nclass TealStack:\n stack: list[int]\n\n @classmethod\n def from_stack_size(cls, stack_size: int) -> \"TealStack\":\n return cls(stack=list(range(stack_size)))\n\n def apply(self, ops: Sequence[models.TealOpUInt8]) -> \"TealStack\":\n stack = TealStack(self.stack.copy())\n for op in ops:\n n = op.n\n if n:\n index = len(stack.stack) - n - 1\n if index < 0 or index >= len(stack.stack):\n raise InvalidOpSequenceError\n match op.op_code:\n case \"cover\":\n stack.stack.insert(index, stack.stack.pop())\n case \"uncover\":\n stack.stack.append(stack.stack.pop(index))\n case _:\n raise InvalidOpSequenceError\n return stack\n\n\n@functools.cache\ndef simplify_rotation_ops(original_ops: TealOpSequence) -> TealOpSequence | None:\n num_rot_ops = len(original_ops)\n max_rot_op_n = 0\n for o in original_ops:\n max_rot_op_n = max(max_rot_op_n, o.n)\n\n original_stack = TealStack.from_stack_size(max_rot_op_n + 1)\n\n expected = original_stack.apply(original_ops)\n # entire sequence can be removed!\n if expected == original_stack:\n return ()\n\n possible_rotation_ops = get_possible_rotation_ops(max_rot_op_n)\n original_stack_result = original_stack.apply(original_ops)\n\n # TODO: use a non-bruteforce approach and\/or capture common simplifications as data\n for num_rotation_ops in range(num_rot_ops):\n for maybe_ops in itertools.permutations(possible_rotation_ops, num_rotation_ops):\n try:\n stack = original_stack.apply(maybe_ops)\n except InvalidOpSequenceError:\n continue\n if expected == stack:\n assert original_stack_result == original_stack.apply(maybe_ops)\n return tuple(attrs.evolve(op, source_location=None) for op in maybe_ops)\n return None\n\n\n@functools.cache\ndef get_possible_rotation_ops(n: int) -> TealOpSequence:\n possible_ops = list[models.TealOpUInt8]()\n for i in range(1, n + 1):\n possible_ops.append(models.Cover(i, source_location=None))\n possible_ops.append(models.Uncover(i, source_location=None))\n return tuple(possible_ops)\n\n\nROTATION_SIMPLIFY_OPS = frozenset(\n [\n \"cover\",\n \"uncover\",\n ]\n)\n\n\ndef repeated_rotation_ops_search(teal_ops: list[models.TealOp]) -> list[models.TealOp]:\n maybe_remove_rotations = list[models.TealOpUInt8]()\n result = list[models.TealOp]()\n for teal_op in teal_ops:\n if teal_op.op_code in ROTATION_SIMPLIFY_OPS:\n maybe_remove_rotations.append(typing.cast(models.TealOpUInt8, teal_op))\n else:\n maybe_simplified = _maybe_simplified(maybe_remove_rotations)\n maybe_remove_rotations = []\n result.extend(maybe_simplified)\n result.append(teal_op)\n result.extend(_maybe_simplified(maybe_remove_rotations))\n return result\n\n\ndef _maybe_simplified(\n maybe_remove_rotations: list[models.TealOpUInt8], window_size: int = 5\n) -> Sequence[models.TealOpUInt8]:\n if len(maybe_remove_rotations) < 2:\n return maybe_remove_rotations\n\n for start_idx in range(len(maybe_remove_rotations) - 1):\n window_slice = slice(start_idx, start_idx + window_size + 1)\n window = maybe_remove_rotations[window_slice]\n simplified = simplify_rotation_ops(tuple(window))\n if simplified is not None:\n logger.debug(\n f\"Replaced '{'; '.join(map(str, maybe_remove_rotations))}'\"\n f\" with '{'; '.join(map(str, simplified))}',\"\n f\" reducing by {len(maybe_remove_rotations) - len(simplified)} ops by search\"\n )\n result_ = maybe_remove_rotations.copy()\n preserve_stack_manipulations(result_, window_slice, simplified)\n assert result_ != maybe_remove_rotations\n return result_\n return maybe_remove_rotations\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/teal\/optimize\/repeated_rotations_search.py","language":"Python","license":"NOASSERTION","size":4405} {"code":"import textwrap\n\nimport attrs\n\nfrom puya.context import ArtifactCompileContext\nfrom puya.teal import models\n\n\ndef emit_teal(context: ArtifactCompileContext, program: models.TealProgram) -> str:\n indent = \" \" * 4\n\n result = [\n f\"#pragma version {program.avm_version}\",\n \"#pragma typetrack false\",\n \"\",\n ]\n for idx, subroutine in enumerate(program.all_subroutines):\n if idx > 0:\n result.append(\"\")\n result.append(f\"\/\/ {subroutine.signature}\")\n\n for block in subroutine.blocks:\n last_location = None\n result.append(f\"{block.label}:\")\n for teal_op in block.ops:\n if context.options.debug_level and (op_loc := teal_op.source_location):\n whole_lines_location = attrs.evolve(\n op_loc.with_comments(), column=None, end_column=None\n )\n if whole_lines_location != last_location:\n last_location = whole_lines_location\n src = context.try_get_source(whole_lines_location)\n if src is not None:\n result.append(f\"{indent}\/\/ {whole_lines_location}\")\n lines = textwrap.dedent(\"\\n\".join(src)).splitlines()\n result.extend(f\"{indent}\/\/ {line.rstrip()}\" for line in lines)\n\n result.append(f\"{indent}{teal_op.teal()}\")\n result.append(\"\")\n return \"\\n\".join(result)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/teal\/output.py","language":"Python","license":"NOASSERTION","size":1513} {"code":"","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ussemble\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"import struct\nimport typing\nfrom collections import defaultdict\nfrom collections.abc import Callable, Iterable, Mapping, Sequence\n\nfrom puya import log\nfrom puya.compilation_artifacts import DebugEvent\nfrom puya.errors import InternalError\nfrom puya.parse import SourceLocation\nfrom puya.teal import models as teal\nfrom puya.ussemble import models\nfrom puya.ussemble.context import AssembleContext\nfrom puya.ussemble.debug import build_debug_info\nfrom puya.ussemble.op_spec import OP_SPECS\nfrom puya.ussemble.op_spec_models import ImmediateEnum, ImmediateKind\n\nlogger = log.get_logger(__name__)\n_BRANCHING_OPS = {\n op.name\n for op in OP_SPECS.values()\n if any(i in (ImmediateKind.label, ImmediateKind.label_array) for i in op.immediates)\n}\n\n\ndef assemble_bytecode_and_debug_info(\n ctx: AssembleContext, program: teal.TealProgram\n) -> models.AssembledProgram:\n function_block_ids = {s.blocks[0].label: s.signature.name for s in program.all_subroutines}\n\n version_bytes = _encode_varuint(program.avm_version)\n pc_events = defaultdict[int, DebugEvent](lambda: DebugEvent())\n pc_ops = dict[int, models.AVMOp]()\n label_pcs = dict[str, int]()\n\n # pc includes version header\n pc = len(version_bytes)\n # first pass lowers teal ops, calculate pcs, and captures debug info\n for subroutine in program.all_subroutines:\n current_event = pc_events[pc]\n current_event[\"subroutine\"] = subroutine.signature.name\n current_event[\"params\"] = {\n p.local_id: p.atype.name or \"\" for p in subroutine.signature.parameters\n }\n stack = list[str]()\n for block in subroutine.blocks:\n current_event = pc_events[pc]\n # update stack with correct values on entry to a block\n f_stack_height = block.entry_stack_height - len(block.x_stack_in)\n stack[f_stack_height:] = block.x_stack_in\n label_pcs[block.label] = pc\n current_event[\"block\"] = block.label\n current_event[\"stack_in\"] = stack.copy()\n defined = set[str]()\n\n for op in block.ops:\n current_event = pc_events[pc]\n avm_op = _lower_op(ctx, op)\n # actual label offsets can't be determined until all PC values are known\n # so just use a placeholder value initially\n op_size = len(_encode_op(avm_op, get_label_offset=lambda _: 0))\n assert op_size, \"expected non empty bytecode\"\n _add_op_debug_events(\n current_event,\n function_block_ids,\n op,\n # note: stack & defined are mutated\n stack,\n defined,\n )\n pc_ops[pc] = avm_op\n pc += op_size\n\n # all pc values, including pc after final op\n pcs = [*pc_ops, pc]\n # second pass assembles final byte code\n bytecode = [version_bytes]\n for op_index, avm_op in enumerate(pc_ops.values()):\n\n def get_label_offset(label: models.Label) -> int:\n # label offset is the signed PC difference\n # between the label PC location and the end of the current op\n return label_pcs[label.name] - pcs[op_index + 1] # noqa: B023\n\n bytecode.append(_encode_op(avm_op, get_label_offset=get_label_offset))\n\n return models.AssembledProgram(\n bytecode=b\"\".join(bytecode),\n debug_info=build_debug_info(ctx, pc_ops, pc_events),\n template_variables={\n var: ctx.provided_template_variables.get(var, (None, None))[0]\n for var in ctx.template_variable_types\n },\n )\n\n\ndef _add_op_debug_events(\n event: DebugEvent,\n subroutine_ids: Mapping[str, str],\n op: teal.TealOp,\n stack: list[str],\n defined: set[str],\n) -> None:\n stack_in = stack.copy()\n num_defined = len(defined)\n if op.op_code == \"callsub\":\n (func_block,) = op.immediates\n assert isinstance(func_block, str), \"expected label\"\n event[\"callsub\"] = subroutine_ids[func_block]\n elif op.op_code == \"retsub\":\n event[\"retsub\"] = True\n if op.error_message:\n event[\"error\"] = op.error_message\n event[\"op\"] = op.teal()\n\n for sm in op.stack_manipulations:\n match sm:\n case teal.StackConsume(n=n):\n for _ in range(n):\n stack.pop()\n case teal.StackExtend() as se:\n stack.extend(se.local_ids)\n case teal.StackDefine() as sd:\n defined.update(sd.local_ids)\n case teal.StackInsert() as si:\n index = len(stack) - si.depth\n stack.insert(index, si.local_id)\n case teal.StackPop() as sp:\n index = len(stack) - sp.depth - 1\n stack.pop(index)\n case _:\n typing.assert_never(sm)\n\n if len(defined) != num_defined:\n event[\"defined_out\"] = sorted(set(defined) & set(stack))\n if stack_in != stack:\n event[\"stack_out\"] = stack.copy()\n\n\ndef _lower_op(ctx: AssembleContext, op: teal.TealOp) -> models.AVMOp:\n loc = op.source_location\n match op:\n case teal.TemplateVar() | teal.Int() | teal.Byte():\n raise InternalError(f\"{op} should have been eliminated during TEAL phase\", loc)\n case teal.IntBlock(constants=constants):\n return models.AVMOp(\n op_code=op.op_code,\n immediates=[_resolve_template_vars(ctx, int, constants.items())],\n source_location=loc,\n )\n case teal.BytesBlock(constants=constants):\n return models.AVMOp(\n op_code=op.op_code,\n immediates=[\n _resolve_template_vars(ctx, bytes, [(b, es[1]) for b, es in constants.items()])\n ],\n source_location=loc,\n )\n case teal.PushBytes(value=bytes_value):\n return models.AVMOp(\n op_code=op.op_code,\n immediates=[bytes_value],\n source_location=loc,\n )\n case teal.PushBytess(values=values):\n return models.AVMOp(\n op_code=op.op_code,\n immediates=[[t[0] for t in values]],\n source_location=loc,\n )\n case teal.PushInts(values=values):\n return models.AVMOp(\n op_code=op.op_code,\n immediates=[values],\n source_location=loc,\n )\n case teal.CallSub(target=label_id):\n return models.AVMOp(\n op_code=op.op_code,\n immediates=[models.Label(name=label_id)],\n source_location=loc,\n )\n case teal.TealOp(op_code=\"b\" | \"bz\" | \"bnz\", immediates=[str(label_id)]):\n return models.AVMOp(\n op_code=op.op_code,\n immediates=[models.Label(name=label_id)],\n source_location=loc,\n )\n case teal.TealOp(\n op_code=\"switch\" | \"match\" as op_code, immediates=label_ids\n ) if _is_sequence(label_ids, str):\n return models.AVMOp(\n op_code=op_code,\n immediates=[[models.Label(label_id) for label_id in label_ids]],\n source_location=loc,\n )\n case teal.TealOp() if op.op_code not in _BRANCHING_OPS:\n return models.AVMOp(op_code=op.op_code, immediates=op.immediates, source_location=loc)\n case _:\n raise InternalError(f\"invalid teal op: {op}\", loc)\n\n\ndef _resolve_template_vars[T: (int, bytes)](\n ctx: AssembleContext, typ: type[T], values: Iterable[tuple[T | str, SourceLocation | None]]\n) -> Sequence[T]:\n result = []\n for value_or_template, var_loc in values:\n if not isinstance(value_or_template, str):\n value = value_or_template\n else:\n try:\n maybe_value, val_loc = ctx.provided_template_variables[value_or_template]\n except KeyError:\n # if bytecode isn't required for this program, then a dummy value is sufficient\n bytecode_required = ctx.options.output_bytecode and (\n ctx.artifact_ref in ctx.compilation_set\n )\n if ctx.is_reference or bytecode_required:\n logger.error( # noqa: TRY400\n f\"template variable not defined: {value_or_template}\", location=var_loc\n )\n value = typ()\n else:\n if isinstance(maybe_value, typ):\n value = maybe_value\n else:\n logger.error(\n f\"invalid template value type for {value_or_template!r},\"\n f\" expected {typ.__name__}\",\n location=val_loc or var_loc,\n )\n value = typ()\n result.append(value)\n return result\n\n\ndef _encode_op(op: models.AVMOp, *, get_label_offset: Callable[[models.Label], int]) -> bytes:\n op_spec = op.op_spec\n bytecode = _encode_uint8(op.op_spec.code)\n for immediate_kind, immediate in zip(op_spec.immediates, op.immediates, strict=True):\n match immediate_kind:\n case ImmediateKind.uint8 if isinstance(immediate, int):\n bytecode += _encode_uint8(immediate)\n case ImmediateKind.int8 if isinstance(immediate, int):\n bytecode += _encode_int8(immediate)\n case ImmediateEnum(codes=enum_codes) if isinstance(immediate, str):\n immediate_code = enum_codes[immediate]\n bytecode += _encode_uint8(immediate_code)\n case ImmediateKind.bytes if isinstance(immediate, bytes):\n bytecode += _encode_bytes(immediate)\n case ImmediateKind.varuint if isinstance(immediate, int):\n bytecode += _encode_varuint(immediate)\n case ImmediateKind.varuint_array if _is_sequence(immediate, int):\n bytecode += _encode_varuint_array(immediate)\n case ImmediateKind.bytes_array if _is_sequence(immediate, bytes):\n bytecode += _encode_bytes_array(immediate)\n case ImmediateKind.label if isinstance(immediate, models.Label):\n offset = get_label_offset(immediate)\n bytecode += _encode_label(offset)\n case ImmediateKind.label_array if _is_sequence(immediate, models.Label):\n offsets = [get_label_offset(label) for label in immediate]\n bytecode += _encode_label_array(offsets)\n case _:\n raise InternalError(f\"Invalid op: {op}\")\n return bytecode\n\n\n_encode_uint8 = struct.Struct(\">B\").pack\n_encode_int8 = struct.Struct(\">b\").pack\n_encode_label = struct.Struct(\">h\").pack\n\n\ndef _encode_varuint(value: int) -> bytes:\n bits = value & 0x7F\n value >>= 7\n result = b\"\"\n while value:\n result += _encode_uint8(0x80 | bits)\n bits = value & 0x7F\n value >>= 7\n return result + _encode_uint8(bits)\n\n\ndef _encode_bytes(value: bytes) -> bytes:\n return _encode_varuint(len(value)) + value\n\n\ndef _encode_varuint_array(values: Sequence[int]) -> bytes:\n return b\"\".join((_encode_varuint(len(values)), *map(_encode_varuint, values)))\n\n\ndef _encode_label_array(values: Sequence[int]) -> bytes:\n # note: op spec describes a label array size as a varuint\n # however actual algod go implementation is just a single byte\n # additionally max number of labels is 255\n return b\"\".join((_encode_uint8(len(values)), *map(_encode_label, values)))\n\n\ndef _encode_bytes_array(values: Sequence[bytes]) -> bytes:\n return b\"\".join(\n (\n _encode_varuint(len(values)),\n *map(_encode_bytes, values),\n ),\n )\n\n\ndef _is_sequence[_T](maybe: object, typ: type[_T]) -> typing.TypeGuard[Sequence[_T]]:\n return isinstance(maybe, Sequence) and all(isinstance(m, typ) for m in maybe)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ussemble\/assemble.py","language":"Python","license":"NOASSERTION","size":12046} {"code":"import typing\nfrom collections.abc import Mapping\nfrom functools import cached_property\n\nimport attrs\n\nfrom puya.avm import AVMType\nfrom puya.compilation_artifacts import TemplateValue\nfrom puya.context import CompileContext\nfrom puya.program_refs import ContractReference, LogicSigReference\n\n\n@attrs.frozen(kw_only=True)\nclass AssembleContext(CompileContext):\n artifact_ref: ContractReference | LogicSigReference\n is_reference: bool\n template_variable_types: Mapping[str, typing.Literal[AVMType.uint64, AVMType.bytes]]\n \"\"\"Template variables that are required and their types\"\"\"\n template_constants: Mapping[str, TemplateValue] | None\n \"\"\"Template variables provided via compilation\"\"\"\n\n @cached_property\n def provided_template_variables(self) -> Mapping[str, TemplateValue]:\n return {\n **{k: (v, None) for k, v in self.options.template_variables.items()},\n **(self.template_constants or {}),\n }\n\n @cached_property\n def offset_pc_from_constant_blocks(self) -> bool:\n # only need to offset PC if there are any unspecified template variables\n return not (self.provided_template_variables.keys() >= self.template_variable_types.keys())\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ussemble\/context.py","language":"Python","license":"NOASSERTION","size":1214} {"code":"from collections.abc import Mapping, Sequence\n\nfrom puya.compilation_artifacts import DebugEvent, DebugInfo\nfrom puya.parse import SourceLocation\nfrom puya.ussemble import models\nfrom puya.ussemble.context import AssembleContext\nfrom puya.utils import normalize_path\n\n\ndef build_debug_info(\n ctx: AssembleContext,\n pc_ops: Mapping[int, models.AVMOp],\n pc_events: Mapping[int, DebugEvent],\n) -> DebugInfo:\n op_pc_offset = pc_offset = 0\n if ctx.offset_pc_from_constant_blocks:\n for idx, (pc, node) in enumerate(pc_ops.items()):\n # stop at first op that is not a constant block\n if node.op_code not in (\"intcblock\", \"bytecblock\"):\n # only need to set pc_offset if there was a constant block present (i.e. idx != 0)\n # this is because the first op will be after the version byte and so will always\n # have a pc of 1, but a op_pc_offset of 0 means the values are not offset\n if idx:\n op_pc_offset = idx\n pc_offset = pc\n break\n events = {pc - pc_offset: event for pc, event in pc_events.items() if pc >= pc_offset}\n source_map = {\n pc - pc_offset: node.source_location for pc, node in pc_ops.items() if pc >= pc_offset\n }\n\n files = sorted(map(normalize_path, {s.file for s in source_map.values() if s and s.file}))\n mappings = _get_src_mappings(source_map, files)\n\n return DebugInfo(\n version=3,\n sources=files,\n mappings=\";\".join(mappings),\n op_pc_offset=op_pc_offset,\n pc_events=events,\n )\n\n\ndef _get_src_mappings(\n source_map: Mapping[int, SourceLocation | None],\n files: Sequence[str],\n) -> list[str]:\n mappings = []\n previous_source_index = 0\n previous_line = 0\n previous_column = 0\n for pc in range(max(source_map) + 1):\n loc = source_map.get(pc)\n if not loc or not loc.file:\n mappings.append(\"\")\n continue\n source_index = files.index(normalize_path(loc.file))\n line = loc.line - 1 # make 0-indexed\n column = loc.column or 0\n\n mappings.append(\n _base64vlq_encode(\n 0, # generated col offset, always 0 for AVM byte code\n source_index - previous_source_index,\n line - previous_line,\n column - previous_column,\n )\n )\n previous_source_index = source_index\n previous_line = line\n previous_column = column\n return mappings\n\n\ndef _base64vlq_encode(*values: int) -> str:\n \"\"\"Encode integers to a VLQ value\"\"\"\n results = []\n\n b64_chars = b\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/\"\n b64_encode = b64_chars.decode().__getitem__\n shift = 5\n flag = 1 << shift\n mask = flag - 1\n\n for v in values:\n # add sign bit\n v = (abs(v) << 1) | int(v < 0)\n while True:\n to_encode = v & mask\n v >>= shift\n results.append(b64_encode(to_encode | (v and flag)))\n if not v:\n break\n return \"\".join(results)\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ussemble\/debug.py","language":"Python","license":"NOASSERTION","size":3128} {"code":"import typing\nfrom collections.abc import Mapping\n\nfrom puya.avm import AVMType\nfrom puya.compilation_artifacts import TemplateValue\nfrom puya.context import CompileContext\nfrom puya.program_refs import ContractReference, LogicSigReference\nfrom puya.teal import models as teal\nfrom puya.ussemble import models\nfrom puya.ussemble.assemble import assemble_bytecode_and_debug_info\nfrom puya.ussemble.context import AssembleContext\nfrom puya.utils import attrs_extend\n\n\ndef assemble_program(\n ctx: CompileContext,\n ref: ContractReference | LogicSigReference,\n program: teal.TealProgram,\n *,\n template_constants: Mapping[str, TemplateValue] | None = None,\n is_reference: bool = False,\n) -> models.AssembledProgram:\n referenced_template_vars = _gather_template_variables(program)\n assemble_ctx = attrs_extend(\n AssembleContext,\n ctx,\n artifact_ref=ref,\n is_reference=is_reference,\n template_variable_types=referenced_template_vars,\n template_constants=template_constants,\n )\n return assemble_bytecode_and_debug_info(assemble_ctx, program)\n\n\ndef _gather_template_variables(\n program: teal.TealProgram,\n) -> Mapping[str, typing.Literal[AVMType.uint64, AVMType.bytes]]:\n return {\n t: AVMType.uint64 if isinstance(op, teal.IntBlock) else AVMType.bytes\n for sub in program.all_subroutines\n for block in sub.blocks\n for op in block.ops\n if isinstance(op, teal.IntBlock | teal.BytesBlock)\n for t in op.constants\n if isinstance(t, str)\n }\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ussemble\/main.py","language":"Python","license":"NOASSERTION","size":1555} {"code":"from collections.abc import Mapping, Sequence\n\nimport attrs\n\nfrom puya.compilation_artifacts import DebugInfo\nfrom puya.parse import SourceLocation\nfrom puya.ussemble.op_spec import OP_SPECS\nfrom puya.ussemble.op_spec_models import OpSpec\n\n\n@attrs.frozen(str=False)\nclass Label:\n name: str\n\n def __str__(self) -> str:\n return f\"{self.name}:\"\n\n\n@attrs.frozen(str=False, eq=False)\nclass AVMOp:\n source_location: SourceLocation | None\n op_code: str\n immediates: Sequence[\n Sequence[int] | int | Sequence[bytes] | bytes | Sequence[Label] | Label | str\n ]\n\n @property\n def op_spec(self) -> OpSpec:\n return OP_SPECS[self.op_code]\n\n\n@attrs.frozen\nclass AssembledProgram:\n bytecode: bytes\n debug_info: DebugInfo\n template_variables: Mapping[str, int | bytes | None]\n \"\"\"Indicates template variable values used in compilation\"\"\"\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ussemble\/models.py","language":"Python","license":"NOASSERTION","size":877} {"code":"from puya.ussemble.op_spec_models import ImmediateEnum, ImmediateKind, OpSpec\n\nOP_SPECS = {\n \"err\": OpSpec(name=\"err\", code=0, immediates=[]),\n \"sha256\": OpSpec(name=\"sha256\", code=1, immediates=[]),\n \"keccak256\": OpSpec(name=\"keccak256\", code=2, immediates=[]),\n \"sha512_256\": OpSpec(name=\"sha512_256\", code=3, immediates=[]),\n \"ed25519verify\": OpSpec(name=\"ed25519verify\", code=4, immediates=[]),\n \"ecdsa_verify\": OpSpec(\n name=\"ecdsa_verify\",\n code=5,\n immediates=[ImmediateEnum(codes={\"Secp256k1\": 0, \"Secp256r1\": 1})],\n ),\n \"ecdsa_pk_decompress\": OpSpec(\n name=\"ecdsa_pk_decompress\",\n code=6,\n immediates=[ImmediateEnum(codes={\"Secp256k1\": 0, \"Secp256r1\": 1})],\n ),\n \"ecdsa_pk_recover\": OpSpec(\n name=\"ecdsa_pk_recover\",\n code=7,\n immediates=[ImmediateEnum(codes={\"Secp256k1\": 0, \"Secp256r1\": 1})],\n ),\n \"+\": OpSpec(name=\"+\", code=8, immediates=[]),\n \"-\": OpSpec(name=\"-\", code=9, immediates=[]),\n \"\/\": OpSpec(name=\"\/\", code=10, immediates=[]),\n \"*\": OpSpec(name=\"*\", code=11, immediates=[]),\n \"<\": OpSpec(name=\"<\", code=12, immediates=[]),\n \">\": OpSpec(name=\">\", code=13, immediates=[]),\n \"<=\": OpSpec(name=\"<=\", code=14, immediates=[]),\n \">=\": OpSpec(name=\">=\", code=15, immediates=[]),\n \"&&\": OpSpec(name=\"&&\", code=16, immediates=[]),\n \"||\": OpSpec(name=\"||\", code=17, immediates=[]),\n \"==\": OpSpec(name=\"==\", code=18, immediates=[]),\n \"!=\": OpSpec(name=\"!=\", code=19, immediates=[]),\n \"!\": OpSpec(name=\"!\", code=20, immediates=[]),\n \"len\": OpSpec(name=\"len\", code=21, immediates=[]),\n \"itob\": OpSpec(name=\"itob\", code=22, immediates=[]),\n \"btoi\": OpSpec(name=\"btoi\", code=23, immediates=[]),\n \"%\": OpSpec(name=\"%\", code=24, immediates=[]),\n \"|\": OpSpec(name=\"|\", code=25, immediates=[]),\n \"&\": OpSpec(name=\"&\", code=26, immediates=[]),\n \"^\": OpSpec(name=\"^\", code=27, immediates=[]),\n \"~\": OpSpec(name=\"~\", code=28, immediates=[]),\n \"mulw\": OpSpec(name=\"mulw\", code=29, immediates=[]),\n \"addw\": OpSpec(name=\"addw\", code=30, immediates=[]),\n \"divmodw\": OpSpec(name=\"divmodw\", code=31, immediates=[]),\n \"intcblock\": OpSpec(name=\"intcblock\", code=32, immediates=[ImmediateKind.varuint_array]),\n \"intc\": OpSpec(name=\"intc\", code=33, immediates=[ImmediateKind.uint8]),\n \"intc_0\": OpSpec(name=\"intc_0\", code=34, immediates=[]),\n \"intc_1\": OpSpec(name=\"intc_1\", code=35, immediates=[]),\n \"intc_2\": OpSpec(name=\"intc_2\", code=36, immediates=[]),\n \"intc_3\": OpSpec(name=\"intc_3\", code=37, immediates=[]),\n \"bytecblock\": OpSpec(name=\"bytecblock\", code=38, immediates=[ImmediateKind.bytes_array]),\n \"bytec\": OpSpec(name=\"bytec\", code=39, immediates=[ImmediateKind.uint8]),\n \"bytec_0\": OpSpec(name=\"bytec_0\", code=40, immediates=[]),\n \"bytec_1\": OpSpec(name=\"bytec_1\", code=41, immediates=[]),\n \"bytec_2\": OpSpec(name=\"bytec_2\", code=42, immediates=[]),\n \"bytec_3\": OpSpec(name=\"bytec_3\", code=43, immediates=[]),\n \"arg\": OpSpec(name=\"arg\", code=44, immediates=[ImmediateKind.uint8]),\n \"arg_0\": OpSpec(name=\"arg_0\", code=45, immediates=[]),\n \"arg_1\": OpSpec(name=\"arg_1\", code=46, immediates=[]),\n \"arg_2\": OpSpec(name=\"arg_2\", code=47, immediates=[]),\n \"arg_3\": OpSpec(name=\"arg_3\", code=48, immediates=[]),\n \"txn\": OpSpec(\n name=\"txn\",\n code=49,\n immediates=[\n ImmediateEnum(\n codes={\n \"Sender\": 0,\n \"Fee\": 1,\n \"FirstValid\": 2,\n \"FirstValidTime\": 3,\n \"LastValid\": 4,\n \"Note\": 5,\n \"Lease\": 6,\n \"Receiver\": 7,\n \"Amount\": 8,\n \"CloseRemainderTo\": 9,\n \"VotePK\": 10,\n \"SelectionPK\": 11,\n \"VoteFirst\": 12,\n \"VoteLast\": 13,\n \"VoteKeyDilution\": 14,\n \"Type\": 15,\n \"TypeEnum\": 16,\n \"XferAsset\": 17,\n \"AssetAmount\": 18,\n \"AssetSender\": 19,\n \"AssetReceiver\": 20,\n \"AssetCloseTo\": 21,\n \"GroupIndex\": 22,\n \"TxID\": 23,\n \"ApplicationID\": 24,\n \"OnCompletion\": 25,\n \"ApplicationArgs\": 26,\n \"NumAppArgs\": 27,\n \"Accounts\": 28,\n \"NumAccounts\": 29,\n \"ApprovalProgram\": 30,\n \"ClearStateProgram\": 31,\n \"RekeyTo\": 32,\n \"ConfigAsset\": 33,\n \"ConfigAssetTotal\": 34,\n \"ConfigAssetDecimals\": 35,\n \"ConfigAssetDefaultFrozen\": 36,\n \"ConfigAssetUnitName\": 37,\n \"ConfigAssetName\": 38,\n \"ConfigAssetURL\": 39,\n \"ConfigAssetMetadataHash\": 40,\n \"ConfigAssetManager\": 41,\n \"ConfigAssetReserve\": 42,\n \"ConfigAssetFreeze\": 43,\n \"ConfigAssetClawback\": 44,\n \"FreezeAsset\": 45,\n \"FreezeAssetAccount\": 46,\n \"FreezeAssetFrozen\": 47,\n \"Assets\": 48,\n \"NumAssets\": 49,\n \"Applications\": 50,\n \"NumApplications\": 51,\n \"GlobalNumUint\": 52,\n \"GlobalNumByteSlice\": 53,\n \"LocalNumUint\": 54,\n \"LocalNumByteSlice\": 55,\n \"ExtraProgramPages\": 56,\n \"Nonparticipation\": 57,\n \"Logs\": 58,\n \"NumLogs\": 59,\n \"CreatedAssetID\": 60,\n \"CreatedApplicationID\": 61,\n \"LastLog\": 62,\n \"StateProofPK\": 63,\n \"ApprovalProgramPages\": 64,\n \"NumApprovalProgramPages\": 65,\n \"ClearStateProgramPages\": 66,\n \"NumClearStateProgramPages\": 67,\n }\n )\n ],\n ),\n \"global\": OpSpec(\n name=\"global\",\n code=50,\n immediates=[\n ImmediateEnum(\n codes={\n \"MinTxnFee\": 0,\n \"MinBalance\": 1,\n \"MaxTxnLife\": 2,\n \"ZeroAddress\": 3,\n \"GroupSize\": 4,\n \"LogicSigVersion\": 5,\n \"Round\": 6,\n \"LatestTimestamp\": 7,\n \"CurrentApplicationID\": 8,\n \"CreatorAddress\": 9,\n \"CurrentApplicationAddress\": 10,\n \"GroupID\": 11,\n \"OpcodeBudget\": 12,\n \"CallerApplicationID\": 13,\n \"CallerApplicationAddress\": 14,\n \"AssetCreateMinBalance\": 15,\n \"AssetOptInMinBalance\": 16,\n \"GenesisHash\": 17,\n \"PayoutsEnabled\": 18,\n \"PayoutsGoOnlineFee\": 19,\n \"PayoutsPercent\": 20,\n \"PayoutsMinBalance\": 21,\n \"PayoutsMaxBalance\": 22,\n }\n )\n ],\n ),\n \"gtxn\": OpSpec(\n name=\"gtxn\",\n code=51,\n immediates=[\n ImmediateKind.uint8,\n ImmediateEnum(\n codes={\n \"Sender\": 0,\n \"Fee\": 1,\n \"FirstValid\": 2,\n \"FirstValidTime\": 3,\n \"LastValid\": 4,\n \"Note\": 5,\n \"Lease\": 6,\n \"Receiver\": 7,\n \"Amount\": 8,\n \"CloseRemainderTo\": 9,\n \"VotePK\": 10,\n \"SelectionPK\": 11,\n \"VoteFirst\": 12,\n \"VoteLast\": 13,\n \"VoteKeyDilution\": 14,\n \"Type\": 15,\n \"TypeEnum\": 16,\n \"XferAsset\": 17,\n \"AssetAmount\": 18,\n \"AssetSender\": 19,\n \"AssetReceiver\": 20,\n \"AssetCloseTo\": 21,\n \"GroupIndex\": 22,\n \"TxID\": 23,\n \"ApplicationID\": 24,\n \"OnCompletion\": 25,\n \"ApplicationArgs\": 26,\n \"NumAppArgs\": 27,\n \"Accounts\": 28,\n \"NumAccounts\": 29,\n \"ApprovalProgram\": 30,\n \"ClearStateProgram\": 31,\n \"RekeyTo\": 32,\n \"ConfigAsset\": 33,\n \"ConfigAssetTotal\": 34,\n \"ConfigAssetDecimals\": 35,\n \"ConfigAssetDefaultFrozen\": 36,\n \"ConfigAssetUnitName\": 37,\n \"ConfigAssetName\": 38,\n \"ConfigAssetURL\": 39,\n \"ConfigAssetMetadataHash\": 40,\n \"ConfigAssetManager\": 41,\n \"ConfigAssetReserve\": 42,\n \"ConfigAssetFreeze\": 43,\n \"ConfigAssetClawback\": 44,\n \"FreezeAsset\": 45,\n \"FreezeAssetAccount\": 46,\n \"FreezeAssetFrozen\": 47,\n \"Assets\": 48,\n \"NumAssets\": 49,\n \"Applications\": 50,\n \"NumApplications\": 51,\n \"GlobalNumUint\": 52,\n \"GlobalNumByteSlice\": 53,\n \"LocalNumUint\": 54,\n \"LocalNumByteSlice\": 55,\n \"ExtraProgramPages\": 56,\n \"Nonparticipation\": 57,\n \"Logs\": 58,\n \"NumLogs\": 59,\n \"CreatedAssetID\": 60,\n \"CreatedApplicationID\": 61,\n \"LastLog\": 62,\n \"StateProofPK\": 63,\n \"ApprovalProgramPages\": 64,\n \"NumApprovalProgramPages\": 65,\n \"ClearStateProgramPages\": 66,\n \"NumClearStateProgramPages\": 67,\n }\n ),\n ],\n ),\n \"load\": OpSpec(name=\"load\", code=52, immediates=[ImmediateKind.uint8]),\n \"store\": OpSpec(name=\"store\", code=53, immediates=[ImmediateKind.uint8]),\n \"txna\": OpSpec(\n name=\"txna\",\n code=54,\n immediates=[\n ImmediateEnum(\n codes={\n \"ApplicationArgs\": 26,\n \"Accounts\": 28,\n \"Assets\": 48,\n \"Applications\": 50,\n \"Logs\": 58,\n \"ApprovalProgramPages\": 64,\n \"ClearStateProgramPages\": 66,\n }\n ),\n ImmediateKind.uint8,\n ],\n ),\n \"gtxna\": OpSpec(\n name=\"gtxna\",\n code=55,\n immediates=[\n ImmediateKind.uint8,\n ImmediateEnum(\n codes={\n \"ApplicationArgs\": 26,\n \"Accounts\": 28,\n \"Assets\": 48,\n \"Applications\": 50,\n \"Logs\": 58,\n \"ApprovalProgramPages\": 64,\n \"ClearStateProgramPages\": 66,\n }\n ),\n ImmediateKind.uint8,\n ],\n ),\n \"gtxns\": OpSpec(\n name=\"gtxns\",\n code=56,\n immediates=[\n ImmediateEnum(\n codes={\n \"Sender\": 0,\n \"Fee\": 1,\n \"FirstValid\": 2,\n \"FirstValidTime\": 3,\n \"LastValid\": 4,\n \"Note\": 5,\n \"Lease\": 6,\n \"Receiver\": 7,\n \"Amount\": 8,\n \"CloseRemainderTo\": 9,\n \"VotePK\": 10,\n \"SelectionPK\": 11,\n \"VoteFirst\": 12,\n \"VoteLast\": 13,\n \"VoteKeyDilution\": 14,\n \"Type\": 15,\n \"TypeEnum\": 16,\n \"XferAsset\": 17,\n \"AssetAmount\": 18,\n \"AssetSender\": 19,\n \"AssetReceiver\": 20,\n \"AssetCloseTo\": 21,\n \"GroupIndex\": 22,\n \"TxID\": 23,\n \"ApplicationID\": 24,\n \"OnCompletion\": 25,\n \"ApplicationArgs\": 26,\n \"NumAppArgs\": 27,\n \"Accounts\": 28,\n \"NumAccounts\": 29,\n \"ApprovalProgram\": 30,\n \"ClearStateProgram\": 31,\n \"RekeyTo\": 32,\n \"ConfigAsset\": 33,\n \"ConfigAssetTotal\": 34,\n \"ConfigAssetDecimals\": 35,\n \"ConfigAssetDefaultFrozen\": 36,\n \"ConfigAssetUnitName\": 37,\n \"ConfigAssetName\": 38,\n \"ConfigAssetURL\": 39,\n \"ConfigAssetMetadataHash\": 40,\n \"ConfigAssetManager\": 41,\n \"ConfigAssetReserve\": 42,\n \"ConfigAssetFreeze\": 43,\n \"ConfigAssetClawback\": 44,\n \"FreezeAsset\": 45,\n \"FreezeAssetAccount\": 46,\n \"FreezeAssetFrozen\": 47,\n \"Assets\": 48,\n \"NumAssets\": 49,\n \"Applications\": 50,\n \"NumApplications\": 51,\n \"GlobalNumUint\": 52,\n \"GlobalNumByteSlice\": 53,\n \"LocalNumUint\": 54,\n \"LocalNumByteSlice\": 55,\n \"ExtraProgramPages\": 56,\n \"Nonparticipation\": 57,\n \"Logs\": 58,\n \"NumLogs\": 59,\n \"CreatedAssetID\": 60,\n \"CreatedApplicationID\": 61,\n \"LastLog\": 62,\n \"StateProofPK\": 63,\n \"ApprovalProgramPages\": 64,\n \"NumApprovalProgramPages\": 65,\n \"ClearStateProgramPages\": 66,\n \"NumClearStateProgramPages\": 67,\n }\n )\n ],\n ),\n \"gtxnsa\": OpSpec(\n name=\"gtxnsa\",\n code=57,\n immediates=[\n ImmediateEnum(\n codes={\n \"ApplicationArgs\": 26,\n \"Accounts\": 28,\n \"Assets\": 48,\n \"Applications\": 50,\n \"Logs\": 58,\n \"ApprovalProgramPages\": 64,\n \"ClearStateProgramPages\": 66,\n }\n ),\n ImmediateKind.uint8,\n ],\n ),\n \"gload\": OpSpec(name=\"gload\", code=58, immediates=[ImmediateKind.uint8, ImmediateKind.uint8]),\n \"gloads\": OpSpec(name=\"gloads\", code=59, immediates=[ImmediateKind.uint8]),\n \"gaid\": OpSpec(name=\"gaid\", code=60, immediates=[ImmediateKind.uint8]),\n \"gaids\": OpSpec(name=\"gaids\", code=61, immediates=[]),\n \"loads\": OpSpec(name=\"loads\", code=62, immediates=[]),\n \"stores\": OpSpec(name=\"stores\", code=63, immediates=[]),\n \"bnz\": OpSpec(name=\"bnz\", code=64, immediates=[ImmediateKind.label]),\n \"bz\": OpSpec(name=\"bz\", code=65, immediates=[ImmediateKind.label]),\n \"b\": OpSpec(name=\"b\", code=66, immediates=[ImmediateKind.label]),\n \"return\": OpSpec(name=\"return\", code=67, immediates=[]),\n \"assert\": OpSpec(name=\"assert\", code=68, immediates=[]),\n \"bury\": OpSpec(name=\"bury\", code=69, immediates=[ImmediateKind.uint8]),\n \"popn\": OpSpec(name=\"popn\", code=70, immediates=[ImmediateKind.uint8]),\n \"dupn\": OpSpec(name=\"dupn\", code=71, immediates=[ImmediateKind.uint8]),\n \"pop\": OpSpec(name=\"pop\", code=72, immediates=[]),\n \"dup\": OpSpec(name=\"dup\", code=73, immediates=[]),\n \"dup2\": OpSpec(name=\"dup2\", code=74, immediates=[]),\n \"dig\": OpSpec(name=\"dig\", code=75, immediates=[ImmediateKind.uint8]),\n \"swap\": OpSpec(name=\"swap\", code=76, immediates=[]),\n \"select\": OpSpec(name=\"select\", code=77, immediates=[]),\n \"cover\": OpSpec(name=\"cover\", code=78, immediates=[ImmediateKind.uint8]),\n \"uncover\": OpSpec(name=\"uncover\", code=79, immediates=[ImmediateKind.uint8]),\n \"concat\": OpSpec(name=\"concat\", code=80, immediates=[]),\n \"substring\": OpSpec(\n name=\"substring\", code=81, immediates=[ImmediateKind.uint8, ImmediateKind.uint8]\n ),\n \"substring3\": OpSpec(name=\"substring3\", code=82, immediates=[]),\n \"getbit\": OpSpec(name=\"getbit\", code=83, immediates=[]),\n \"setbit\": OpSpec(name=\"setbit\", code=84, immediates=[]),\n \"getbyte\": OpSpec(name=\"getbyte\", code=85, immediates=[]),\n \"setbyte\": OpSpec(name=\"setbyte\", code=86, immediates=[]),\n \"extract\": OpSpec(\n name=\"extract\", code=87, immediates=[ImmediateKind.uint8, ImmediateKind.uint8]\n ),\n \"extract3\": OpSpec(name=\"extract3\", code=88, immediates=[]),\n \"extract_uint16\": OpSpec(name=\"extract_uint16\", code=89, immediates=[]),\n \"extract_uint32\": OpSpec(name=\"extract_uint32\", code=90, immediates=[]),\n \"extract_uint64\": OpSpec(name=\"extract_uint64\", code=91, immediates=[]),\n \"replace2\": OpSpec(name=\"replace2\", code=92, immediates=[ImmediateKind.uint8]),\n \"replace3\": OpSpec(name=\"replace3\", code=93, immediates=[]),\n \"base64_decode\": OpSpec(\n name=\"base64_decode\",\n code=94,\n immediates=[ImmediateEnum(codes={\"URLEncoding\": 0, \"StdEncoding\": 1})],\n ),\n \"json_ref\": OpSpec(\n name=\"json_ref\",\n code=95,\n immediates=[ImmediateEnum(codes={\"JSONString\": 0, \"JSONUint64\": 1, \"JSONObject\": 2})],\n ),\n \"balance\": OpSpec(name=\"balance\", code=96, immediates=[]),\n \"app_opted_in\": OpSpec(name=\"app_opted_in\", code=97, immediates=[]),\n \"app_local_get\": OpSpec(name=\"app_local_get\", code=98, immediates=[]),\n \"app_local_get_ex\": OpSpec(name=\"app_local_get_ex\", code=99, immediates=[]),\n \"app_global_get\": OpSpec(name=\"app_global_get\", code=100, immediates=[]),\n \"app_global_get_ex\": OpSpec(name=\"app_global_get_ex\", code=101, immediates=[]),\n \"app_local_put\": OpSpec(name=\"app_local_put\", code=102, immediates=[]),\n \"app_global_put\": OpSpec(name=\"app_global_put\", code=103, immediates=[]),\n \"app_local_del\": OpSpec(name=\"app_local_del\", code=104, immediates=[]),\n \"app_global_del\": OpSpec(name=\"app_global_del\", code=105, immediates=[]),\n \"asset_holding_get\": OpSpec(\n name=\"asset_holding_get\",\n code=112,\n immediates=[ImmediateEnum(codes={\"AssetBalance\": 0, \"AssetFrozen\": 1})],\n ),\n \"asset_params_get\": OpSpec(\n name=\"asset_params_get\",\n code=113,\n immediates=[\n ImmediateEnum(\n codes={\n \"AssetTotal\": 0,\n \"AssetDecimals\": 1,\n \"AssetDefaultFrozen\": 2,\n \"AssetUnitName\": 3,\n \"AssetName\": 4,\n \"AssetURL\": 5,\n \"AssetMetadataHash\": 6,\n \"AssetManager\": 7,\n \"AssetReserve\": 8,\n \"AssetFreeze\": 9,\n \"AssetClawback\": 10,\n \"AssetCreator\": 11,\n }\n )\n ],\n ),\n \"app_params_get\": OpSpec(\n name=\"app_params_get\",\n code=114,\n immediates=[\n ImmediateEnum(\n codes={\n \"AppApprovalProgram\": 0,\n \"AppClearStateProgram\": 1,\n \"AppGlobalNumUint\": 2,\n \"AppGlobalNumByteSlice\": 3,\n \"AppLocalNumUint\": 4,\n \"AppLocalNumByteSlice\": 5,\n \"AppExtraProgramPages\": 6,\n \"AppCreator\": 7,\n \"AppAddress\": 8,\n }\n )\n ],\n ),\n \"acct_params_get\": OpSpec(\n name=\"acct_params_get\",\n code=115,\n immediates=[\n ImmediateEnum(\n codes={\n \"AcctBalance\": 0,\n \"AcctMinBalance\": 1,\n \"AcctAuthAddr\": 2,\n \"AcctTotalNumUint\": 3,\n \"AcctTotalNumByteSlice\": 4,\n \"AcctTotalExtraAppPages\": 5,\n \"AcctTotalAppsCreated\": 6,\n \"AcctTotalAppsOptedIn\": 7,\n \"AcctTotalAssetsCreated\": 8,\n \"AcctTotalAssets\": 9,\n \"AcctTotalBoxes\": 10,\n \"AcctTotalBoxBytes\": 11,\n \"AcctIncentiveEligible\": 12,\n \"AcctLastProposed\": 13,\n \"AcctLastHeartbeat\": 14,\n }\n )\n ],\n ),\n \"voter_params_get\": OpSpec(\n name=\"voter_params_get\",\n code=116,\n immediates=[ImmediateEnum(codes={\"VoterBalance\": 0, \"VoterIncentiveEligible\": 1})],\n ),\n \"online_stake\": OpSpec(name=\"online_stake\", code=117, immediates=[]),\n \"min_balance\": OpSpec(name=\"min_balance\", code=120, immediates=[]),\n \"pushbytes\": OpSpec(name=\"pushbytes\", code=128, immediates=[ImmediateKind.bytes]),\n \"pushint\": OpSpec(name=\"pushint\", code=129, immediates=[ImmediateKind.varuint]),\n \"pushbytess\": OpSpec(name=\"pushbytess\", code=130, immediates=[ImmediateKind.bytes_array]),\n \"pushints\": OpSpec(name=\"pushints\", code=131, immediates=[ImmediateKind.varuint_array]),\n \"ed25519verify_bare\": OpSpec(name=\"ed25519verify_bare\", code=132, immediates=[]),\n \"falcon_verify\": OpSpec(name=\"falcon_verify\", code=133, immediates=[]),\n \"sumhash512\": OpSpec(name=\"sumhash512\", code=134, immediates=[]),\n \"callsub\": OpSpec(name=\"callsub\", code=136, immediates=[ImmediateKind.label]),\n \"retsub\": OpSpec(name=\"retsub\", code=137, immediates=[]),\n \"proto\": OpSpec(name=\"proto\", code=138, immediates=[ImmediateKind.uint8, ImmediateKind.uint8]),\n \"frame_dig\": OpSpec(name=\"frame_dig\", code=139, immediates=[ImmediateKind.int8]),\n \"frame_bury\": OpSpec(name=\"frame_bury\", code=140, immediates=[ImmediateKind.int8]),\n \"switch\": OpSpec(name=\"switch\", code=141, immediates=[ImmediateKind.label_array]),\n \"match\": OpSpec(name=\"match\", code=142, immediates=[ImmediateKind.label_array]),\n \"shl\": OpSpec(name=\"shl\", code=144, immediates=[]),\n \"shr\": OpSpec(name=\"shr\", code=145, immediates=[]),\n \"sqrt\": OpSpec(name=\"sqrt\", code=146, immediates=[]),\n \"bitlen\": OpSpec(name=\"bitlen\", code=147, immediates=[]),\n \"exp\": OpSpec(name=\"exp\", code=148, immediates=[]),\n \"expw\": OpSpec(name=\"expw\", code=149, immediates=[]),\n \"bsqrt\": OpSpec(name=\"bsqrt\", code=150, immediates=[]),\n \"divw\": OpSpec(name=\"divw\", code=151, immediates=[]),\n \"sha3_256\": OpSpec(name=\"sha3_256\", code=152, immediates=[]),\n \"b+\": OpSpec(name=\"b+\", code=160, immediates=[]),\n \"b-\": OpSpec(name=\"b-\", code=161, immediates=[]),\n \"b\/\": OpSpec(name=\"b\/\", code=162, immediates=[]),\n \"b*\": OpSpec(name=\"b*\", code=163, immediates=[]),\n \"b<\": OpSpec(name=\"b<\", code=164, immediates=[]),\n \"b>\": OpSpec(name=\"b>\", code=165, immediates=[]),\n \"b<=\": OpSpec(name=\"b<=\", code=166, immediates=[]),\n \"b>=\": OpSpec(name=\"b>=\", code=167, immediates=[]),\n \"b==\": OpSpec(name=\"b==\", code=168, immediates=[]),\n \"b!=\": OpSpec(name=\"b!=\", code=169, immediates=[]),\n \"b%\": OpSpec(name=\"b%\", code=170, immediates=[]),\n \"b|\": OpSpec(name=\"b|\", code=171, immediates=[]),\n \"b&\": OpSpec(name=\"b&\", code=172, immediates=[]),\n \"b^\": OpSpec(name=\"b^\", code=173, immediates=[]),\n \"b~\": OpSpec(name=\"b~\", code=174, immediates=[]),\n \"bzero\": OpSpec(name=\"bzero\", code=175, immediates=[]),\n \"log\": OpSpec(name=\"log\", code=176, immediates=[]),\n \"itxn_begin\": OpSpec(name=\"itxn_begin\", code=177, immediates=[]),\n \"itxn_field\": OpSpec(\n name=\"itxn_field\",\n code=178,\n immediates=[\n ImmediateEnum(\n codes={\n \"Sender\": 0,\n \"Fee\": 1,\n \"Note\": 5,\n \"Receiver\": 7,\n \"Amount\": 8,\n \"CloseRemainderTo\": 9,\n \"VotePK\": 10,\n \"SelectionPK\": 11,\n \"VoteFirst\": 12,\n \"VoteLast\": 13,\n \"VoteKeyDilution\": 14,\n \"Type\": 15,\n \"TypeEnum\": 16,\n \"XferAsset\": 17,\n \"AssetAmount\": 18,\n \"AssetSender\": 19,\n \"AssetReceiver\": 20,\n \"AssetCloseTo\": 21,\n \"ApplicationID\": 24,\n \"OnCompletion\": 25,\n \"ApplicationArgs\": 26,\n \"Accounts\": 28,\n \"ApprovalProgram\": 30,\n \"ClearStateProgram\": 31,\n \"RekeyTo\": 32,\n \"ConfigAsset\": 33,\n \"ConfigAssetTotal\": 34,\n \"ConfigAssetDecimals\": 35,\n \"ConfigAssetDefaultFrozen\": 36,\n \"ConfigAssetUnitName\": 37,\n \"ConfigAssetName\": 38,\n \"ConfigAssetURL\": 39,\n \"ConfigAssetMetadataHash\": 40,\n \"ConfigAssetManager\": 41,\n \"ConfigAssetReserve\": 42,\n \"ConfigAssetFreeze\": 43,\n \"ConfigAssetClawback\": 44,\n \"FreezeAsset\": 45,\n \"FreezeAssetAccount\": 46,\n \"FreezeAssetFrozen\": 47,\n \"Assets\": 48,\n \"Applications\": 50,\n \"GlobalNumUint\": 52,\n \"GlobalNumByteSlice\": 53,\n \"LocalNumUint\": 54,\n \"LocalNumByteSlice\": 55,\n \"ExtraProgramPages\": 56,\n \"Nonparticipation\": 57,\n \"StateProofPK\": 63,\n \"ApprovalProgramPages\": 64,\n \"ClearStateProgramPages\": 66,\n }\n )\n ],\n ),\n \"itxn_submit\": OpSpec(name=\"itxn_submit\", code=179, immediates=[]),\n \"itxn\": OpSpec(\n name=\"itxn\",\n code=180,\n immediates=[\n ImmediateEnum(\n codes={\n \"Sender\": 0,\n \"Fee\": 1,\n \"FirstValid\": 2,\n \"FirstValidTime\": 3,\n \"LastValid\": 4,\n \"Note\": 5,\n \"Lease\": 6,\n \"Receiver\": 7,\n \"Amount\": 8,\n \"CloseRemainderTo\": 9,\n \"VotePK\": 10,\n \"SelectionPK\": 11,\n \"VoteFirst\": 12,\n \"VoteLast\": 13,\n \"VoteKeyDilution\": 14,\n \"Type\": 15,\n \"TypeEnum\": 16,\n \"XferAsset\": 17,\n \"AssetAmount\": 18,\n \"AssetSender\": 19,\n \"AssetReceiver\": 20,\n \"AssetCloseTo\": 21,\n \"GroupIndex\": 22,\n \"TxID\": 23,\n \"ApplicationID\": 24,\n \"OnCompletion\": 25,\n \"ApplicationArgs\": 26,\n \"NumAppArgs\": 27,\n \"Accounts\": 28,\n \"NumAccounts\": 29,\n \"ApprovalProgram\": 30,\n \"ClearStateProgram\": 31,\n \"RekeyTo\": 32,\n \"ConfigAsset\": 33,\n \"ConfigAssetTotal\": 34,\n \"ConfigAssetDecimals\": 35,\n \"ConfigAssetDefaultFrozen\": 36,\n \"ConfigAssetUnitName\": 37,\n \"ConfigAssetName\": 38,\n \"ConfigAssetURL\": 39,\n \"ConfigAssetMetadataHash\": 40,\n \"ConfigAssetManager\": 41,\n \"ConfigAssetReserve\": 42,\n \"ConfigAssetFreeze\": 43,\n \"ConfigAssetClawback\": 44,\n \"FreezeAsset\": 45,\n \"FreezeAssetAccount\": 46,\n \"FreezeAssetFrozen\": 47,\n \"Assets\": 48,\n \"NumAssets\": 49,\n \"Applications\": 50,\n \"NumApplications\": 51,\n \"GlobalNumUint\": 52,\n \"GlobalNumByteSlice\": 53,\n \"LocalNumUint\": 54,\n \"LocalNumByteSlice\": 55,\n \"ExtraProgramPages\": 56,\n \"Nonparticipation\": 57,\n \"Logs\": 58,\n \"NumLogs\": 59,\n \"CreatedAssetID\": 60,\n \"CreatedApplicationID\": 61,\n \"LastLog\": 62,\n \"StateProofPK\": 63,\n \"ApprovalProgramPages\": 64,\n \"NumApprovalProgramPages\": 65,\n \"ClearStateProgramPages\": 66,\n \"NumClearStateProgramPages\": 67,\n }\n )\n ],\n ),\n \"itxna\": OpSpec(\n name=\"itxna\",\n code=181,\n immediates=[\n ImmediateEnum(\n codes={\n \"ApplicationArgs\": 26,\n \"Accounts\": 28,\n \"Assets\": 48,\n \"Applications\": 50,\n \"Logs\": 58,\n \"ApprovalProgramPages\": 64,\n \"ClearStateProgramPages\": 66,\n }\n ),\n ImmediateKind.uint8,\n ],\n ),\n \"itxn_next\": OpSpec(name=\"itxn_next\", code=182, immediates=[]),\n \"gitxn\": OpSpec(\n name=\"gitxn\",\n code=183,\n immediates=[\n ImmediateKind.uint8,\n ImmediateEnum(\n codes={\n \"Sender\": 0,\n \"Fee\": 1,\n \"FirstValid\": 2,\n \"FirstValidTime\": 3,\n \"LastValid\": 4,\n \"Note\": 5,\n \"Lease\": 6,\n \"Receiver\": 7,\n \"Amount\": 8,\n \"CloseRemainderTo\": 9,\n \"VotePK\": 10,\n \"SelectionPK\": 11,\n \"VoteFirst\": 12,\n \"VoteLast\": 13,\n \"VoteKeyDilution\": 14,\n \"Type\": 15,\n \"TypeEnum\": 16,\n \"XferAsset\": 17,\n \"AssetAmount\": 18,\n \"AssetSender\": 19,\n \"AssetReceiver\": 20,\n \"AssetCloseTo\": 21,\n \"GroupIndex\": 22,\n \"TxID\": 23,\n \"ApplicationID\": 24,\n \"OnCompletion\": 25,\n \"ApplicationArgs\": 26,\n \"NumAppArgs\": 27,\n \"Accounts\": 28,\n \"NumAccounts\": 29,\n \"ApprovalProgram\": 30,\n \"ClearStateProgram\": 31,\n \"RekeyTo\": 32,\n \"ConfigAsset\": 33,\n \"ConfigAssetTotal\": 34,\n \"ConfigAssetDecimals\": 35,\n \"ConfigAssetDefaultFrozen\": 36,\n \"ConfigAssetUnitName\": 37,\n \"ConfigAssetName\": 38,\n \"ConfigAssetURL\": 39,\n \"ConfigAssetMetadataHash\": 40,\n \"ConfigAssetManager\": 41,\n \"ConfigAssetReserve\": 42,\n \"ConfigAssetFreeze\": 43,\n \"ConfigAssetClawback\": 44,\n \"FreezeAsset\": 45,\n \"FreezeAssetAccount\": 46,\n \"FreezeAssetFrozen\": 47,\n \"Assets\": 48,\n \"NumAssets\": 49,\n \"Applications\": 50,\n \"NumApplications\": 51,\n \"GlobalNumUint\": 52,\n \"GlobalNumByteSlice\": 53,\n \"LocalNumUint\": 54,\n \"LocalNumByteSlice\": 55,\n \"ExtraProgramPages\": 56,\n \"Nonparticipation\": 57,\n \"Logs\": 58,\n \"NumLogs\": 59,\n \"CreatedAssetID\": 60,\n \"CreatedApplicationID\": 61,\n \"LastLog\": 62,\n \"StateProofPK\": 63,\n \"ApprovalProgramPages\": 64,\n \"NumApprovalProgramPages\": 65,\n \"ClearStateProgramPages\": 66,\n \"NumClearStateProgramPages\": 67,\n }\n ),\n ],\n ),\n \"gitxna\": OpSpec(\n name=\"gitxna\",\n code=184,\n immediates=[\n ImmediateKind.uint8,\n ImmediateEnum(\n codes={\n \"ApplicationArgs\": 26,\n \"Accounts\": 28,\n \"Assets\": 48,\n \"Applications\": 50,\n \"Logs\": 58,\n \"ApprovalProgramPages\": 64,\n \"ClearStateProgramPages\": 66,\n }\n ),\n ImmediateKind.uint8,\n ],\n ),\n \"box_create\": OpSpec(name=\"box_create\", code=185, immediates=[]),\n \"box_extract\": OpSpec(name=\"box_extract\", code=186, immediates=[]),\n \"box_replace\": OpSpec(name=\"box_replace\", code=187, immediates=[]),\n \"box_del\": OpSpec(name=\"box_del\", code=188, immediates=[]),\n \"box_len\": OpSpec(name=\"box_len\", code=189, immediates=[]),\n \"box_get\": OpSpec(name=\"box_get\", code=190, immediates=[]),\n \"box_put\": OpSpec(name=\"box_put\", code=191, immediates=[]),\n \"txnas\": OpSpec(\n name=\"txnas\",\n code=192,\n immediates=[\n ImmediateEnum(\n codes={\n \"ApplicationArgs\": 26,\n \"Accounts\": 28,\n \"Assets\": 48,\n \"Applications\": 50,\n \"Logs\": 58,\n \"ApprovalProgramPages\": 64,\n \"ClearStateProgramPages\": 66,\n }\n )\n ],\n ),\n \"gtxnas\": OpSpec(\n name=\"gtxnas\",\n code=193,\n immediates=[\n ImmediateKind.uint8,\n ImmediateEnum(\n codes={\n \"ApplicationArgs\": 26,\n \"Accounts\": 28,\n \"Assets\": 48,\n \"Applications\": 50,\n \"Logs\": 58,\n \"ApprovalProgramPages\": 64,\n \"ClearStateProgramPages\": 66,\n }\n ),\n ],\n ),\n \"gtxnsas\": OpSpec(\n name=\"gtxnsas\",\n code=194,\n immediates=[\n ImmediateEnum(\n codes={\n \"ApplicationArgs\": 26,\n \"Accounts\": 28,\n \"Assets\": 48,\n \"Applications\": 50,\n \"Logs\": 58,\n \"ApprovalProgramPages\": 64,\n \"ClearStateProgramPages\": 66,\n }\n )\n ],\n ),\n \"args\": OpSpec(name=\"args\", code=195, immediates=[]),\n \"gloadss\": OpSpec(name=\"gloadss\", code=196, immediates=[]),\n \"itxnas\": OpSpec(\n name=\"itxnas\",\n code=197,\n immediates=[\n ImmediateEnum(\n codes={\n \"ApplicationArgs\": 26,\n \"Accounts\": 28,\n \"Assets\": 48,\n \"Applications\": 50,\n \"Logs\": 58,\n \"ApprovalProgramPages\": 64,\n \"ClearStateProgramPages\": 66,\n }\n )\n ],\n ),\n \"gitxnas\": OpSpec(\n name=\"gitxnas\",\n code=198,\n immediates=[\n ImmediateKind.uint8,\n ImmediateEnum(\n codes={\n \"ApplicationArgs\": 26,\n \"Accounts\": 28,\n \"Assets\": 48,\n \"Applications\": 50,\n \"Logs\": 58,\n \"ApprovalProgramPages\": 64,\n \"ClearStateProgramPages\": 66,\n }\n ),\n ],\n ),\n \"vrf_verify\": OpSpec(\n name=\"vrf_verify\", code=208, immediates=[ImmediateEnum(codes={\"VrfAlgorand\": 0})]\n ),\n \"block\": OpSpec(\n name=\"block\",\n code=209,\n immediates=[\n ImmediateEnum(\n codes={\n \"BlkSeed\": 0,\n \"BlkTimestamp\": 1,\n \"BlkProposer\": 2,\n \"BlkFeesCollected\": 3,\n \"BlkBonus\": 4,\n \"BlkBranch\": 5,\n \"BlkFeeSink\": 6,\n \"BlkProtocol\": 7,\n \"BlkTxnCounter\": 8,\n \"BlkProposerPayout\": 9,\n }\n )\n ],\n ),\n \"box_splice\": OpSpec(name=\"box_splice\", code=210, immediates=[]),\n \"box_resize\": OpSpec(name=\"box_resize\", code=211, immediates=[]),\n \"ec_add\": OpSpec(\n name=\"ec_add\",\n code=224,\n immediates=[\n ImmediateEnum(codes={\"BN254g1\": 0, \"BN254g2\": 1, \"BLS12_381g1\": 2, \"BLS12_381g2\": 3})\n ],\n ),\n \"ec_scalar_mul\": OpSpec(\n name=\"ec_scalar_mul\",\n code=225,\n immediates=[\n ImmediateEnum(codes={\"BN254g1\": 0, \"BN254g2\": 1, \"BLS12_381g1\": 2, \"BLS12_381g2\": 3})\n ],\n ),\n \"ec_pairing_check\": OpSpec(\n name=\"ec_pairing_check\",\n code=226,\n immediates=[\n ImmediateEnum(codes={\"BN254g1\": 0, \"BN254g2\": 1, \"BLS12_381g1\": 2, \"BLS12_381g2\": 3})\n ],\n ),\n \"ec_multi_scalar_mul\": OpSpec(\n name=\"ec_multi_scalar_mul\",\n code=227,\n immediates=[\n ImmediateEnum(codes={\"BN254g1\": 0, \"BN254g2\": 1, \"BLS12_381g1\": 2, \"BLS12_381g2\": 3})\n ],\n ),\n \"ec_subgroup_check\": OpSpec(\n name=\"ec_subgroup_check\",\n code=228,\n immediates=[\n ImmediateEnum(codes={\"BN254g1\": 0, \"BN254g2\": 1, \"BLS12_381g1\": 2, \"BLS12_381g2\": 3})\n ],\n ),\n \"ec_map_to\": OpSpec(\n name=\"ec_map_to\",\n code=229,\n immediates=[\n ImmediateEnum(codes={\"BN254g1\": 0, \"BN254g2\": 1, \"BLS12_381g1\": 2, \"BLS12_381g2\": 3})\n ],\n ),\n \"mimc\": OpSpec(\n name=\"mimc\",\n code=230,\n immediates=[ImmediateEnum(codes={\"BN254Mp110\": 0, \"BLS12_381Mp111\": 1})],\n ),\n}\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ussemble\/op_spec.py","language":"Python","license":"NOASSERTION","size":38713} {"code":"import enum\nfrom collections.abc import Mapping\n\nimport attrs\n\n\nclass ImmediateKind(enum.StrEnum):\n uint8 = enum.auto()\n int8 = enum.auto()\n label = enum.auto()\n varuint = enum.auto()\n bytes = enum.auto()\n\n # array types\n label_array = enum.auto()\n varuint_array = enum.auto()\n bytes_array = enum.auto()\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}.{self.name}\"\n\n\n@attrs.frozen\nclass ImmediateEnum:\n codes: Mapping[str, int]\n\n\n@attrs.frozen\nclass OpSpec:\n name: str\n code: int\n immediates: list[ImmediateKind | ImmediateEnum]\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/ussemble\/op_spec_models.py","language":"Python","license":"NOASSERTION","size":591} {"code":"import base64\nimport contextlib\nimport functools\nimport math\nimport os\nimport typing\nfrom collections.abc import Callable, Iterable, Iterator, MutableMapping, MutableSet, Sequence, Set\nfrom pathlib import Path\n\nimport attrs\n\nfrom puya.algo_constants import (\n ADDRESS_CHECKSUM_LENGTH,\n ENCODED_ADDRESS_LENGTH,\n MAX_APP_PAGE_SIZE,\n MAX_BYTES_LENGTH,\n MAX_UINT64,\n PUBLIC_KEY_HASH_LENGTH,\n)\n\n\n@attrs.frozen\nclass Address:\n address: str\n public_key: bytes = b\"\"\n check_sum: bytes = b\"\"\n is_valid: bool = False\n\n @classmethod\n def from_public_key(cls, public_key: bytes) -> typing.Self:\n check_sum = sha512_256_hash(public_key)[-ADDRESS_CHECKSUM_LENGTH:]\n address_bytes = public_key + check_sum\n address = base64.b32encode(address_bytes).decode(\"utf8\").rstrip(\"=\")\n assert len(address) == ENCODED_ADDRESS_LENGTH\n return cls(\n address=address,\n public_key=public_key,\n check_sum=check_sum,\n is_valid=True,\n )\n\n @classmethod\n def parse(cls, address: str) -> typing.Self:\n # Pad address so it's a valid b32 string\n padded_address = address + (6 * \"=\")\n if not (len(address) == ENCODED_ADDRESS_LENGTH and valid_base32(padded_address)):\n return cls(address)\n address_bytes = base64.b32decode(padded_address)\n if len(address_bytes) != PUBLIC_KEY_HASH_LENGTH + ADDRESS_CHECKSUM_LENGTH:\n return cls(address)\n\n public_key_hash = address_bytes[:PUBLIC_KEY_HASH_LENGTH]\n check_sum = address_bytes[PUBLIC_KEY_HASH_LENGTH:]\n verified_address = cls.from_public_key(public_key_hash)\n return cls(\n address=address,\n public_key=public_key_hash,\n check_sum=check_sum,\n is_valid=verified_address.check_sum == check_sum,\n )\n\n\ndef valid_base32(s: str) -> bool:\n \"\"\"check if s is a valid base32 encoding string and fits into AVM bytes type\"\"\"\n try:\n value = base64.b32decode(s)\n except ValueError:\n return False\n return valid_bytes(value)\n # regex from PyTEAL, appears to be RFC-4648\n # ^(?:[A-Z2-7]{8})*(?:([A-Z2-7]{2}([=]{6})?)|([A-Z2-7]{4}([=]{4})?)|([A-Z2-7]{5}([=]{3})?)|([A-Z2-7]{7}([=]{1})?))? # noqa: E501\n\n\ndef valid_base16(s: str) -> bool:\n try:\n value = base64.b16decode(s)\n except ValueError:\n return False\n return valid_bytes(value)\n\n\ndef valid_base64(s: str) -> bool:\n \"\"\"check if s is a valid base64 encoding string and fits into AVM bytes type\"\"\"\n try:\n value = base64.b64decode(s, validate=True)\n except ValueError:\n return False\n return valid_bytes(value)\n # regex from PyTEAL, appears to be RFC-4648\n # ^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$\n\n\ndef valid_bytes(value: bytes) -> bool:\n return len(value) <= MAX_BYTES_LENGTH\n\n\ndef valid_int64(value: int) -> bool:\n return bool(0 <= value <= MAX_UINT64)\n\n\ndef valid_address(address: str) -> bool:\n \"\"\"check if address is a valid address with checksum\"\"\"\n return Address.parse(address).is_valid\n\n\ndef sha512_256_hash(value: bytes) -> bytes:\n \"\"\"\n Returns the SHA512\/256 hash of a value. This is the hashing algorithm used\n to generate address checksums\n \"\"\"\n from Cryptodome.Hash import SHA512\n\n sha = SHA512.new(truncate=\"256\")\n sha.update(value)\n return sha.digest()\n\n\ndef method_selector_hash(method_signature: str) -> bytes:\n return sha512_256_hash(method_signature.encode(\"utf8\"))[:4]\n\n\ndef attrs_extend[T: attrs.AttrsInstance](\n new_type: type[T], base_instance: attrs.AttrsInstance, **changes: object\n) -> T:\n \"\"\"Like attrs.evolve but allows creating a related type\"\"\"\n base_type = type(base_instance)\n old_type_fields = attrs.fields_dict(base_type)\n new_type_fields = attrs.fields(new_type)\n for a in new_type_fields:\n if not a.init:\n continue\n attr_name = a.name # To deal with private attributes.\n init_name = a.alias\n if init_name not in changes and attr_name in old_type_fields:\n changes[init_name] = getattr(base_instance, attr_name)\n\n return new_type(**changes)\n\n\n@functools.cache\ndef make_path_relative_to(*, to: Path, path: Path, walk_up: bool = False) -> str:\n with contextlib.suppress(ValueError):\n path = path.relative_to(to, walk_up=walk_up)\n return normalize_path(path)\n\n\ndef make_path_relative_to_cwd(path: Path) -> str:\n return make_path_relative_to(to=Path.cwd(), path=path)\n\n\ndef unique[T](items: Iterable[T]) -> list[T]:\n return list(dict.fromkeys(items))\n\n\nclass StableSet[T](MutableSet[T]):\n __slots__ = (\"_data\",)\n\n def __init__(self, *items: T) -> None:\n self._data = dict.fromkeys(items)\n\n @classmethod\n def from_iter(cls, items: Iterable[T]) -> \"StableSet[T]\":\n result = StableSet.__new__(StableSet)\n result._data = dict.fromkeys(items) # noqa: SLF001\n return result\n\n def __eq__(self, other: object) -> bool:\n if isinstance(other, StableSet):\n return self._data.__eq__(other._data)\n else:\n return self._data.keys() == other\n\n def __ne__(self, other: object) -> bool:\n if isinstance(other, StableSet):\n return self._data.__ne__(other._data)\n else:\n return self._data.keys() != other\n\n def __contains__(self, x: object) -> bool:\n return self._data.__contains__(x)\n\n def __len__(self) -> int:\n return self._data.__len__()\n\n def __iter__(self) -> Iterator[T]:\n return self._data.__iter__()\n\n def add(self, value: T) -> None:\n self._data[value] = None\n\n def discard(self, value: T) -> None:\n self._data.pop(value, None)\n\n def intersection(self, other: Iterable[T]) -> \"StableSet[T]\":\n result = StableSet.__new__(StableSet)\n result._data = dict.fromkeys(k for k in self._data if k in other) # noqa: SLF001\n return result\n\n def __or__(self, other: Iterable[T]) -> \"StableSet[T]\": # type: ignore[override]\n result = StableSet.__new__(StableSet)\n if isinstance(other, StableSet):\n other_data = other._data\n else:\n other_data = dict.fromkeys(other)\n result._data = self._data | other_data\n return result\n\n def __ior__(self, other: Iterable[T]) -> typing.Self: # type: ignore[override]\n if isinstance(other, StableSet):\n other_data = other._data\n else:\n other_data = dict.fromkeys(other)\n self._data |= other_data\n return self\n\n def __sub__(self, other: Set[T]) -> \"StableSet[T]\":\n result = StableSet.__new__(StableSet)\n if isinstance(other, StableSet):\n data: Iterable[T] = self._data.keys() - other._data.keys()\n else:\n data = (k for k in self._data if k not in other)\n result._data = dict.fromkeys(data)\n return result\n\n def __repr__(self) -> str:\n return type(self).__name__ + \"(\" + \", \".join(map(repr, self._data)) + \")\"\n\n\ndef lazy_setdefault[T, U](m: MutableMapping[T, U], \/, key: T, default: Callable[[T], U]) -> U:\n \"\"\"dict.setdefault, but with a callable\"\"\"\n try:\n return m[key]\n except KeyError:\n pass\n value = default(key)\n m[key] = value\n return value\n\n\n_INVERT_ORDERED_BINARY_OP = str.maketrans(\"<>\", \"><\")\n\n\ndef invert_ordered_binary_op(op: str) -> str:\n return op.translate(_INVERT_ORDERED_BINARY_OP)\n\n\ndef clamp(value: int, *, low: int, high: int) -> int:\n if value < low:\n return low\n if value > high:\n return high\n return value\n\n\ndef bits_to_bytes(bit_size: int) -> int:\n return int(math.ceil(bit_size \/ 8))\n\n\ndef round_bits_to_nearest_bytes(bit_size: int) -> int:\n return bits_to_bytes(bit_size) * 8\n\n\n@contextlib.contextmanager\ndef pushd(new_dir: Path) -> Iterator[None]:\n orig_dir = Path.cwd()\n os.chdir(new_dir)\n try:\n yield\n finally:\n os.chdir(orig_dir)\n\n\ndef normalise_path_to_str(path: Path) -> str:\n return str(path).replace(\"\\\\\", \"\/\")\n\n\ndef biguint_bytes_eval(value: int) -> bytes:\n byte_length = math.ceil(value.bit_length() \/ 8.0)\n assert byte_length <= 64, \"Biguints must be 64 bytes or less\"\n big_uint_bytes = value.to_bytes(byteorder=\"big\", length=byte_length)\n return big_uint_bytes\n\n\ndef calculate_extra_program_pages(approval_program_length: int, clear_program_length: int) -> int:\n total_bytes = approval_program_length + clear_program_length\n return (total_bytes - 1) \/\/ MAX_APP_PAGE_SIZE\n\n\n@typing.overload\ndef coalesce[T](arg1: T | None, arg2: T, \/) -> T: ...\n\n\n@typing.overload\ndef coalesce[T](arg1: T | None, arg2: T | None, arg3: T, \/) -> T: ...\n\n\n@typing.overload\ndef coalesce[T](*args: T | None) -> T | None: ...\n\n\ndef coalesce[T](*args: T | None) -> T | None:\n \"\"\"Shorthand for `a if a is not None else b`, with eager evaluation as a tradeoff\"\"\"\n # REFACTOR: if there's a better way to do the above overloads, we should.\n # the problem is you can't have a positional argument after *args,\n # and we want to take the last one's type separately\n for arg in args:\n if arg is not None:\n return arg\n return None\n\n\ndef positive_index[T](idx: int, seq: Sequence[T]) -> int:\n return idx if idx >= 0 else len(seq) + idx\n\n\ndef set_add[T](set_: MutableSet[T], value: T) -> bool:\n \"\"\"ensure item exists in a set, returning if it was added or not\"\"\"\n added = value not in set_\n set_.add(value)\n return added\n\n\ndef set_remove[T](set_: MutableSet[T], value: T) -> bool:\n removed = value in set_\n set_.discard(value)\n return removed\n\n\ndef normalize_path(path: Path) -> str:\n return str(path).replace(os.sep, \"\/\")\n","repo_name":"algorandfoundation\/puya","path":"src\/puya\/utils.py","language":"Python","license":"NOASSERTION","size":9783} {"code":"import pathlib\nimport sys\n\n_VENDOR_PATH = pathlib.Path(__file__).parent \/ \"_vendor\"\n\nsys.path.insert(0, str(_VENDOR_PATH))\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/__init__.py","language":"Python","license":"NOASSERTION","size":123} {"code":"import argparse\nimport typing\nfrom collections.abc import Sequence\nfrom importlib.metadata import version\nfrom pathlib import Path\n\nfrom puya.algo_constants import MAINNET_AVM_VERSION, SUPPORTED_AVM_VERSIONS\nfrom puya.log import LogLevel, configure_logging\nfrom puya.options import LocalsCoalescingStrategy\nfrom puyapy.compile import compile_to_teal\nfrom puyapy.options import PuyaPyOptions\nfrom puyapy.template import parse_template_key_value\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n prog=\"puyapy\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n parser.add_argument(\"--version\", action=\"version\", version=f\"%(prog)s {version('puyapy')}\")\n parser.add_argument(\n \"-O\",\n \"--optimization-level\",\n type=int,\n choices=[0, 1, 2],\n default=1,\n help=\"Set optimization level of output TEAL \/ AVM bytecode\",\n )\n parser.add_argument(\n \"--output-teal\",\n action=argparse.BooleanOptionalAction,\n default=True,\n help=\"Output TEAL code\",\n )\n parser.add_argument(\n \"--output-source-map\",\n action=argparse.BooleanOptionalAction,\n default=True,\n help=\"Output debug source maps\",\n )\n parser.add_argument(\n \"--output-arc32\",\n action=argparse.BooleanOptionalAction,\n default=True,\n help=\"Output {contract}.arc32.json ARC-32 app spec file\",\n )\n parser.add_argument(\n \"--output-arc56\",\n action=argparse.BooleanOptionalAction,\n default=False,\n help=\"Output {contract}.arc56.json ARC-56 app spec file\",\n )\n parser.add_argument(\n \"--output-client\",\n action=argparse.BooleanOptionalAction,\n default=False,\n help=\"Output Algorand Python contract client for typed ARC4 ABI calls\",\n )\n parser.add_argument(\n \"--out-dir\", type=Path, help=\"Path for outputting artefacts\", default=False\n )\n parser.add_argument(\n \"--log-level\",\n type=LogLevel.from_string,\n choices=list(LogLevel),\n default=LogLevel.info,\n help=\"Minimum level to log to console\",\n )\n parser.add_argument(\n \"-g\", # -g chosen because it is the same option for debug in gcc\n \"--debug-level\",\n type=int,\n choices=[0, 1, 2],\n default=1,\n help=\"Output debug information level, 0 = none, 1 = debug, 2 = reserved for future use\",\n )\n parser.add_argument(\n \"--output-awst\",\n action=argparse.BooleanOptionalAction,\n default=False,\n help=\"Output parsed result of AWST\",\n )\n parser.add_argument(\n \"--output-awst-json\",\n action=argparse.BooleanOptionalAction,\n default=False,\n help=\"Output parsed result of AWST as JSON\",\n )\n parser.add_argument(\n \"--output-ssa-ir\",\n action=argparse.BooleanOptionalAction,\n default=False,\n help=\"Output IR (in SSA form) before optimisations\",\n )\n parser.add_argument(\n \"--output-optimization-ir\",\n action=argparse.BooleanOptionalAction,\n default=False,\n help=\"Output IR after each optimization\",\n )\n parser.add_argument(\n \"--output-destructured-ir\",\n action=argparse.BooleanOptionalAction,\n default=False,\n help=\"Output IR after SSA destructuring and before MIR\",\n )\n parser.add_argument(\n \"--output-memory-ir\",\n action=argparse.BooleanOptionalAction,\n default=False,\n help=\"Output MIR before lowering to TealOps\",\n )\n parser.add_argument(\n \"--output-bytecode\",\n action=argparse.BooleanOptionalAction,\n default=False,\n help=\"Output AVM bytecode\",\n )\n parser.add_argument(\n \"--match-algod-bytecode\",\n action=_EmitDeprecated,\n dest=argparse.SUPPRESS,\n nargs=0,\n help=\"Deprecated: When outputting bytecode, ensure bytecode matches algod output\",\n )\n parser.add_argument(\n \"-T\",\n \"--template-var\",\n dest=\"cli_template_definitions\",\n metavar=\"VAR=VALUE\",\n action=_ParseAndStoreTemplateVar,\n default={},\n nargs=\"+\",\n help=\"Define template vars for use when assembling via --output-bytecode\"\n \" should be specified without the prefix (see --template-vars-prefix), e.g.\"\n ' -T SOME_INT=1234 SOME_BYTES=0x1A2B SOME_BOOL=True SOME_STR=\\\\\"hello\\\\\"',\n )\n parser.add_argument(\n \"--template-vars-prefix\",\n help=\"Define the prefix to use with --template-var\",\n default=\"TMPL_\",\n )\n parser.add_argument(\n \"--target-avm-version\",\n type=int,\n choices=SUPPORTED_AVM_VERSIONS,\n default=MAINNET_AVM_VERSION,\n )\n parser.add_argument(\n \"--locals-coalescing-strategy\",\n type=LocalsCoalescingStrategy,\n choices=list(LocalsCoalescingStrategy),\n default=LocalsCoalescingStrategy.root_operand,\n help=(\n \"Strategy choice for out-of-ssa local variable coalescing. \"\n \"The best choice for your app is best determined through experimentation\"\n ),\n )\n\n parser.add_argument(\"paths\", type=Path, nargs=\"+\", metavar=\"PATH\")\n\n namespace = parser.parse_args()\n options = PuyaPyOptions(**vars(namespace))\n configure_logging(min_log_level=options.log_level)\n compile_to_teal(options)\n\n\nclass _EmitDeprecated(argparse.Action):\n @typing.override\n def __call__(\n self,\n parser: argparse.ArgumentParser,\n namespace: argparse.Namespace,\n values: str | Sequence[typing.Any] | None,\n option_string: str | None = None,\n ) -> None:\n print(f\"warning: {option_string} is deprecated and no longer does anything\") # noqa: T201\n\n\nclass _ParseAndStoreTemplateVar(argparse.Action):\n @typing.override\n def __call__(\n self,\n parser: argparse.ArgumentParser,\n namespace: argparse.Namespace,\n values: str | Sequence[typing.Any] | None,\n option_string: str | None = None,\n ) -> None:\n mapping: dict[str, int | bytes] = dict(getattr(namespace, self.dest, {}))\n lst = []\n if isinstance(values, str):\n lst = [values]\n elif values:\n for value in values:\n assert isinstance(value, str)\n lst.append(value)\n for kv in lst:\n try:\n name, value = parse_template_key_value(kv)\n except Exception as ex:\n parser.error(str(ex))\n mapping[name] = value\n setattr(namespace, self.dest, mapping)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/__main__.py","language":"Python","license":"NOASSERTION","size":6637} {"code":"# This page intentionally left blank\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/__init__.py","language":"Python","license":"NOASSERTION","size":37} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/__main__.py","language":"Python","license":"NOASSERTION","size":1061} {"code":"\"\"\"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(, , ),\nin which is what mypy normally writes to sys.stdout,\n 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/api.py","language":"Python","license":"NOASSERTION","size":2922} {"code":"from __future__ import annotations\n\nfrom typing import Callable, Iterable, Sequence\n\nimport mypy.subtypes\nfrom mypy.erasetype import erase_typevars\nfrom mypy.expandtype import expand_type\nfrom mypy.nodes import Context, TypeInfo\nfrom mypy.type_visitor import TypeTranslator\nfrom mypy.typeops import get_all_type_vars\nfrom mypy.types import (\n AnyType,\n CallableType,\n Instance,\n Parameters,\n ParamSpecFlavor,\n ParamSpecType,\n PartialType,\n ProperType,\n Type,\n TypeAliasType,\n TypeVarId,\n TypeVarLikeType,\n TypeVarTupleType,\n TypeVarType,\n UninhabitedType,\n UnpackType,\n get_proper_type,\n remove_dups,\n)\n\n\ndef get_target_type(\n tvar: TypeVarLikeType,\n type: Type,\n callable: CallableType,\n report_incompatible_typevar_value: Callable[[CallableType, Type, str, Context], None],\n context: Context,\n skip_unsatisfied: bool,\n) -> Type | None:\n p_type = get_proper_type(type)\n if isinstance(p_type, UninhabitedType) and tvar.has_default():\n return tvar.default\n if isinstance(tvar, ParamSpecType):\n return type\n if isinstance(tvar, TypeVarTupleType):\n return type\n assert isinstance(tvar, TypeVarType)\n values = tvar.values\n if values:\n if isinstance(p_type, AnyType):\n return type\n if isinstance(p_type, TypeVarType) and p_type.values:\n # Allow substituting T1 for T if every allowed value of T1\n # is also a legal value of T.\n if all(any(mypy.subtypes.is_same_type(v, v1) for v in values) for v1 in p_type.values):\n return type\n matching = []\n for value in values:\n if mypy.subtypes.is_subtype(type, value):\n matching.append(value)\n if matching:\n best = matching[0]\n # If there are more than one matching value, we select the narrowest\n for match in matching[1:]:\n if mypy.subtypes.is_subtype(match, best):\n best = match\n return best\n if skip_unsatisfied:\n return None\n report_incompatible_typevar_value(callable, type, tvar.name, context)\n else:\n upper_bound = tvar.upper_bound\n if tvar.name == \"Self\":\n # Internally constructed Self-types contain class type variables in upper bound,\n # so we need to erase them to avoid false positives. This is safe because we do\n # not support type variables in upper bounds of user defined types.\n upper_bound = erase_typevars(upper_bound)\n if not mypy.subtypes.is_subtype(type, upper_bound):\n if skip_unsatisfied:\n return None\n report_incompatible_typevar_value(callable, type, tvar.name, context)\n return type\n\n\ndef apply_generic_arguments(\n callable: CallableType,\n orig_types: Sequence[Type | None],\n report_incompatible_typevar_value: Callable[[CallableType, Type, str, Context], None],\n context: Context,\n skip_unsatisfied: bool = False,\n) -> CallableType:\n \"\"\"Apply generic type arguments to a callable type.\n\n For example, applying [int] to 'def [T] (T) -> T' results in\n 'def (int) -> int'.\n\n Note that each type can be None; in this case, it will not be applied.\n\n If `skip_unsatisfied` is True, then just skip the types that don't satisfy type variable\n bound or constraints, instead of giving an error.\n \"\"\"\n tvars = callable.variables\n assert len(orig_types) <= len(tvars)\n # Check that inferred type variable values are compatible with allowed\n # values and bounds. Also, promote subtype values to allowed values.\n # Create a map from type variable id to target type.\n id_to_type: dict[TypeVarId, Type] = {}\n\n for tvar, type in zip(tvars, orig_types):\n assert not isinstance(type, PartialType), \"Internal error: must never apply partial type\"\n if type is None:\n continue\n\n target_type = get_target_type(\n tvar, type, callable, report_incompatible_typevar_value, context, skip_unsatisfied\n )\n if target_type is not None:\n id_to_type[tvar.id] = target_type\n\n # TODO: validate arg_kinds\/arg_names for ParamSpec and TypeVarTuple replacements,\n # not just type variable bounds above.\n param_spec = callable.param_spec()\n if param_spec is not None:\n nt = id_to_type.get(param_spec.id)\n if nt is not None:\n # ParamSpec expansion is special-cased, so we need to always expand callable\n # as a whole, not expanding arguments individually.\n callable = expand_type(callable, id_to_type)\n assert isinstance(callable, CallableType)\n return callable.copy_modified(\n variables=[tv for tv in tvars if tv.id not in id_to_type]\n )\n\n # Apply arguments to argument types.\n var_arg = callable.var_arg()\n if var_arg is not None and isinstance(var_arg.typ, UnpackType):\n # Same as for ParamSpec, callable with variadic types needs to be expanded as a whole.\n callable = expand_type(callable, id_to_type)\n assert isinstance(callable, CallableType)\n return callable.copy_modified(variables=[tv for tv in tvars if tv.id not in id_to_type])\n else:\n callable = callable.copy_modified(\n arg_types=[expand_type(at, id_to_type) for at in callable.arg_types]\n )\n\n # Apply arguments to TypeGuard and TypeIs if any.\n if callable.type_guard is not None:\n type_guard = expand_type(callable.type_guard, id_to_type)\n else:\n type_guard = None\n if callable.type_is is not None:\n type_is = expand_type(callable.type_is, id_to_type)\n else:\n type_is = None\n\n # The callable may retain some type vars if only some were applied.\n # TODO: move apply_poly() logic here when new inference\n # becomes universally used (i.e. in all passes + in unification).\n # With this new logic we can actually *add* some new free variables.\n remaining_tvars: list[TypeVarLikeType] = []\n for tv in tvars:\n if tv.id in id_to_type:\n continue\n if not tv.has_default():\n remaining_tvars.append(tv)\n continue\n # TypeVarLike isn't in id_to_type mapping.\n # Only expand the TypeVar default here.\n typ = expand_type(tv, id_to_type)\n assert isinstance(typ, TypeVarLikeType)\n remaining_tvars.append(typ)\n\n return callable.copy_modified(\n ret_type=expand_type(callable.ret_type, id_to_type),\n variables=remaining_tvars,\n type_guard=type_guard,\n type_is=type_is,\n )\n\n\ndef apply_poly(tp: CallableType, poly_tvars: Sequence[TypeVarLikeType]) -> CallableType | None:\n \"\"\"Make free type variables generic in the type if possible.\n\n This will translate the type `tp` while trying to create valid bindings for\n type variables `poly_tvars` while traversing the type. This follows the same rules\n as we do during semantic analysis phase, examples:\n * Callable[Callable[[T], T], T] -> def [T] (def (T) -> T) -> T\n * Callable[[], Callable[[T], T]] -> def () -> def [T] (T -> T)\n * List[T] -> None (not possible)\n \"\"\"\n try:\n return tp.copy_modified(\n arg_types=[t.accept(PolyTranslator(poly_tvars)) for t in tp.arg_types],\n ret_type=tp.ret_type.accept(PolyTranslator(poly_tvars)),\n variables=[],\n )\n except PolyTranslationError:\n return None\n\n\nclass PolyTranslationError(Exception):\n pass\n\n\nclass PolyTranslator(TypeTranslator):\n \"\"\"Make free type variables generic in the type if possible.\n\n See docstring for apply_poly() for details.\n \"\"\"\n\n def __init__(\n self,\n poly_tvars: Iterable[TypeVarLikeType],\n bound_tvars: frozenset[TypeVarLikeType] = frozenset(),\n seen_aliases: frozenset[TypeInfo] = frozenset(),\n ) -> None:\n super().__init__()\n self.poly_tvars = set(poly_tvars)\n # This is a simplified version of TypeVarScope used during semantic analysis.\n self.bound_tvars = bound_tvars\n self.seen_aliases = seen_aliases\n\n def collect_vars(self, t: CallableType | Parameters) -> list[TypeVarLikeType]:\n found_vars = []\n for arg in t.arg_types:\n for tv in get_all_type_vars(arg):\n if isinstance(tv, ParamSpecType):\n normalized: TypeVarLikeType = tv.copy_modified(\n flavor=ParamSpecFlavor.BARE, prefix=Parameters([], [], [])\n )\n else:\n normalized = tv\n if normalized in self.poly_tvars and normalized not in self.bound_tvars:\n found_vars.append(normalized)\n return remove_dups(found_vars)\n\n def visit_callable_type(self, t: CallableType) -> Type:\n found_vars = self.collect_vars(t)\n self.bound_tvars |= set(found_vars)\n result = super().visit_callable_type(t)\n self.bound_tvars -= set(found_vars)\n\n assert isinstance(result, ProperType) and isinstance(result, CallableType)\n result.variables = 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/applytype.py","language":"Python","license":"NOASSERTION","size":12022} {"code":"\"\"\"Utilities for mapping between actual and formal arguments (and their types).\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Callable, Sequence\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/argmap.py","language":"Python","license":"NOASSERTION","size":11300} {"code":"from __future__ import annotations\n\nfrom collections import defaultdict\nfrom contextlib import contextmanager\nfrom typing import DefaultDict, Iterator, List, Optional, Tuple, Union, cast\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 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, Type] = {}\n self.unreachable = False\n self.conditional_frame = conditional_frame\n self.suppress_unreachable_warnings = False\n\n def __repr__(self) -> str:\n return f\"Frame({self.id}, {self.types}, {self.unreachable}, {self.conditional_frame})\"\n\n\nAssigns = DefaultDict[Expression, List[Tuple[Type, 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\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, index: int = -1) -> None:\n self.frames[index].types[key] = type\n\n def _get(self, key: Key, index: int = -1) -> Type | 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) -> 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)\n\n def unreachable(self) -> None:\n self.frames[-1].unreachable = True\n\n def suppress_unreachable_warnings(self) -> None:\n self.frames[-1].suppress_unreachable_warnings = True\n\n def get(self, expr: Expression) -> Type | None:\n key = literal_hash(expr)\n assert key is not None, \"Internal error: binder tried to get non-literal\"\n return self._get(key)\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\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 type = resulting_values[0]\n assert type is not None\n declaration_type = get_proper_type(self.declarations.get(key))\n if isinstance(declaration_type, AnyType):\n # At this point resulting values can't contain None, see continue above\n if not all(is_same_type(type, cast(Type, t)) for t in resulting_values[1:]):\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)\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):\n self._put(key, type)\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] for f in self.frames if key in f.types and is_subtype(type, f.types[key])\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 = True\n self.options_on_return[index].append(frame)\n\n def handle_break(self) -> None:\n self.allow_jump(self.break_frames[-1])\n self.unreachable()\n\n def handle_continue(self) -> None:\n self.allow_jump(self.continue_frames[-1])\n self.unreachable()\n\n @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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/binder.py","language":"Python","license":"NOASSERTION","size":21037} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/bogus_type.py","language":"Python","license":"NOASSERTION","size":816} {"code":"\"\"\"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 typing import (\n TYPE_CHECKING,\n AbstractSet,\n Any,\n Callable,\n ClassVar,\n Dict,\n Final,\n Iterator,\n Mapping,\n NamedTuple,\n NoReturn,\n Sequence,\n TextIO,\n)\nfrom typing_extensions import TypeAlias as _TypeAlias, TypedDict\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, 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 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 errorcodes as codes\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 __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 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 # This seems the most reasonable place to tune garbage collection.\n gc.set_threshold(150 * 1000)\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 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=__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 .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\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 )\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 = 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 assert st.meta, \"Module must be either parsed or cached\"\n hash = st.meta.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\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 not manager.metastore.write(PLUGIN_SNAPSHOT_FILE, snapshot):\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 raw_quickstart: dict[str, Any] = {}\n try:\n with open(options.quickstart_file, \"rb\") as f:\n raw_quickstart = json_loads(f.read())\n\n quickstart = {}\n for file, (x, y, z) in raw_quickstart.items():\n quickstart[file] = (x, y, z)\n except Exception as e:\n print(f\"Warning: Failed to load quickstart file: {str(e)}\\n\", file=stdout)\n return quickstart\n\n\ndef read_deps_cache(manager: BuildManager, graph: Graph) -> dict[str, FgDepMeta] | None:\n \"\"\"Read and validate the fine-grained dependencies cache.\n\n See the write_deps_cache documentation for more information on\n the details of the cache.\n\n Returns None if the cache was invalid in some way.\n \"\"\"\n deps_meta = _load_json_file(\n DEPS_META_FILE,\n manager,\n log_success=\"Deps meta \",\n log_error=\"Could not load fine-grained dependency metadata: \",\n )\n if deps_meta is None:\n return None\n meta_snapshot = deps_meta[\"snapshot\"]\n # Take a snapshot of the source hashes from all 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 #\n # TODO: these `type: ignore`s wouldn't be necessary\n # if the type annotations for CacheMeta were more accurate\n # (all of these attributes can be `None`)\n if (\n m.id != id\n or m.mtime is None # type: ignore[redundant-expr]\n or m.size is None # type: ignore[redundant-expr]\n or m.dependencies is None # type: ignore[redundant-expr]\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 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) -> 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 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 }\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 ''\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 \"\"\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\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 raise CompileError(\n [\n \"mypy: can't read file '{}': {}\".format(\n self.path, 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 expr_types = set(self.type_map().values())\n symbol_types = set()\n for _, sym, _ in self.tree.local_definitions():\n if sym.type is not None:\n symbol_types.add(sym.type)\n if isinstance(sym.node, TypeInfo):\n # TypeInfo symbols have some extra relevant types.\n symbol_types.update(sym.node.bases)\n if sym.node.metaclass_type:\n symbol_types.add(sym.node.metaclass_type)\n if sym.node.typeddict_type:\n symbol_types.add(sym.node.typeddict_type)\n if sym.node.tuple_type:\n symbol_types.add(sym.node.tuple_type)\n self._patch_indirect_dependencies(\n self.type_checker().module_refs, expr_types | symbol_types\n )\n\n if self.options.dump_inference_stats:\n dump_type_stats(\n self.tree,\n self.xpath,\n modules=self.manager.modules,\n inferred=True,\n typemap=self.type_map(),\n )\n manager.report_file(self.tree, self.type_map(), self.options)\n\n self.update_fine_grained_deps(self.manager.fg_deps)\n\n if manager.options.export_ref_info:\n write_undocumented_ref_info(\n self, manager.metastore, manager.options, self.type_map()\n )\n\n self.free_state()\n if not manager.options.fine_grained_incremental and not manager.options.preserve_asts:\n free_tree(self.tree)\n self.time_spent_us += time_spent_us(t0)\n\n def free_state(self) -> None:\n if self._type_checker:\n self._type_checker.reset()\n self._type_checker = None\n\n def _patch_indirect_dependencies(self, module_refs: set[str], types: set[Type]) -> None:\n assert 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) -> 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 )\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 (\"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 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:\/\/mypy.readthedocs.io\/en\/stable\/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:\/\/mypy.readthedocs.io\/en\/stable\/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 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 if graph[id].xpath not in manager.errors.ignored_files:\n errors = manager.errors.file_messages(\n graph[id].xpath, formatter=manager.error_formatter\n )\n manager.flush_errors(manager.errors.simplify_path(graph[id].xpath), errors, False)\n graph[id].write_cache()\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/build.py","language":"Python","license":"NOASSERTION","size":144775} {"code":"\"\"\"Mypy type checker.\"\"\"\n\nfrom __future__ import annotations\n\nimport itertools\nfrom collections import defaultdict\nfrom contextlib import ExitStack, contextmanager\nfrom typing import (\n AbstractSet,\n Callable,\n Dict,\n Final,\n Generic,\n Iterable,\n Iterator,\n Mapping,\n NamedTuple,\n Optional,\n Sequence,\n Tuple,\n TypeVar,\n Union,\n cast,\n overload,\n)\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.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 is_overlapping_erased_types, is_overlapping_types, meet_types\nfrom mypy.message_registry import ErrorMessage\nfrom mypy.messages import (\n SUGGESTED_TEST_FIXTURES,\n MessageBuilder,\n append_invariance_notes,\n append_union_note,\n format_type,\n format_type_bare,\n format_type_distinctly,\n make_inferred_type_note,\n pretty_seq,\n)\nfrom mypy.mro import MroError, calculate_mro\nfrom mypy.nodes import (\n ARG_NAMED,\n ARG_POS,\n ARG_STAR,\n CONTRAVARIANT,\n COVARIANT,\n FUNC_NO_INFO,\n GDEF,\n IMPLICITLY_ABSTRACT,\n INVARIANT,\n IS_ABSTRACT,\n LDEF,\n LITERAL_TYPE,\n MDEF,\n NOT_ABSTRACT,\n 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 check_for_explicit_any, has_any_from_unimported_type, make_optional_type\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 is_literal_type_like,\n is_singleton_type,\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 LiteralType,\n NoneType,\n Overloaded,\n PartialType,\n ProperType,\n TupleType,\n Type,\n TypeAliasType,\n TypedDictType,\n TypeGuardedType,\n TypeOfAny,\n TypeTranslator,\n TypeType,\n TypeVarId,\n TypeVarLikeType,\n TypeVarTupleType,\n TypeVarType,\n UnboundType,\n UninhabitedType,\n UnionType,\n UnpackType,\n find_unpack_in_list,\n flatten_nested_unions,\n get_proper_type,\n get_proper_types,\n is_literal_type,\n is_named_instance,\n)\nfrom mypy.types_utils import is_overlapping_none, remove_optional, store_argument_type, strip_type\nfrom mypy.typetraverser import TypeTraverserVisitor\nfrom mypy.typevars import fill_typevars, fill_typevars_with_any, has_no_typevars\nfrom mypy.util import is_dunder, is_sunder\nfrom mypy.visitor import NodeVisitor\n\nT = TypeVar(\"T\")\n\nDEFAULT_LAST_PASS: Final = 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 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 @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 If exit_condition is set, assume it must be False on exit from the loop.\n\n Then check the else_body.\n \"\"\"\n # The outer frame accumulates the results of all iterations\n with self.binder.frame_context(can_skip=False, conditional_frame=True):\n while True:\n with self.binder.frame_context(can_skip=True, break_frame=2, continue_frame=1):\n self.accept(body)\n if not self.binder.last_pop_changed:\n break\n if exit_condition:\n _, else_map = self.find_isinstance_check(exit_condition)\n self.push_type_map(else_map)\n if else_body:\n self.accept(else_body)\n\n #\n # Definitions\n #\n\n def visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:\n if not self.recurse_into_functions:\n return\n with self.tscope.function_scope(defn):\n self._visit_overloaded_func_def(defn)\n\n def _visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:\n num_abstract = 0\n if not defn.items:\n # In this case we have already complained about none of these being\n # valid overloads.\n return\n if len(defn.items) == 1:\n self.fail(message_registry.MULTIPLE_OVERLOADS_REQUIRED, defn)\n\n if defn.is_property:\n # HACK: Infer the type of the property.\n assert isinstance(defn.items[0], Decorator)\n self.visit_decorator(defn.items[0])\n 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\n is_descriptor_get = defn.info and defn.name == \"__get__\"\n for i, item in enumerate(defn.items):\n assert isinstance(item, Decorator)\n sig1 = self.extract_callable_type(item.var.type, item)\n if sig1 is None:\n continue\n\n for j, item2 in enumerate(defn.items[i + 1 :]):\n assert isinstance(item2, Decorator)\n sig2 = self.extract_callable_type(item2.var.type, item2)\n if sig2 is None:\n continue\n\n if not are_argument_counts_overlapping(sig1, sig2):\n continue\n\n if overload_can_never_match(sig1, sig2):\n self.msg.overloaded_signature_will_never_match(i + 1, i + j + 2, item2.func)\n elif not is_descriptor_get:\n # Note: we force mypy to check overload signatures in strict-optional mode\n # so we don't incorrectly report errors when a user tries typing an overload\n # that happens to have a 'if the argument is None' fallback.\n #\n # For example, the following is fine in strict-optional mode but would throw\n # the unsafe overlap error when strict-optional is disabled:\n #\n # @overload\n # def foo(x: None) -> int: ...\n # @overload\n # def foo(x: str) -> str: ...\n #\n # See Python 2's map function for a concrete example of this kind of overload.\n current_class = self.scope.active_class()\n type_vars = current_class.defn.type_vars if current_class else []\n with state.strict_optional_set(True):\n if is_unsafe_overlapping_overload_signatures(sig1, sig2, type_vars):\n flip_note = (\n j == 0\n and not is_unsafe_overlapping_overload_signatures(\n sig2, sig1, type_vars\n )\n and not overload_can_never_match(sig2, sig1)\n )\n self.msg.overloaded_signatures_overlap(\n i + 1, i + j + 2, flip_note, item.func\n )\n\n if impl_type is not None:\n assert defn.impl is not None\n\n # This is what we want from implementation, it should accept all arguments\n # of an overload, but the return types should go the opposite way.\n if is_callable_compatible(\n impl_type,\n sig1,\n is_compat=is_subtype,\n is_proper_subtype=False,\n is_compat_return=lambda l, r: is_subtype(r, l),\n ):\n continue\n # If the above check didn't work, we repeat some key steps in\n # is_callable_compatible() to give a better error message.\n\n # We perform a unification step that's very similar to what\n # 'is_callable_compatible' does -- the only difference is that\n # we check and see if the impl_type's return value is a\n # *supertype* of the overload alternative, not a *subtype*.\n #\n # This is to match the direction the implementation's return\n # needs to be compatible in.\n if impl_type.variables:\n impl: CallableType | None = unify_generic_callable(\n # Normalize both before unifying\n impl_type.with_unpacked_kwargs(),\n sig1.with_unpacked_kwargs(),\n ignore_return=False,\n return_constraint_direction=SUPERTYPE_OF,\n )\n if impl is None:\n self.msg.overloaded_signatures_typevar_specific(i + 1, defn.impl)\n continue\n else:\n impl = impl_type\n\n # Prevent extra noise from inconsistent use of @classmethod by copying\n # the first arg from the method being checked against.\n if sig1.arg_types and defn.info:\n impl = impl.copy_modified(arg_types=[sig1.arg_types[0]] + impl.arg_types[1:])\n\n # Is the overload alternative's arguments subtypes of the implementation's?\n if not is_callable_compatible(\n impl, sig1, is_compat=is_subtype, is_proper_subtype=False, ignore_return=True\n ):\n self.msg.overloaded_signatures_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 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 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 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 @contextmanager\n def enter_attribute_inference_context(self) -> Iterator[None]:\n old_types = self.inferred_attribute_types\n self.inferred_attribute_types = {}\n yield None\n self.inferred_attribute_types = old_types\n\n def check_func_def(\n self, defn: FuncItem, typ: CallableType, name: str | None, allow_empty: bool = False\n ) -> None:\n \"\"\"Type check a function definition.\"\"\"\n # Expand type variables with value restrictions to ordinary types.\n 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.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 msg = 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 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 # 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 # 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, AnyType))\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 def is_unannotated_any(t: Type) -> bool:\n if not isinstance(t, ProperType):\n return False\n return isinstance(t, AnyType) and t.type_of_any == TypeOfAny.unannotated\n\n has_explicit_annotation = isinstance(fdef.type, CallableType) and any(\n not is_unannotated_any(t) for t in fdef.type.arg_types + [fdef.type.ret_type]\n )\n\n 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\n and (fdef.arg_names[0] == \"self\" or fdef.arg_names[0] == \"cls\")\n ):\n self.fail(message_registry.RETURN_TYPE_EXPECTED, fdef)\n if not has_return_statement(fdef) and not fdef.is_generator:\n self.note(\n 'Use \"-> None\" if function does not return a value',\n fdef,\n code=codes.NO_UNTYPED_DEF,\n )\n else:\n self.fail(message_registry.FUNCTION_TYPE_EXPECTED, fdef)\n elif isinstance(fdef.type, CallableType):\n ret_type = get_proper_type(fdef.type.ret_type)\n if is_unannotated_any(ret_type):\n self.fail(message_registry.RETURN_TYPE_EXPECTED, fdef)\n elif fdef.is_generator:\n if is_unannotated_any(\n self.get_generator_return_type(ret_type, fdef.is_coroutine)\n ):\n self.fail(message_registry.RETURN_TYPE_EXPECTED, fdef)\n elif fdef.is_coroutine and isinstance(ret_type, Instance):\n if is_unannotated_any(self.get_coroutine_return_type(ret_type)):\n self.fail(message_registry.RETURN_TYPE_EXPECTED, fdef)\n if any(is_unannotated_any(t) for t in fdef.type.arg_types):\n self.fail(message_registry.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 )\n\n reverse_base_erased = reverse_type.arg_types[0]\n if isinstance(reverse_base_erased, TypeVarType):\n reverse_base_erased = erase_to_bound(reverse_base_erased)\n\n if is_same_type(reverse_base_erased, forward_base_erased):\n return False\n elif is_subtype(reverse_base_erased, forward_base_erased):\n first = reverse_tweaked\n second = forward_tweaked\n else:\n first = forward_tweaked\n second = reverse_tweaked\n\n current_class = self.scope.active_class()\n type_vars = current_class.defn.type_vars if current_class else []\n return is_unsafe_overlapping_overload_signatures(\n first, second, type_vars, partial_only=False\n )\n\n def check_inplace_operator_method(self, defn: FuncBase) -> None:\n \"\"\"Check an inplace operator method such as __iadd__.\n\n They cannot arbitrarily overlap with __add__.\n \"\"\"\n method = defn.name\n if method not in operators.inplace_operator_methods:\n return\n typ = bind_self(self.function_type(defn))\n cls = defn.info\n other_method = \"__\" + method[3:]\n if cls.has_readable_member(other_method):\n instance = fill_typevars(cls)\n typ2 = get_proper_type(\n self.expr_checker.analyze_external_member_access(other_method, instance, defn)\n )\n fail = False\n if isinstance(typ2, FunctionLike):\n if not is_more_general_arg_prefix(typ, typ2):\n fail = True\n else:\n # TODO overloads\n fail = True\n if fail:\n self.msg.signatures_incompatible(method, other_method, defn)\n\n def check_getattr_method(self, typ: Type, context: Context, name: str) -> None:\n if len(self.scope.stack) == 1:\n # module scope\n if name == \"__getattribute__\":\n self.fail(message_registry.MODULE_LEVEL_GETATTRIBUTE, context)\n return\n # __getattr__ is fine at the module level as of Python 3.7 (PEP 562). We could\n # show an error for Python < 3.7, but that would be annoying in code that supports\n # both 3.7 and older versions.\n method_type = CallableType(\n [self.named_type(\"builtins.str\")],\n [nodes.ARG_POS],\n [None],\n AnyType(TypeOfAny.special_form),\n self.named_type(\"builtins.function\"),\n )\n elif self.scope.active_class():\n method_type = CallableType(\n [AnyType(TypeOfAny.special_form), self.named_type(\"builtins.str\")],\n [nodes.ARG_POS, nodes.ARG_POS],\n [None, None],\n AnyType(TypeOfAny.special_form),\n self.named_type(\"builtins.function\"),\n )\n else:\n return\n if not is_subtype(typ, method_type):\n self.msg.invalid_signature_for_special_method(typ, context, name)\n\n def check_setattr_method(self, typ: Type, context: Context) -> None:\n if not self.scope.active_class():\n return\n method_type = CallableType(\n [\n AnyType(TypeOfAny.special_form),\n self.named_type(\"builtins.str\"),\n AnyType(TypeOfAny.special_form),\n ],\n [nodes.ARG_POS, nodes.ARG_POS, nodes.ARG_POS],\n [None, None, None],\n NoneType(),\n self.named_type(\"builtins.function\"),\n )\n if not is_subtype(typ, method_type):\n self.msg.invalid_signature_for_special_method(typ, context, \"__setattr__\")\n\n def check_slots_definition(self, typ: Type, context: Context) -> None:\n \"\"\"Check the type of __slots__.\"\"\"\n str_type = self.named_type(\"builtins.str\")\n expected_type = UnionType(\n [str_type, self.named_generic_type(\"typing.Iterable\", [str_type])]\n )\n self.check_subtype(\n typ,\n expected_type,\n context,\n message_registry.INVALID_TYPE_FOR_SLOTS,\n \"actual type\",\n \"expected type\",\n code=codes.ASSIGNMENT,\n )\n\n def check_match_args(self, var: Var, typ: Type, context: Context) -> None:\n \"\"\"Check that __match_args__ contains literal strings\"\"\"\n if not self.scope.active_class():\n return\n typ = get_proper_type(typ)\n if not isinstance(typ, TupleType) or not all(\n is_string_literal(item) for item in typ.items\n ):\n self.msg.note(\n \"__match_args__ must be a tuple containing string literals for checking \"\n \"of match statements to work\",\n context,\n code=codes.LITERAL_REQ,\n )\n\n def expand_typevars(\n self, defn: FuncItem, typ: CallableType\n ) -> list[tuple[FuncItem, CallableType]]:\n # TODO use generator\n subst: list[list[tuple[TypeVarId, Type]]] = []\n tvars = list(typ.variables) or []\n if defn.info:\n # Class type variables\n tvars += defn.info.defn.type_vars or []\n for tvar in tvars:\n if isinstance(tvar, TypeVarType) and tvar.values:\n subst.append([(tvar.id, value) for value in tvar.values])\n # Make a copy of the function to check for each combination of\n # value restricted type variables. (Except when running mypyc,\n # where we need one canonical version of the function.)\n if subst and not (self.options.mypyc or self.options.inspections):\n result: list[tuple[FuncItem, CallableType]] = []\n for substitutions in itertools.product(*subst):\n mapping = dict(substitutions)\n result.append((expand_func(defn, mapping), expand_type(typ, mapping)))\n return result\n else:\n return [(defn, typ)]\n\n def check_explicit_override_decorator(\n self,\n defn: FuncDef | OverloadedFuncDef,\n found_method_base_classes: list[TypeInfo] | None,\n context: Context | None = None,\n ) -> None:\n plugin_generated = False\n if defn.info and (node := defn.info.get(defn.name)) and node.plugin_generated:\n # Do not report issues for plugin generated nodes,\n # they can't realistically use `@override` for their methods.\n plugin_generated = True\n\n if (\n not plugin_generated\n and found_method_base_classes\n and not defn.is_explicit_override\n and defn.name not in (\"__init__\", \"__new__\")\n and not is_private(defn.name)\n ):\n self.msg.explicit_override_decorator_missing(\n defn.name, found_method_base_classes[0].fullname, context or defn\n )\n\n def check_method_override(\n self, defn: FuncDef | OverloadedFuncDef | Decorator\n ) -> list[TypeInfo] | None:\n \"\"\"Check if function definition is compatible with base classes.\n\n This may defer the method if a signature is not available in at least one base class.\n Return ``None`` if that happens.\n\n Return a list of base classes which contain an attribute with the method name.\n \"\"\"\n # Check against definitions in base classes.\n check_override_compatibility = defn.name not in (\n \"__init__\",\n \"__new__\",\n \"__init_subclass__\",\n \"__post_init__\",\n ) and (self.options.check_untyped_defs or not defn.is_dynamic())\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 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 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 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 = self.scope.active_self_type()\n if isinstance(mapped_typ, Overloaded) and active_self_type:\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 ) -> None:\n \"\"\"Check a method override with given signatures.\n\n Arguments:\n override: The signature of the overriding method.\n original: The signature of the original supertype method.\n name: The name of the overriding method.\n Used primarily for generating error messages.\n name_in_super: The name of the overridden in the superclass.\n Used for generating error messages only.\n supertype: The name of the supertype.\n original_class_or_static: Indicates whether the original method (from the superclass)\n is either a class method or a static method.\n override_class_or_static: Indicates whether the overriding method (from the subclass)\n is either a class method or a static method.\n node: Context node.\n \"\"\"\n # Use boolean variable to clarify code.\n fail = False\n op_method_wider_note = False\n if not is_subtype(override, original, ignore_pos_arg_names=True):\n fail = True\n elif isinstance(override, Overloaded) and self.is_forward_op_method(name):\n # Operator method overrides cannot extend the domain, as\n # this could be unsafe with reverse operator methods.\n original_domain = self.get_op_other_domain(original)\n override_domain = self.get_op_other_domain(override)\n if (\n original_domain\n and override_domain\n and not is_subtype(override_domain, original_domain)\n ):\n fail = True\n op_method_wider_note = True\n if isinstance(override, FunctionLike):\n if original_class_or_static and not override_class_or_static:\n fail = True\n elif isinstance(original, CallableType) and isinstance(override, CallableType):\n if original.type_guard is not None and override.type_guard is None:\n fail = True\n if original.type_is is not None and override.type_is is None:\n fail = True\n\n if is_private(name):\n fail = False\n\n if fail:\n emitted_msg = False\n\n offset_arguments = isinstance(override, CallableType) and override.unpack_kwargs\n # Normalize signatures, so we get better diagnostics.\n if isinstance(override, (CallableType, Overloaded)):\n override = override.with_unpacked_kwargs()\n if isinstance(original, (CallableType, Overloaded)):\n original = original.with_unpacked_kwargs()\n\n if (\n isinstance(override, CallableType)\n and isinstance(original, CallableType)\n and len(override.arg_types) == len(original.arg_types)\n and override.min_args == original.min_args\n ):\n # Give more detailed messages for the common case of both\n # signatures having the same number of arguments and no\n # overloads.\n\n # override might have its own generic function type\n # variables. If an argument or return type of override\n # does not have the correct subtyping relationship\n # with the original type even after these variables\n # are erased, then it is definitely an incompatibility.\n\n override_ids = override.type_var_ids()\n type_name = None\n 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 if isinstance(node, FuncDef) and not node.is_property:\n context: Context = node.arguments[i + len(override.bound_args)]\n else:\n context = 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\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\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_enum(self, defn: ClassDef) -> None:\n assert defn.info.is_enum\n if defn.info.fullname not in ENUM_BASES:\n for sym in defn.info.names.values():\n if (\n isinstance(sym.node, Var)\n and sym.node.has_explicit_value\n and sym.node.name == \"__members__\"\n ):\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_OVERRIDEN, 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 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: Instance | None = None\n for base in defn.info.bases:\n if enum_base is None and base.type.is_enum:\n enum_base = base\n continue\n elif enum_base is not None and not base.type.is_enum:\n self.fail(\n f'No non-enum mixin classes are allowed after \"{enum_base.str_with_options(self.options)}\"',\n defn,\n )\n break\n\n def check_enum_new(self, defn: ClassDef) -> None:\n def has_new_method(info: TypeInfo) -> bool:\n new_method = info.get(\"__new__\")\n return bool(\n new_method\n and new_method.node\n and new_method.node.fullname != \"builtins.object.__new__\"\n )\n\n has_new = False\n for base in defn.info.bases:\n candidate = False\n\n if base.type.is_enum:\n # If we have an `Enum`, then we need to check all its bases.\n candidate = any(not b.is_enum and has_new_method(b) for b in base.type.mro[1:-1])\n else:\n candidate = has_new_method(base.type)\n\n if candidate and has_new:\n self.fail(\n \"Only a single data type mixin is allowed for Enum subtypes, \"\n 'found extra \"{}\"'.format(base.str_with_options(self.options)),\n defn,\n )\n elif candidate:\n has_new = True\n\n def check_protocol_variance(self, defn: ClassDef) -> None:\n \"\"\"Check that protocol definition is compatible with declared\n variances of type variables.\n\n Note that we also prohibit declaring protocol classes as invariant\n if they are actually covariant\/contravariant, since this may break\n transitivity of subtyping, see PEP 544.\n \"\"\"\n if 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 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 for i, base in enumerate(mro):\n # Attributes defined in both the type and base are skipped.\n # Normal checks for attribute compatibility should catch any problems elsewhere.\n non_overridden_attrs = base.names.keys() - typ.names.keys()\n for name in non_overridden_attrs:\n if is_private(name):\n continue\n for base2 in mro[i + 1 :]:\n # We only need to check compatibility of attributes from classes not\n # in a subclass relationship. For subclasses, normal (single inheritance)\n # checks suffice (these are implemented elsewhere).\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, ignore_pos_arg_names=True)\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, ignore_pos_arg_names=True)\n elif first_type and second_type:\n if isinstance(first.node, Var):\n first_type = expand_self_type(first.node, first_type, fill_typevars(ctx))\n if isinstance(second.node, Var):\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 self.check_import(node)\n\n def visit_import_all(self, node: ImportAll) -> None:\n self.check_import(node)\n\n def visit_import(self, node: Import) -> None:\n self.check_import(node)\n\n def check_import(self, node: ImportBase) -> None:\n for assign in node.assignments:\n lvalue = assign.lvalues[0]\n lvalue_type, _, __ = self.check_lvalue(lvalue)\n if lvalue_type is None:\n # TODO: This is broken.\n lvalue_type = AnyType(TypeOfAny.special_form)\n assert isinstance(assign.rvalue, NameExpr)\n message = message_registry.INCOMPATIBLE_IMPORT_OF.format(assign.rvalue.name)\n self.check_simple_assignment(\n lvalue_type,\n assign.rvalue,\n node,\n msg=message,\n lvalue_name=\"local name\",\n rvalue_name=\"imported name\",\n )\n\n #\n # Statements\n #\n\n def visit_block(self, b: Block) -> None:\n if b.is_unreachable:\n # This block was marked as being unreachable during semantic analysis.\n # It turns out any blocks marked in this way are *intentionally* marked\n # as unreachable -- so we don't display an error.\n self.binder.unreachable()\n return\n for s in b.body:\n if self.binder.is_unreachable():\n if not self.should_report_unreachable_issues():\n break\n if not self.is_noop_for_reachability(s):\n self.msg.unreachable_statement(s)\n break\n else:\n self.accept(s)\n\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 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 # Avoid type checking type aliases in stubs to avoid false\n # positives about modern type syntax available in stubs such\n # as X | Y.\n if not (s.is_alias_def and self.is_stub):\n with self.enter_final_context(s.is_final_def):\n self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None, s.new_syntax)\n\n if s.is_alias_def:\n self.check_type_alias_rvalue(s)\n\n if (\n s.type is not None\n and self.options.disallow_any_unimported\n and has_any_from_unimported_type(s.type)\n ):\n if isinstance(s.lvalues[-1], TupleExpr):\n # This is a multiple assignment. Instead of figuring out which type is problematic,\n # give a generic error message.\n self.msg.unimported_type_becomes_any(\n \"A type on this line\", AnyType(TypeOfAny.special_form), s\n )\n else:\n self.msg.unimported_type_becomes_any(\"Type of variable\", s.type, s)\n check_for_explicit_any(s.type, self.options, self.is_typeshed_stub, self.msg, context=s)\n\n if len(s.lvalues) > 1:\n # Chained assignment (e.g. x = y = ...).\n # Make sure that rvalue type will not be reinferred.\n if not self.has_type(s.rvalue):\n self.expr_checker.accept(s.rvalue)\n rvalue = self.temp_node(self.lookup_type(s.rvalue), s)\n for lv in s.lvalues[:-1]:\n with self.enter_final_context(s.is_final_def):\n self.check_assignment(lv, rvalue, s.type is None)\n\n self.check_final(s)\n if (\n s.is_final_def\n and s.type\n and not has_no_typevars(s.type)\n and self.scope.active_class() is not None\n ):\n self.fail(message_registry.DEPENDENT_FINAL_IN_CLASS_BODY, s)\n\n if s.unanalyzed_type and not self.in_checked_function():\n self.msg.annotation_in_unchecked_function(context=s)\n\n def check_type_alias_rvalue(self, s: AssignmentStmt) -> None:\n with self.msg.filter_errors():\n alias_type = self.expr_checker.accept(s.rvalue)\n self.store_type(s.lvalues[-1], alias_type)\n\n def check_assignment(\n self,\n lvalue: Lvalue,\n rvalue: Expression,\n infer_lvalue_type: bool = True,\n new_syntax: bool = False,\n ) -> None:\n \"\"\"Type check a single assignment: lvalue = rvalue.\"\"\"\n if isinstance(lvalue, (TupleExpr, ListExpr)):\n self.check_assignment_to_multiple_lvalues(\n lvalue.items, rvalue, rvalue, infer_lvalue_type\n )\n else:\n self.try_infer_partial_generic_type_from_assignment(lvalue, rvalue, \"=\")\n lvalue_type, index_lvalue, inferred = self.check_lvalue(lvalue)\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 if rvalue_type and infer_lvalue_type and not isinstance(lvalue_type, PartialType):\n # Don't use type binder for definitions of special forms, like named tuples.\n if not (isinstance(lvalue, NameExpr) and lvalue.is_special_form):\n self.binder.assign_type(lvalue, rvalue_type, lvalue_type, False)\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 (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 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 ):\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 `@propery`\n if isinstance(typ, Instance):\n # When working with instances, we need to know if they contain\n # `__set__` special method. Like `@property` does.\n # This makes assigning to properties possible,\n # even without extra slot spec.\n return typ.type.get(\"__set__\") is not None\n if isinstance(typ, FunctionLike):\n return True # Can be a property, or some other magic\n if isinstance(typ, UnionType):\n return all(self.is_assignable_slot(lvalue, u) for u in typ.items)\n return False\n\n def flatten_rvalues(self, rvalues: list[Expression]) -> list[Expression]:\n \"\"\"Flatten expression list by expanding those * items that have tuple type.\n\n For each regular type item in the tuple type use a TempNode(), for an Unpack\n item use a corresponding StarExpr(TempNode()).\n \"\"\"\n new_rvalues = []\n for rv in rvalues:\n if not isinstance(rv, StarExpr):\n new_rvalues.append(rv)\n continue\n typ = get_proper_type(self.expr_checker.accept(rv.expr))\n if not isinstance(typ, TupleType):\n new_rvalues.append(rv)\n continue\n for t in typ.items:\n if not isinstance(t, UnpackType):\n new_rvalues.append(TempNode(t))\n else:\n unpacked = get_proper_type(t.type)\n if isinstance(unpacked, TypeVarTupleType):\n fallback = unpacked.upper_bound\n else:\n assert (\n isinstance(unpacked, Instance)\n and unpacked.type.fullname == \"builtins.tuple\"\n )\n fallback = unpacked\n new_rvalues.append(StarExpr(TempNode(fallback)))\n return new_rvalues\n\n def check_assignment_to_multiple_lvalues(\n self,\n lvalues: list[Lvalue],\n rvalue: Expression,\n context: Context,\n infer_lvalue_type: bool = True,\n ) -> None:\n if isinstance(rvalue, (TupleExpr, ListExpr)):\n # Recursively go into Tuple or List expression rhs instead of\n # using the type of rhs, because this allows more fine-grained\n # control in cases like: a, b = [int, str] where rhs would get\n # type List[object]\n rvalues: list[Expression] = []\n iterable_type: Type | None = None\n last_idx: int | None = None\n for idx_rval, rval in enumerate(self.flatten_rvalues(rvalue.items)):\n if isinstance(rval, StarExpr):\n typs = get_proper_type(self.expr_checker.accept(rval.expr))\n if self.type_is_iterable(typs) and isinstance(typs, Instance):\n if iterable_type is not None and iterable_type != self.iterable_item_type(\n typs, rvalue\n ):\n self.fail(message_registry.CONTIGUOUS_ITERABLE_EXPECTED, context)\n else:\n if last_idx is None or last_idx + 1 == idx_rval:\n rvalues.append(rval)\n last_idx = idx_rval\n iterable_type = self.iterable_item_type(typs, rvalue)\n else:\n self.fail(message_registry.CONTIGUOUS_ITERABLE_EXPECTED, context)\n else:\n self.fail(message_registry.ITERABLE_TYPE_EXPECTED.format(typs), context)\n else:\n rvalues.append(rval)\n iterable_start: int | None = None\n iterable_end: int | None = None\n for i, rval in enumerate(rvalues):\n if isinstance(rval, StarExpr):\n typs = get_proper_type(self.expr_checker.accept(rval.expr))\n if self.type_is_iterable(typs) and isinstance(typs, Instance):\n if iterable_start is None:\n iterable_start = i\n iterable_end = i\n if (\n iterable_start is not None\n and iterable_end is not None\n and iterable_type is not None\n ):\n iterable_num = iterable_end - iterable_start + 1\n rvalue_needed = len(lvalues) - (len(rvalues) - iterable_num)\n if rvalue_needed > 0:\n rvalues = (\n rvalues[0:iterable_start]\n + [TempNode(iterable_type) 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)\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 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)\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 # 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\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\n if defn.is_async_generator:\n self.fail(message_registry.RETURN_IN_ASYNC_GENERATOR, s)\n return\n # Returning a value of type Any is always fine.\n if isinstance(typ, AnyType):\n # (Unless you asked to be warned in that case, and the\n # function is not declared to return Any)\n if (\n self.options.warn_return_any\n and not self.current_node_deferred\n and not is_proper_subtype(AnyType(TypeOfAny.special_form), return_type)\n and not (\n defn.name in BINARY_MAGIC_METHODS\n and is_literal_not_implemented(s.expr)\n )\n and not (\n isinstance(return_type, Instance)\n and return_type.type.fullname == \"builtins.object\"\n )\n and not is_lambda\n ):\n self.msg.incorrectly_returning_any(return_type, s)\n return\n\n # Disallow return expressions in functions declared to return\n # None, subject to two exceptions below.\n if declared_none_return:\n # Lambdas are allowed to have None returns.\n # Functions returning a value of type None are allowed to have a None return.\n if is_lambda or isinstance(typ, NoneType):\n return\n self.fail(message_registry.NO_RETURN_VALUE_EXPECTED, s)\n else:\n self.check_subtype(\n subtype_label=\"got\",\n subtype=typ,\n supertype_label=\"expected\",\n supertype=return_type,\n context=s.expr,\n outer_context=s,\n msg=message_registry.INCOMPATIBLE_RETURN_VALUE_TYPE,\n )\n else:\n # Empty returns are valid in Generators with Any typed returns, but not in\n # coroutines.\n if (\n defn.is_generator\n and not defn.is_coroutine\n and isinstance(return_type, AnyType)\n ):\n return\n\n if isinstance(return_type, (NoneType, AnyType)):\n return\n\n if self.in_checked_function():\n self.fail(message_registry.RETURN_VALUE_EXPECTED, s)\n\n def visit_if_stmt(self, s: IfStmt) -> None:\n \"\"\"Type check an if statement.\"\"\"\n # This frame records the knowledge from previous if\/elif clauses not being taken.\n # Fall-through to the original frame is handled explicitly in each block.\n with self.binder.frame_context(can_skip=False, conditional_frame=True, fall_through=0):\n for e, b in zip(s.expr, s.body):\n t = get_proper_type(self.expr_checker.accept(e))\n\n if isinstance(t, DeletedType):\n self.msg.deleted_as_rvalue(t, s)\n\n if_map, else_map = self.find_isinstance_check(e)\n\n # XXX Issue a warning if condition is always False?\n with self.binder.frame_context(can_skip=True, fall_through=2):\n self.push_type_map(if_map)\n self.accept(b)\n\n # XXX Issue a warning if condition is always True?\n self.push_type_map(else_map)\n\n with self.binder.frame_context(can_skip=False, fall_through=2):\n if s.else_body:\n self.accept(s.else_body)\n\n def visit_while_stmt(self, s: WhileStmt) -> None:\n \"\"\"Type check a while statement.\"\"\"\n if_stmt = IfStmt([s.expr], [s.body], None)\n if_stmt.set_line(s)\n self.accept_loop(if_stmt, s.else_body, exit_condition=s.expr)\n\n def visit_operator_assignment_stmt(self, s: OperatorAssignmentStmt) -> None:\n \"\"\"Type check an operator assignment statement, e.g. x += 1.\"\"\"\n self.try_infer_partial_generic_type_from_assignment(s.lvalue, s.rvalue, s.op)\n if isinstance(s.lvalue, MemberExpr):\n # Special case, some additional errors may be given for\n # assignments to read-only or final attributes.\n lvalue_type = self.expr_checker.visit_member_expr(s.lvalue, True)\n else:\n lvalue_type = self.expr_checker.accept(s.lvalue)\n inplace, method = infer_operator_assignment_method(lvalue_type, s.op)\n if inplace:\n # There is __ifoo__, treat as x = x.__ifoo__(y)\n rvalue_type, method_type = self.expr_checker.check_op(method, lvalue_type, s.rvalue, s)\n if not is_subtype(rvalue_type, lvalue_type):\n self.msg.incompatible_operator_assignment(s.op, s)\n else:\n # There is no __ifoo__, treat as x = x 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(else_map, s.msg, None)\n self.push_type_map(true_map)\n\n def visit_raise_stmt(self, s: RaiseStmt) -> None:\n \"\"\"Type check a raise statement.\"\"\"\n if s.expr:\n self.type_check_raise(s.expr, s)\n if s.from_expr:\n self.type_check_raise(s.from_expr, s, optional=True)\n self.binder.unreachable()\n\n def type_check_raise(self, e: Expression, s: RaiseStmt, optional: bool = False) -> None:\n typ = get_proper_type(self.expr_checker.accept(e))\n if isinstance(typ, DeletedType):\n self.msg.deleted_as_rvalue(typ, e)\n return\n\n exc_type = self.named_type(\"builtins.BaseException\")\n expected_type_items = [exc_type, TypeType(exc_type)]\n if optional:\n # This is used for `x` part in a case like `raise e from x`,\n # where we allow `raise e from None`.\n expected_type_items.append(NoneType())\n\n self.check_subtype(\n typ, UnionType.make_union(expected_type_items), s, message_registry.INVALID_EXCEPTION\n )\n\n if isinstance(typ, FunctionLike):\n # https:\/\/github.com\/python\/mypy\/issues\/11089\n self.expr_checker.check_call(typ, [], [], e)\n\n 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 s.expr.accept(self.expr_checker)\n for elt in flatten(s.expr):\n if isinstance(elt, NameExpr):\n self.binder.assign_type(\n elt, DeletedType(source=elt.name), get_declaration(elt), 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=e)\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\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)\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)\n if pattern_map:\n for expr, typ in pattern_map.items():\n self.push_type_map(self._get_recursive_sub_patterns_map(expr, typ))\n self.push_type_map(pattern_type.captures)\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)\n self.accept(b)\n else:\n self.accept(b)\n self.push_type_map(else_map)\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(self, type_maps: list[TypeMap]) -> dict[Var, Type]:\n all_captures: dict[Var, 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 isinstance(node, Var)\n all_captures[node].append((expr, typ))\n\n inferred_types: dict[Var, 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 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(self, type_map: TypeMap, inferred_types: dict[Var, Type]) -> None:\n if type_map:\n for expr, typ in list(type_map.items()):\n if isinstance(expr, NameExpr):\n node = expr.node\n assert isinstance(node, Var)\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 with self.msg.filter_errors():\n self.expr_checker.accept(o.value)\n\n def make_fake_typeinfo(\n self,\n curr_module_fullname: str,\n class_gen_name: str,\n class_short_name: str,\n bases: list[Instance],\n ) -> tuple[ClassDef, TypeInfo]:\n # Build the fake ClassDef and TypeInfo together.\n # The ClassDef is full of lies and doesn't actually contain a body.\n # Use format_bare to generate a nice name for error messages.\n # We skip fully filling out a handful of TypeInfo fields because they\n # should be irrelevant for a generated type like this:\n # is_protocol, protocol_members, is_abstract\n cdef = ClassDef(class_short_name, Block([]))\n cdef.fullname = curr_module_fullname + \".\" + class_gen_name\n info = TypeInfo(SymbolTable(), cdef, curr_module_fullname)\n cdef.info = info\n info.bases = bases\n calculate_mro(info)\n info.metaclass_type = info.calculate_metaclass_type()\n return cdef, info\n\n def intersect_instances(\n self, instances: tuple[Instance, Instance], errors: list[tuple[str, str]]\n ) -> Instance | None:\n \"\"\"Try creating an ad-hoc intersection of the given instances.\n\n Note that this function does *not* try and create a full-fledged\n intersection type. Instead, it returns an instance of a new ad-hoc\n subclass of the given instances.\n\n This is mainly useful when you need a way of representing some\n theoretical subclass of the instances the user may be trying to use\n the generated intersection can serve as a placeholder.\n\n This function will create a fresh subclass 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_], \"and\")\n short_name = f\"\"\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 = pretty_seq(\n format_type_distinctly(*base_classes, options=self.options, bare=True), \"and\"\n )\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 Instance(info, [], extra_attrs=instances[0].extra_attrs or instances[1].extra_attrs)\n\n def intersect_instance_callable(self, typ: Instance, callable_type: CallableType) -> Instance:\n \"\"\"Creates a fake type that represents the intersection of an Instance and a CallableType.\n\n It operates by creating a bare-minimum dummy TypeInfo that\n subclasses type and adds a __call__ method matching callable_type.\n \"\"\"\n\n # In order for this to work in incremental mode, the type we generate needs to\n # have a valid fullname and a corresponding entry in a symbol table. We generate\n # a unique name inside the symbol table of the current module.\n cur_module = self.scope.stack[0]\n assert isinstance(cur_module, MypyFile)\n gen_name = gen_unique_name(f\"\", 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 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 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) and len(node.args) != 0:\n expr = collapse_walrus(node.args[0])\n if refers_to_fullname(node.callee, \"builtins.isinstance\"):\n if len(node.args) != 2: # the error will be reported elsewhere\n return {}, {}\n if literal(expr) == LITERAL_TYPE:\n return conditional_types_to_typemaps(\n expr,\n *self.conditional_types_with_intersection(\n self.lookup_type(expr), self.get_isinstance_type(node.args[1]), expr\n ),\n )\n elif refers_to_fullname(node.callee, \"builtins.issubclass\"):\n if len(node.args) != 2: # the error will be reported elsewhere\n return {}, {}\n if literal(expr) == LITERAL_TYPE:\n return self.infer_issubclass_maps(node, expr)\n elif refers_to_fullname(node.callee, \"builtins.callable\"):\n if len(node.args) != 1: # the error will be reported elsewhere\n return {}, {}\n if literal(expr) == LITERAL_TYPE:\n vartype = self.lookup_type(expr)\n return self.conditional_callable_type_map(expr, vartype)\n elif refers_to_fullname(node.callee, \"builtins.hasattr\"):\n if len(node.args) != 2: # the error will be reported elsewhere\n return {}, {}\n attr = try_getting_str_literals(node.args[1], self.lookup_type(node.args[1]))\n if literal(expr) == LITERAL_TYPE and attr and len(attr) == 1:\n return self.hasattr_type_maps(expr, self.lookup_type(expr), attr[0])\n elif isinstance(node.callee, RefExpr):\n if node.callee.type_guard is not None or node.callee.type_is is not None:\n # TODO: Follow *args, **kwargs\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(\n \"__call__\", called_type, called_type, is_operator=True\n )\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 = (\n \"guard\" if node.callee.type_guard is not None else \"narrower\"\n )\n self.fail(\n message_registry.TYPE_GUARD_POS_ARG_REQUIRED.format(kind), node\n )\n return {}, {}\n if literal(expr) == LITERAL_TYPE:\n # Note: we wrap the target type, so that we can special case later.\n # Namely, for isinstance() we use a normal meet, while TypeGuard is\n # considered \"always right\" (i.e. even if the types are not overlapping).\n # Also note that a care must be taken to unwrap this back at read places\n # where we use this to narrow down declared type.\n if node.callee.type_guard is not None:\n return {expr: TypeGuardedType(node.callee.type_guard)}, {}\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 elif isinstance(node, ComparisonExpr):\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 # 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 # Strictly speaking, we should also skip this check if the objects in the expr\n # chain have custom __eq__ or __ne__ methods. But we (maybe optimistically)\n # assume nobody would actually create a custom objects that considers itself\n # equal to None.\n if if_map == {} and else_map == {}:\n if_map, else_map = self.refine_away_none_in_comparison(\n operands,\n operand_types,\n expr_indices,\n 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 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(\n builtin_item_type(iterable_type)\n )\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 elif isinstance(node, AssignmentExpr):\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 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 ''), this distinction is also moot: mypy\n # currently will just mark the whole branch as unreachable if either operand is\n # narrowed to .\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 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 # Make sure we have a mixture of optional and non-optional types.\n if len(non_optional_types) == 0 or len(non_optional_types) == len(chain_indices):\n return {}, {}\n\n if_map = {}\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 return if_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) -> None:\n if type_map is None:\n self.binder.unreachable()\n else:\n for expr, type in type_map.items():\n self.binder.put(expr, type)\n\n def infer_issubclass_maps(self, node: CallExpr, expr: Expression) -> tuple[TypeMap, TypeMap]:\n \"\"\"Infer type restrictions for an expression in issubclass call.\"\"\"\n vartype = self.lookup_type(expr)\n type = self.get_isinstance_type(node.args[1])\n if isinstance(vartype, TypeVarType):\n vartype = vartype.upper_bound\n vartype = get_proper_type(vartype)\n if isinstance(vartype, UnionType):\n union_list = []\n for t in get_proper_types(vartype.items):\n if isinstance(t, TypeType):\n union_list.append(t.item)\n else:\n # This is an error that should be reported earlier\n # if we reach here, we refuse to do any type inference.\n return {}, {}\n vartype = UnionType(union_list)\n elif isinstance(vartype, TypeType):\n vartype = vartype.item\n elif isinstance(vartype, Instance) and vartype.type.is_metaclass():\n vartype = self.named_type(\"builtins.object\")\n else:\n # Any other object whose type we don't know precisely\n # for example, Any or a custom metaclass.\n return {}, {} # unknown type\n yes_type, no_type = self.conditional_types_with_intersection(vartype, type, expr)\n yes_map, no_map = conditional_types_to_typemaps(expr, yes_type, no_type)\n yes_map, no_map = map(convert_to_typetype, (yes_map, no_map))\n return yes_map, no_map\n\n @overload\n def conditional_types_with_intersection(\n self,\n expr_type: Type,\n type_ranges: list[TypeRange] | None,\n ctx: Context,\n default: None = None,\n ) -> tuple[Type | None, Type | None]: ...\n\n @overload\n def conditional_types_with_intersection(\n self, expr_type: Type, type_ranges: list[TypeRange] | None, ctx: Context, default: Type\n ) -> tuple[Type, Type]: ...\n\n def conditional_types_with_intersection(\n self,\n expr_type: Type,\n type_ranges: list[TypeRange] | None,\n ctx: Context,\n default: Type | None = None,\n ) -> tuple[Type | None, Type | None]:\n initial_types = conditional_types(expr_type, type_ranges, default)\n # For some reason, doing \"yes_map, no_map = conditional_types_to_typemaps(...)\"\n # doesn't work: mypyc will decide that 'yes_map' is of type None if we try.\n yes_type: Type | None = initial_types[0]\n no_type: Type | None = initial_types[1]\n\n if not isinstance(get_proper_type(yes_type), UninhabitedType) or type_ranges is None:\n return yes_type, no_type\n\n # If conditional_types was unable to successfully narrow the expr_type\n # using the type_ranges and concluded if-branch is unreachable, we try\n # computing it again using a different algorithm that tries to generate\n # an ad-hoc intersection between the expr_type and the type_ranges.\n proper_type = get_proper_type(expr_type)\n if isinstance(proper_type, UnionType):\n possible_expr_types = get_proper_types(proper_type.relevant_items())\n else:\n possible_expr_types = [proper_type]\n\n possible_target_types = []\n for tr in type_ranges:\n item = get_proper_type(tr.item)\n if isinstance(item, (Instance, NoneType)):\n possible_target_types.append(item)\n if not possible_target_types:\n return yes_type, no_type\n\n out = []\n errors: list[tuple[str, str]] = []\n for v in possible_expr_types:\n if not isinstance(v, Instance):\n return yes_type, no_type\n for t in possible_target_types:\n if isinstance(t, NoneType):\n errors.append((f'\"{v.type.name}\" and \"NoneType\"', '\"NoneType\" is final'))\n continue\n intersection = self.intersect_instances((v, t), errors)\n if intersection is None:\n continue\n out.append(intersection)\n if not out:\n # Only report errors if no element in the union worked.\n if self.should_report_unreachable_issues():\n for types, reason in errors:\n self.msg.impossible_intersection(types, reason, ctx)\n return UninhabitedType(), expr_type\n new_yes_type = make_simplified_union(out)\n return new_yes_type, expr_type\n\n def is_writable_attribute(self, node: Node) -> bool:\n \"\"\"Check if an attribute is writable\"\"\"\n if isinstance(node, Var):\n if node.is_property and not node.is_settable_property:\n return False\n return True\n elif isinstance(node, OverloadedFuncDef) and node.is_property:\n first_item = node.items[0]\n assert isinstance(first_item, Decorator)\n return first_item.var.is_settable_property\n return False\n\n def get_isinstance_type(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\nclass CollectArgTypeVarTypes(TypeTraverserVisitor):\n \"\"\"Collects the non-nested argument types in a set.\"\"\"\n\n def __init__(self) -> None:\n self.arg_types: set[TypeVarType] = set()\n\n def visit_type_var(self, t: TypeVarType) -> None:\n self.arg_types.add(t)\n\n\n@overload\ndef conditional_types(\n current_type: Type, proposed_type_ranges: list[TypeRange] | None, default: None = None\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\n) -> tuple[Type, Type]: ...\n\n\ndef conditional_types(\n current_type: Type, proposed_type_ranges: list[TypeRange] | None, default: Type | None = None\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, prohibit_none_typevar_overlap=True, ignore_promotions=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(current_type, proposed_precise_type)\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, 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 ignore_pos_arg_names=True,\n )\n\n\ndef infer_operator_assignment_method(typ: Type, operator: str) -> tuple[bool, str]:\n \"\"\"Determine if operator assignment on given value type is in-place, and the method name.\n\n For example, if operator is '+', return (True, '__iadd__') or (False, '__add__')\n depending on which method is supported by the type.\n \"\"\"\n typ = get_proper_type(typ)\n method = operators.op_methods[operator]\n existing_method = None\n if isinstance(typ, Instance):\n existing_method = _find_inplace_method(typ, method, operator)\n elif isinstance(typ, TypedDictType):\n existing_method = _find_inplace_method(typ.fallback, method, operator)\n\n if existing_method is not None:\n return True, existing_method\n return False, method\n\n\ndef _find_inplace_method(inst: Instance, method: str, operator: str) -> str | None:\n if operator in operators.ops_with_inplace_method:\n inplace_method = \"__i\" + method[2:]\n if inst.type.has_readable_member(inplace_method):\n return inplace_method\n return None\n\n\ndef is_valid_inferred_type(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[].\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 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 ComparisionExpr'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 (\"\")\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(\"\")\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(\"\")\n return result\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/checker.py","language":"Python","license":"NOASSERTION","size":389651} {"code":"\"\"\"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 contextlib import contextmanager\nfrom typing import Callable, ClassVar, Final, Iterable, Iterator, List, Optional, Sequence, cast\nfrom typing_extensions import TypeAlias as _TypeAlias, assert_never, overload\n\nimport mypy.checker\nimport mypy.errorcodes as codes\nfrom mypy import applytype, erasetype, join, message_registry, nodes, operators, types\nfrom mypy.argmap import ArgTypeExpander, map_actuals_to_formals, map_formals_to_actuals\nfrom mypy.checkmember import analyze_member_access, freeze_all_type_vars, type_object_type\nfrom mypy.checkstrformat import StringFormatterChecker\nfrom mypy.erasetype import erase_type, remove_instance_last_known_values, replace_meta_vars\nfrom mypy.errors import 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\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 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_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 LiteralType,\n LiteralValue,\n NoneType,\n Overloaded,\n Parameters,\n ParamSpecFlavor,\n ParamSpecType,\n PartialType,\n ProperType,\n TupleType,\n Type,\n TypeAliasType,\n TypedDictType,\n TypeOfAny,\n TypeType,\n TypeVarId,\n TypeVarTupleType,\n TypeVarType,\n UnboundType,\n UninhabitedType,\n UnionType,\n UnpackType,\n find_unpack_in_list,\n flatten_nested_tuples,\n flatten_nested_unions,\n get_proper_type,\n get_proper_types,\n has_recursive_types,\n 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 return self.narrow_type_from_binder(e, result)\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 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.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 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.implicit\n and callee_type.name != LAMBDA_NAME\n ):\n if fullname is None and member is not None:\n assert object_type is not None\n fullname = self.method_fullname(object_type, member)\n if not fullname or not any(\n fullname == p or fullname.startswith(f\"{p}.\")\n for p in self.chk.options.untyped_calls_exclude\n ):\n self.msg.untyped_function_call(callee_type, e)\n\n ret_type = self.check_call_expr_with_callee_type(\n callee_type, e, fullname, object_type, member\n )\n if isinstance(e.callee, RefExpr) and len(e.args) == 2:\n if e.callee.fullname in (\"builtins.isinstance\", \"builtins.issubclass\"):\n self.check_runtime_protocol_test(e)\n if e.callee.fullname == \"builtins.issubclass\":\n self.check_protocol_issubclass(e)\n if isinstance(e.callee, MemberExpr) and e.callee.name == \"format\":\n self.check_str_format_call(e)\n ret_type = get_proper_type(ret_type)\n if isinstance(ret_type, UnionType):\n ret_type = make_simplified_union(ret_type.items)\n if isinstance(ret_type, UninhabitedType) and not ret_type.ambiguous:\n self.chk.binder.unreachable()\n # Warn on calls to functions that always return None. The check\n # of ret_type is both a common-case optimization and prevents reporting\n # the error in dynamic functions (where it will be Any).\n if (\n not allow_none_return\n and isinstance(ret_type, NoneType)\n and self.always_returns_none(e.callee)\n ):\n self.chk.msg.does_not_return_value(callee_type, e)\n return AnyType(TypeOfAny.from_error)\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, 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 overriden 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, RefExpr) and isinstance(proper_callee, CallableType):\n # Cache it for find_isinstance_check()\n if proper_callee.type_guard is not None:\n e.callee.type_guard = proper_callee.type_guard\n if proper_callee.type_is is not None:\n e.callee.type_is = proper_callee.type_is\n return ret_type\n\n def check_union_call_expr(self, e: CallExpr, object_type: UnionType, member: str) -> Type:\n \"\"\"Type check calling a member expression where the base type is a union.\"\"\"\n res: list[Type] = []\n for typ in 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, Instance):\n call_function = analyze_member_access(\n \"__call__\",\n callee,\n context,\n is_lvalue=False,\n is_super=False,\n is_operator=True,\n 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 = [AnyType(TypeOfAny.unannotated)] * len(callee_type.variables)\n return self.apply_inferred_arguments(callee_type, inferred_args, context)\n\n def infer_function_type_arguments_pass2(\n self,\n callee_type: CallableType,\n args: list[Expression],\n arg_kinds: list[ArgKind],\n arg_names: Sequence[str | None] | None,\n formal_to_actual: list[list[int]],\n old_inferred_args: Sequence[Type | None],\n need_refresh: bool,\n context: Context,\n ) -> tuple[CallableType, list[Type | None]]:\n \"\"\"Perform second pass of generic function type argument inference.\n\n The second pass is needed for arguments with types such as Callable[[T], S],\n where both T and S are type variables, when the actual argument is a\n lambda with inferred types. The idea is to infer the type variable T\n in the first pass (based on the types of other arguments). This lets\n us infer the argument and return type of the lambda expression and\n thus also the type variable S in this second pass.\n\n Return (the callee with type vars applied, inferred actual arg types).\n \"\"\"\n # None or erased types in inferred types mean that there was not enough\n # information to infer the argument. Replace them with None values so\n # that they are not applied yet below.\n inferred_args = list(old_inferred_args)\n for i, arg in enumerate(get_proper_types(inferred_args)):\n if isinstance(arg, (NoneType, UninhabitedType)) or has_erased_component(arg):\n inferred_args[i] = None\n callee_type = self.apply_generic_arguments(callee_type, inferred_args, context)\n 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 callee.param_spec() is not None and not formal_to_actual[i]:\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 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 if actual_kind == nodes.ARG_STAR and not self.is_valid_var_arg(actual_type):\n self.msg.invalid_var_arg(actual_type, context)\n if actual_kind == nodes.ARG_STAR2 and not self.is_valid_keyword_var_arg(\n actual_type\n ):\n is_mapping = is_subtype(\n actual_type, self.chk.named_type(\"_typeshed.SupportsKeysAndGetItem\")\n )\n self.msg.invalid_keyword_var_arg(actual_type, is_mapping, context)\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 arg_types = self.infer_arg_types_in_empty_context(args)\n # Step 1: Filter call targets to remove ones where the argument counts don't match\n plausible_targets = self.plausible_overload_call_targets(\n arg_types, arg_kinds, arg_names, callee\n )\n\n # Step 2: If the arguments contain a union, we try performing union math first,\n # instead of picking the first matching overload.\n # This is because picking the first overload often ends up being too greedy:\n # for example, when we have a fallback alternative that accepts an unrestricted\n # typevar. See https:\/\/github.com\/python\/mypy\/issues\/4063 for related discussion.\n erased_targets: list[CallableType] | None = None\n 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, including\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 star_matches.append(typ)\n elif self.check_argument_count(\n typ, arg_types, arg_kinds, arg_names, formal_to_actual, None\n ):\n if args_have_var_arg and typ.is_var_arg:\n star_matches.append(typ)\n elif args_have_kw_arg and typ.is_kw_arg:\n star_matches.append(typ)\n else:\n matches.append(typ)\n\n return star_matches + matches\n\n def infer_overload_return_type(\n self,\n plausible_targets: list[CallableType],\n args: list[Expression],\n arg_types: list[Type],\n arg_kinds: list[ArgKind],\n arg_names: Sequence[str | None] | None,\n callable_name: str | None,\n object_type: Type | None,\n context: Context,\n ) -> tuple[Type, Type] | None:\n \"\"\"Attempts to find the first matching callable from the given list.\n\n If a match is found, returns a tuple containing the result type and the inferred\n callee type. (This tuple is meant to be eventually returned by check_call.)\n If multiple targets match due to ambiguous Any parameters, returns (AnyType, AnyType).\n If no targets match, returns None.\n\n Assumes all of the given targets have argument counts compatible with the caller.\n \"\"\"\n\n matches: list[CallableType] = []\n return_types: list[Type] = []\n inferred_types: list[Type] = []\n args_contain_any = any(map(has_any_type, arg_types))\n type_maps: list[dict[Expression, Type]] = []\n\n for typ in plausible_targets:\n assert self.msg is self.chk.msg\n with self.msg.filter_errors() as w:\n with self.chk.local_type_map() as m:\n ret_type, infer_type = self.check_call(\n callee=typ,\n args=args,\n arg_kinds=arg_kinds,\n arg_names=arg_names,\n context=context,\n callable_name=callable_name,\n object_type=object_type,\n )\n is_match = not w.has_new_errors()\n if is_match:\n # Return early if possible; otherwise record info, so we can\n # check for ambiguity due to 'Any' below.\n if not args_contain_any:\n self.chk.store_types(m)\n return ret_type, infer_type\n p_infer_type = get_proper_type(infer_type)\n if isinstance(p_infer_type, CallableType):\n # Prefer inferred types if possible, this will avoid false triggers for\n # Any-ambiguity caused by arguments with Any passed to generic overloads.\n matches.append(p_infer_type)\n else:\n matches.append(typ)\n return_types.append(ret_type)\n inferred_types.append(infer_type)\n type_maps.append(m)\n\n if not matches:\n return None\n elif any_causes_overload_ambiguity(matches, return_types, arg_types, arg_kinds, arg_names):\n # An argument of type or containing the type 'Any' caused ambiguity.\n # We try returning a precise type if we can. If not, we give up and just return 'Any'.\n if all_same_types(return_types):\n self.chk.store_types(type_maps[0])\n return return_types[0], inferred_types[0]\n elif all_same_types([erase_type(typ) for typ in return_types]):\n self.chk.store_types(type_maps[0])\n return erase_type(return_types[0]), erase_type(inferred_types[0])\n else:\n return self.check_call(\n callee=AnyType(TypeOfAny.special_form),\n args=args,\n arg_kinds=arg_kinds,\n arg_names=arg_names,\n context=context,\n callable_name=callable_name,\n object_type=object_type,\n )\n else:\n # Success! No ambiguity; return the first match.\n self.chk.store_types(type_maps[0])\n return return_types[0], inferred_types[0]\n\n def overload_erased_call_targets(\n self,\n plausible_targets: list[CallableType],\n arg_types: list[Type],\n arg_kinds: list[ArgKind],\n arg_names: Sequence[str | None] | None,\n args: list[Expression],\n context: Context,\n ) -> list[CallableType]:\n \"\"\"Returns a list of all targets that match the caller after erasing types.\n\n Assumes all of the given targets have argument counts compatible with the caller.\n \"\"\"\n matches: list[CallableType] = []\n for typ in plausible_targets:\n if self.erased_signature_similarity(\n arg_types, arg_kinds, arg_names, args, typ, context\n ):\n matches.append(typ)\n return matches\n\n def possible_none_type_var_overlap(\n self, arg_types: list[Type], plausible_targets: list[CallableType]\n ) -> bool:\n \"\"\"Heuristic to determine whether we need to try forcing union math.\n\n This is needed to avoid greedy type variable match in situations like this:\n @overload\n def foo(x: None) -> None: ...\n @overload\n def foo(x: T) -> list[T]: ...\n\n x: int | None\n foo(x)\n we want this call to infer list[int] | None, not list[int | None].\n \"\"\"\n if not plausible_targets or not arg_types:\n return False\n has_optional_arg = False\n for arg_type in get_proper_types(arg_types):\n if not isinstance(arg_type, UnionType):\n continue\n for item in get_proper_types(arg_type.items):\n if isinstance(item, NoneType):\n has_optional_arg = True\n break\n if not has_optional_arg:\n return False\n\n min_prefix = min(len(c.arg_types) for c in plausible_targets)\n for i in range(min_prefix):\n if any(\n isinstance(get_proper_type(c.arg_types[i]), NoneType) for c in plausible_targets\n ) and any(\n isinstance(get_proper_type(c.arg_types[i]), TypeVarType) for c in plausible_targets\n ):\n return True\n return False\n\n def union_overload_result(\n self,\n plausible_targets: list[CallableType],\n args: list[Expression],\n arg_types: list[Type],\n arg_kinds: list[ArgKind],\n arg_names: Sequence[str | None] | None,\n callable_name: str | None,\n object_type: Type | None,\n none_type_var_overlap: bool,\n context: Context,\n level: int = 0,\n ) -> list[tuple[Type, Type]] | None:\n \"\"\"Accepts a list of overload signatures and attempts to match calls by destructuring\n the first union.\n\n Return a list of (, ) 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[]] 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, AnyType):\n return (\n AnyType(TypeOfAny.from_another_any, source_any=callee),\n AnyType(TypeOfAny.from_another_any, source_any=callee),\n )\n else:\n return AnyType(TypeOfAny.special_form), AnyType(TypeOfAny.special_form)\n\n def check_union_call(\n self,\n callee: UnionType,\n args: list[Expression],\n arg_kinds: list[ArgKind],\n arg_names: Sequence[str | None] | None,\n context: Context,\n ) -> tuple[Type, Type]:\n with self.msg.disable_type_names():\n results = [\n self.check_call(subtype, args, arg_kinds, context, arg_names)\n for subtype in callee.relevant_items()\n ]\n\n return (make_simplified_union([res[0] for res in results]), callee)\n\n def visit_member_expr(self, e: MemberExpr, is_lvalue: bool = False) -> Type:\n \"\"\"Visit member expression (of form e.id).\"\"\"\n self.chk.module_refs.update(extract_refexpr_names(e))\n result = self.analyze_ordinary_member_access(e, is_lvalue)\n return self.narrow_type_from_binder(e, result)\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 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 = [(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 = [(right_op, right_type, left_expr), (left_op, left_type, right_expr)]\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 = [(left_op, left_type, right_expr), (right_op, right_type, left_expr)]\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 = [(op, obj, arg) for (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 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 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 # If right_map is None then we know mypy considers the right branch\n # to be unreachable and therefore any errors found in the right branch\n # should be suppressed.\n with self.msg.filter_errors(filter_errors=right_map is None):\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: [...] * . 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 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 if not self.chk.current_node_deferred:\n self.msg.reveal_type(revealed_type, expr.expr)\n if not self.chk.in_checked_function():\n self.msg.note(\n \"'reveal_type' always outputs 'Any' in unchecked functions\", expr.expr\n )\n self.check_reveal_imported(expr)\n return revealed_type\n else:\n # REVEAL_LOCALS\n if not self.chk.current_node_deferred:\n # the RevealExpr contains a local_nodes attribute,\n # calculated at semantic analysis time. Use it to pull out the\n # corresponding subset of variables in self.chk.type_map\n names_to_types = (\n {var_node.name: var_node.type for var_node in expr.local_nodes}\n if expr.local_nodes is not None\n else {}\n )\n\n self.msg.reveal_locals(names_to_types, expr)\n self.check_reveal_imported(expr)\n return NoneType()\n\n def check_reveal_imported(self, expr: RevealExpr) -> None:\n if codes.UNIMPORTED_REVEAL not in self.chk.options.enabled_error_codes:\n return\n\n name = \"\"\n if expr.kind == REVEAL_LOCALS:\n name = \"reveal_locals\"\n elif expr.kind == REVEAL_TYPE and not expr.is_imported:\n name = \"reveal_type\"\n else:\n return\n\n self.chk.fail(f'Name \"{name}\" is not defined', expr, code=codes.UNIMPORTED_REVEAL)\n if name == \"reveal_type\":\n module = (\n \"typing\" if self.chk.options.python_version >= (3, 11) else \"typing_extensions\"\n )\n hint = (\n 'Did you forget to import it from \"{module}\"?'\n ' (Suggestion: \"from {module} import {name}\")'\n ).format(module=module, name=name)\n self.chk.note(hint, expr, code=codes.UNIMPORTED_REVEAL)\n\n def visit_type_application(self, tapp: TypeApplication) -> Type:\n \"\"\"Type check a type application (expr[type, ...]).\n\n There are two different options here, depending on whether expr refers\n to a type alias or directly to a generic class. In the first case we need\n to use a dedicated function typeanal.instantiate_type_alias(). This\n is due to slight differences in how type arguments are applied and checked.\n \"\"\"\n if isinstance(tapp.expr, RefExpr) and isinstance(tapp.expr.node, TypeAlias):\n if tapp.expr.node.python_3_12_type_alias:\n return self.type_alias_type_type()\n # Subscription of a (generic) alias in runtime context, expand the alias.\n item = instantiate_type_alias(\n tapp.expr.node,\n tapp.types,\n self.chk.fail,\n tapp.expr.node.no_args,\n tapp,\n self.chk.options,\n )\n item = get_proper_type(item)\n if isinstance(item, Instance):\n tp = type_object_type(item.type, self.named_type)\n return self.apply_type_arguments_to_callable(tp, item.args, tapp)\n elif isinstance(item, TupleType) and item.partial_fallback.type.is_named_tuple:\n tp = type_object_type(item.partial_fallback.type, self.named_type)\n return self.apply_type_arguments_to_callable(tp, item.partial_fallback.args, tapp)\n elif isinstance(item, TypedDictType):\n return self.typeddict_callable_from_context(item)\n else:\n self.chk.fail(message_registry.ONLY_CLASS_APPLICATION, tapp)\n return AnyType(TypeOfAny.from_error)\n # Type application of a normal generic class in runtime context.\n # This is typically used as `x = G[int]()`.\n tp = get_proper_type(self.accept(tapp.expr))\n if isinstance(tp, (CallableType, Overloaded)):\n if not tp.is_type_obj():\n self.chk.fail(message_registry.ONLY_CLASS_APPLICATION, tapp)\n return self.apply_type_arguments_to_callable(tp, tapp.types, tapp)\n if isinstance(tp, AnyType):\n return AnyType(TypeOfAny.from_another_any, source_any=tp)\n return AnyType(TypeOfAny.special_form)\n\n def visit_type_alias_expr(self, alias: TypeAliasExpr) -> Type:\n \"\"\"Right hand side of a type alias definition.\n\n It has the same type as if the alias itself was used in a runtime context.\n For example, here:\n\n A = reveal_type(List[T])\n reveal_type(A)\n\n both `reveal_type` instances will reveal the same type `def (...) -> builtins.list[Any]`.\n Note that type variables are implicitly substituted with `Any`.\n \"\"\"\n return self.alias_type_in_runtime_context(alias.node, ctx=alias, alias_definition=True)\n\n def alias_type_in_runtime_context(\n self, alias: TypeAlias, *, ctx: Context, alias_definition: bool = False\n ) -> Type:\n \"\"\"Get type of a type alias (could be generic) in a runtime expression.\n\n Note that this function can be called only if the alias appears _not_\n as a target of type application, which is treated separately in the\n visit_type_application method. Some examples where this method is called are\n casts and instantiation:\n\n class LongName(Generic[T]): ...\n A = LongName[int]\n\n x = A()\n y = cast(A, ...)\n \"\"\"\n if alias.python_3_12_type_alias:\n return self.type_alias_type_type()\n if 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 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 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\", \"\")\n\n def visit_set_expr(self, e: SetExpr) -> Type:\n return self.check_lst_expr(e, \"builtins.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=\"\"),\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\", \"\")\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\", \"\")\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=\"\"),\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=\"\"),\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 (*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=\"\",\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 self.chk.binder.frame_context(\n can_skip=True, fall_through=0\n ), self.chk.scope.push_function(e):\n # Lambdas can have more than one element in body,\n # when we add \"fictional\" AssigmentStatement 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 ret_type = self.chk.lookup_type(e.expr())\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 AnyType(TypeOfAny.unannotated)\n elif len(e.call.args) == 0:\n if not e.info:\n # This has already been reported by the semantic analyzer.\n return AnyType(TypeOfAny.from_error)\n elif self.chk.scope.active_class():\n self.chk.fail(message_registry.SUPER_OUTSIDE_OF_METHOD_NOT_SUPPORTED, e)\n return AnyType(TypeOfAny.from_error)\n\n # Zero-argument super() is like super(, )\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 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 return self.named_type(\"builtins.slice\")\n\n def visit_list_comprehension(self, e: ListComprehension) -> Type:\n return self.check_generator_or_comprehension(\n e.generator, \"builtins.list\", \"\"\n )\n\n def visit_set_comprehension(self, e: SetComprehension) -> Type:\n return self.check_generator_or_comprehension(\n e.generator, \"builtins.set\", \"\"\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, \"\", 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=\"\"),\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=\"\"),\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=\"\"),\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=\"\",\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 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 ) -> 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\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(typ)\n and not self.chk.current_node_deferred\n ):\n self.msg.disallowed_any_type(typ, node)\n\n if not self.chk.in_checked_function() or self.chk.current_node_deferred:\n result: Type = AnyType(TypeOfAny.unannotated)\n else:\n result = typ\n if record_time:\n self.per_line_checking_time_ns[node.line] += time.perf_counter_ns() - t0\n self.in_expression = False\n return result\n\n def 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(t: Type, ignore_in_type_obj: bool = False) -> bool:\n \"\"\"Whether t contains an Any type\"\"\"\n return t.accept(HasAnyType(ignore_in_type_obj))\n\n\nclass HasAnyType(types.BoolTypeQuery):\n def __init__(self, ignore_in_type_obj: bool) -> None:\n super().__init__(types.ANY_STRATEGY)\n self.ignore_in_type_obj = ignore_in_type_obj\n\n def visit_any(self, t: AnyType) -> bool:\n return t.type_of_any != TypeOfAny.special_form # special forms are not real Any types\n\n def visit_callable_type(self, t: CallableType) -> bool:\n if self.ignore_in_type_obj and t.is_type_obj():\n return False\n return super().visit_callable_type(t)\n\n def visit_type_var(self, t: TypeVarType) -> bool:\n default = [t.default] if t.has_default() else []\n return self.query_types([t.upper_bound, *default] + t.values)\n\n def visit_param_spec(self, t: ParamSpecType) -> bool:\n default = [t.default] if t.has_default() else []\n return self.query_types([t.upper_bound, *default])\n\n def visit_type_var_tuple(self, t: TypeVarTupleType) -> bool:\n default = [t.default] if t.has_default() else []\n return self.query_types([t.upper_bound, *default])\n\n\ndef has_coroutine_decorator(t: Type) -> bool:\n \"\"\"Whether t came from a function decorated with `@coroutine`.\"\"\"\n t = get_proper_type(t)\n return isinstance(t, Instance) and t.type.fullname == \"typing.AwaitableGenerator\"\n\n\ndef is_async_def(t: Type) -> bool:\n \"\"\"Whether t came from a function defined using `async def`.\"\"\"\n # In check_func_def(), when we see a function decorated with\n # `@typing.coroutine` or `@async.coroutine`, we change the\n # return type to typing.AwaitableGenerator[...], so that its\n # type is compatible with either Generator or Awaitable.\n # But for the check here we need to know whether the original\n # function (before decoration) was an `async def`. The\n # AwaitableGenerator type conveniently preserves the original\n # type as its 4th parameter (3rd when using 0-origin indexing\n # :-), so that we can recover that information here.\n # (We really need to see whether the original, undecorated\n # function was an `async def`, which is orthogonal to its\n # decorations.)\n t = get_proper_type(t)\n if (\n isinstance(t, Instance)\n and t.type.fullname == \"typing.AwaitableGenerator\"\n and len(t.args) >= 4\n ):\n t = get_proper_type(t.args[3])\n return isinstance(t, Instance) and t.type.fullname == \"typing.Coroutine\"\n\n\ndef is_non_empty_tuple(t: Type) -> bool:\n t = get_proper_type(t)\n return isinstance(t, TupleType) and bool(t.items)\n\n\ndef is_duplicate_mapping(\n mapping: list[int], actual_types: list[Type], actual_kinds: list[ArgKind]\n) -> bool:\n return (\n len(mapping) > 1\n # Multiple actuals can map to the same formal if they both come from\n # varargs (*args and **kwargs); in this case at runtime it is possible\n # that here are no duplicates. We need to allow this, as the convention\n # f(..., *args, **kwargs) is common enough.\n and not (\n len(mapping) == 2\n and actual_kinds[mapping[0]] == nodes.ARG_STAR\n and actual_kinds[mapping[1]] == nodes.ARG_STAR2\n )\n # Multiple actuals can map to the same formal if there are multiple\n # **kwargs which cannot be mapped with certainty (non-TypedDict\n # **kwargs).\n and not all(\n actual_kinds[m] == nodes.ARG_STAR2\n and not isinstance(get_proper_type(actual_types[m]), TypedDictType)\n for m in mapping\n )\n )\n\n\ndef replace_callable_return_type(c: CallableType, new_ret_type: Type) -> CallableType:\n \"\"\"Return a copy of a callable type with a different return type.\"\"\"\n return c.copy_modified(ret_type=new_ret_type)\n\n\nclass ArgInferSecondPassQuery(types.BoolTypeQuery):\n \"\"\"Query whether an argument type should be inferred in the second pass.\n\n The result is True if the type has a type variable in a callable return\n type anywhere. For example, the result for Callable[[], T] is True if t is\n a type variable.\n \"\"\"\n\n def __init__(self) -> None:\n super().__init__(types.ANY_STRATEGY)\n\n def visit_callable_type(self, t: CallableType) -> bool:\n # TODO: we need to check only for type variables of original callable.\n return self.query_types(t.arg_types) or t.accept(HasTypeVarQuery())\n\n\nclass HasTypeVarQuery(types.BoolTypeQuery):\n \"\"\"Visitor for querying whether a type has a type variable component.\"\"\"\n\n def __init__(self) -> None:\n super().__init__(types.ANY_STRATEGY)\n\n def visit_type_var(self, t: TypeVarType) -> bool:\n return True\n\n def visit_param_spec(self, t: ParamSpecType) -> bool:\n return True\n\n def visit_type_var_tuple(self, t: TypeVarTupleType) -> bool:\n return True\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/checkexpr.py","language":"Python","license":"NOASSERTION","size":289197} {"code":"\"\"\"Type checking of attribute access\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Callable, Sequence, cast\n\nfrom mypy import meet, message_registry, subtypes\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 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_union,\n supported_self_type,\n tuple_fallback,\n type_object_type_from_function,\n)\nfrom mypy.types import (\n ENUM_REMOVED_PROPS,\n AnyType,\n CallableType,\n DeletedType,\n FunctionLike,\n Instance,\n LiteralType,\n NoneType,\n Overloaded,\n ParamSpecType,\n PartialType,\n ProperType,\n TupleType,\n Type,\n TypedDictType,\n TypeOfAny,\n TypeType,\n TypeVarLikeType,\n TypeVarTupleType,\n TypeVarType,\n UnionType,\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, AnyType):\n # The base object has dynamic type.\n return AnyType(TypeOfAny.from_another_any, source_any=typ)\n elif isinstance(typ, UnionType):\n return analyze_union_member_access(name, typ, mx)\n elif isinstance(typ, FunctionLike) and typ.is_type_obj():\n return analyze_type_callable_member_access(name, typ, mx)\n elif isinstance(typ, TypeType):\n return analyze_type_type_member_access(name, typ, mx, override_info)\n elif isinstance(typ, TupleType):\n # Actually look up from the fallback instance type.\n return _analyze_member_access(name, tuple_fallback(typ), mx, override_info)\n elif isinstance(typ, (LiteralType, FunctionLike)):\n # Actually look up from the fallback instance type.\n return _analyze_member_access(name, typ.fallback, mx, override_info)\n elif isinstance(typ, TypedDictType):\n return analyze_typeddict_access(name, typ, mx, override_info)\n elif isinstance(typ, NoneType):\n return analyze_none_member_access(name, typ, mx)\n elif isinstance(typ, TypeVarLikeType):\n if isinstance(typ, TypeVarType) and typ.values:\n return _analyze_member_access(\n name, make_simplified_union(typ.values), mx, override_info\n )\n return _analyze_member_access(name, typ.upper_bound, mx, override_info)\n elif isinstance(typ, DeletedType):\n 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 first_item = method.items[0]\n assert isinstance(first_item, Decorator)\n return analyze_var(name, first_item.var, typ, info, mx)\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(signature, mx.self_type, is_classmethod=method.is_class)\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_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 vv = v\n if isinstance(vv, Decorator):\n # The associated Var node of a decorator contains the type.\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), result, mx.context, 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(descriptor_type: Type, mx: MemberContext) -> Type:\n \"\"\"Type check descriptor access.\n\n Arguments:\n descriptor_type: The type of the descriptor attribute being accessed\n (the type of ``f`` in ``a.f`` when ``f`` is a descriptor).\n mx: The current member access context.\n Return:\n The return type of the appropriate ``__get__`` 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 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\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\n if not var.is_staticmethod:\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 signature = check_self_arg(\n signature, dispatched_type, var.is_classmethod, mx.context, name, mx.msg\n )\n signature = bind_self(signature, mx.self_type, var.is_classmethod)\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(get_proper_type(mx.original_type), result, mx.context, mx.chk)\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 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\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(get_proper_type(mx.original_type), result, mx.context, mx.chk)\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 ENUM_REMOVED_PROPS:\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(\"builtins.function\"),\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/checkmember.py","language":"Python","license":"NOASSERTION","size":55260} {"code":"\"\"\"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 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 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 new_type = self.construct_sequence_child(current_type, new_inner_type)\n if is_subtype(new_type, current_type):\n new_type, _ = self.chk.conditional_types_with_intersection(\n current_type, [get_type_range(new_type)], o, default=current_type\n )\n else:\n new_type = current_type\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 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.is_named_tuple:\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, 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, 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 proper_type = get_proper_type(outer_type)\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/checkpattern.py","language":"Python","license":"NOASSERTION","size":33519} {"code":"\"\"\"\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 typing import TYPE_CHECKING, Callable, Dict, Final, Match, Pattern, Tuple, 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 TupleType,\n Type,\n TypeOfAny,\n TypeVarTupleType,\n TypeVarType,\n UnionType,\n UnpackType,\n find_unpack_in_list,\n get_proper_type,\n get_proper_types,\n)\n\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[^)]*)\\))?\" # (optional) parenthesised sequence of characters.\n flags_re = r\"(?P[#0\\-+ ]*)\" # (optional) sequence of flags.\n width_re = r\"(?P[1-9][0-9]*|\\*)?\" # (optional) minimum field width (* or numbers).\n precision_re = r\"(?:\\.(?P\\*|[0-9]+)?)?\" # (optional) . followed by * of numbers.\n length_mod_re = r\"[hlL]?\" # (optional) length modifier (unused).\n type_re = r\"(?P.)?\" # 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(?P[^.[!:]*)([^:!]+)?)\"\n\n # Conversion (optional) is ! followed by one of letters for forced repr(), str(), or ascii().\n conversion = r\"(?P![^:])?\"\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.?[<>=^])?\"\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[+\\- ]?#?0?)(?P\\d+)?[_,]?(?P\\.\\d+)?\"\n # The last element is type.\n conv_type = r\"(?P.)?\" # only some are supported, but we want to give a better error\n format_spec = r\"(?P:\" + 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:.*)?\"\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 conv_specs = parse_format_value(format_value, call, self.msg)\n if conv_specs is None:\n return\n if not self.auto_generate_keys(conv_specs, call):\n return\n self.check_specs_in_format_call(call, conv_specs, format_value)\n\n def check_specs_in_format_call(\n self, call: CallExpr, specs: list[ConversionSpecifier], format_value: str\n ) -> None:\n \"\"\"Perform pairwise checks for conversion specifiers vs their replacements.\n\n The core logic for format checking is implemented in this method.\n \"\"\"\n assert all(s.key for s in specs), \"Keys must be auto-generated first!\"\n replacements = self.find_replacements_in_call(call, [cast(str, s.key) for s in specs])\n assert len(replacements) == len(specs)\n for spec, repl in zip(specs, replacements):\n repl = self.apply_field_accessors(spec, repl, ctx=call)\n actual_type = repl.type if isinstance(repl, TempNode) else self.chk.lookup_type(repl)\n assert actual_type is not None\n\n # Special case custom formatting.\n if (\n spec.format_spec\n and spec.non_standard_format_spec\n and\n # Exclude \"dynamic\" specifiers (i.e. containing nested formatting).\n not (\"{\" in spec.format_spec or \"}\" in spec.format_spec)\n ):\n if (\n not custom_special_method(actual_type, \"__format__\", check_all=True)\n or spec.conversion\n ):\n # TODO: add support for some custom specs like datetime?\n self.msg.fail(\n f'Unrecognized format specification \"{spec.format_spec[1:]}\"',\n call,\n code=codes.STRING_FORMATTING,\n )\n continue\n # Adjust expected and actual types.\n if not spec.conv_type:\n expected_type: Type | None = AnyType(TypeOfAny.special_form)\n else:\n assert isinstance(call.callee, MemberExpr)\n if isinstance(call.callee.expr, StrExpr):\n format_str = call.callee.expr\n else:\n format_str = StrExpr(format_value)\n expected_type = self.conversion_type(\n spec.conv_type, call, format_str, format_call=True\n )\n if spec.conversion is not None:\n # If the explicit conversion is given, then explicit conversion is called _first_.\n if spec.conversion[1] not in \"rsa\":\n self.msg.fail(\n 'Invalid conversion type \"{}\",'\n ' must be one of \"r\", \"s\" or \"a\"'.format(spec.conversion[1]),\n call,\n code=codes.STRING_FORMATTING,\n )\n actual_type = self.named_type(\"builtins.str\")\n\n # Perform the checks for given types.\n if expected_type is None:\n continue\n\n a_type = get_proper_type(actual_type)\n actual_items = (\n get_proper_types(a_type.items) if isinstance(a_type, UnionType) else [a_type]\n )\n for a_type in actual_items:\n if custom_special_method(a_type, \"__format__\"):\n continue\n self.check_placeholder_type(a_type, expected_type, call)\n self.perform_special_format_checks(spec, call, repl, a_type, expected_type)\n\n def perform_special_format_checks(\n self,\n spec: ConversionSpecifier,\n call: CallExpr,\n repl: Expression,\n actual_type: Type,\n expected_type: Type,\n ) -> None:\n # TODO: try refactoring to combine this logic with % formatting.\n if spec.conv_type == \"c\":\n if isinstance(repl, (StrExpr, BytesExpr)) and len(repl.value) != 1:\n self.msg.requires_int_or_char(call, format_call=True)\n c_typ = get_proper_type(self.chk.lookup_type(repl))\n if isinstance(c_typ, Instance) and c_typ.last_known_value:\n c_typ = c_typ.last_known_value\n if isinstance(c_typ, LiteralType) and isinstance(c_typ.value, str):\n if len(c_typ.value) != 1:\n self.msg.requires_int_or_char(call, format_call=True)\n if (not spec.conv_type or spec.conv_type == \"s\") and not spec.conversion:\n if has_type_component(actual_type, \"builtins.bytes\") and not custom_special_method(\n actual_type, \"__str__\"\n ):\n self.msg.fail(\n 'If x = b\\'abc\\' then f\"{x}\" or \"{}\".format(x) produces \"b\\'abc\\'\", '\n 'not \"abc\". If this is desired behavior, use f\"{x!r}\" or \"{!r}\".format(x). '\n \"Otherwise, decode the bytes\",\n call,\n code=codes.STR_BYTES_PY3,\n )\n if spec.flags:\n numeric_types = UnionType(\n [self.named_type(\"builtins.int\"), self.named_type(\"builtins.float\")]\n )\n if (\n spec.conv_type\n and spec.conv_type not in NUMERIC_TYPES_NEW\n or not spec.conv_type\n and not is_subtype(actual_type, numeric_types)\n and not custom_special_method(actual_type, \"__format__\")\n ):\n self.msg.fail(\n \"Numeric flags are only allowed for numeric types\",\n call,\n code=codes.STRING_FORMATTING,\n )\n\n def find_replacements_in_call(self, call: CallExpr, keys: list[str]) -> list[Expression]:\n \"\"\"Find replacement expression for every specifier in str.format() call.\n\n In case of an error use TempNode(AnyType).\n \"\"\"\n result: list[Expression] = []\n used: set[Expression] = set()\n for key in keys:\n if key.isdecimal():\n expr = self.get_expr_by_position(int(key), call)\n if not expr:\n self.msg.fail(\n \"Cannot find replacement for positional\"\n \" format specifier {}\".format(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(). 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(). 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=\"\", 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\"\n ' accessor \"{}\"'.format(spec.field[len(spec.key) :]),\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 checkers_for_regular_type(\n self, conv_type: str, context: Context, expr: FormatStringExpr\n ) -> Checkers | None:\n \"\"\"Returns a tuple of check functions that check whether, respectively,\n a node or a type is compatible with 'type'. Return None in case of an error.\n \"\"\"\n expected_type = self.conversion_type(conv_type, context, expr)\n if expected_type is None:\n return None\n\n def check_type(typ: Type) -> bool:\n assert expected_type is not None\n ret = self.check_placeholder_type(typ, expected_type, context)\n if ret and conv_type == \"s\":\n ret = self.check_s_special_cases(expr, typ, context)\n return ret\n\n def check_expr(expr: Expression) -> None:\n type = self.accept(expr, expected_type)\n check_type(type)\n\n return check_expr, check_type\n\n def check_s_special_cases(self, expr: FormatStringExpr, typ: Type, context: Context) -> bool:\n \"\"\"Additional special cases for %s in bytes vs string context.\"\"\"\n if isinstance(expr, StrExpr):\n # Couple special cases for string formatting.\n if has_type_component(typ, \"builtins.bytes\"):\n self.msg.fail(\n 'If x = b\\'abc\\' then \"%s\" % x produces \"b\\'abc\\'\", not \"abc\". '\n 'If this is desired behavior use \"%r\" % x. Otherwise, decode the bytes',\n context,\n code=codes.STR_BYTES_PY3,\n )\n return False\n if isinstance(expr, BytesExpr):\n # A special case for bytes formatting: b'%s' actually requires bytes on Python 3.\n if has_type_component(typ, \"builtins.str\"):\n self.msg.fail(\n \"On Python 3 b'%s' requires bytes, not string\",\n context,\n code=codes.STRING_FORMATTING,\n )\n return False\n return True\n\n def checkers_for_c_type(\n self, type: str, context: Context, format_expr: FormatStringExpr\n ) -> Checkers | None:\n \"\"\"Returns a tuple of check functions that check whether, respectively,\n a node or a type is compatible with 'type' that is a character type.\n \"\"\"\n expected_type = self.conversion_type(type, context, format_expr)\n if expected_type is None:\n return None\n\n def check_type(type: Type) -> bool:\n assert expected_type is not None\n if isinstance(format_expr, BytesExpr):\n err_msg = '\"%c\" requires an integer in range(256) or a single byte'\n else:\n err_msg = '\"%c\" requires int or char'\n return self.chk.check_subtype(\n type,\n expected_type,\n context,\n err_msg,\n \"expression has type\",\n code=codes.STRING_FORMATTING,\n )\n\n def check_expr(expr: Expression) -> None:\n \"\"\"int, or str with length 1\"\"\"\n type = self.accept(expr, expected_type)\n # We need further check with expr to make sure that\n # it has exact one char or one single byte.\n if check_type(type):\n # Python 3 doesn't support b'%c' % str\n if (\n isinstance(format_expr, BytesExpr)\n and isinstance(expr, BytesExpr)\n and len(expr.value) != 1\n ):\n self.msg.requires_int_or_single_byte(context)\n elif isinstance(expr, (StrExpr, BytesExpr)) and len(expr.value) != 1:\n self.msg.requires_int_or_char(context)\n\n return check_expr, check_type\n\n def conversion_type(\n self, p: str, context: Context, expr: FormatStringExpr, format_call: bool = False\n ) -> Type | None:\n \"\"\"Return the type that is accepted for a string interpolation conversion specifier type.\n\n Note that both Python's float (e.g. %f) and integer (e.g. %d)\n specifier types accept both float and integers.\n\n The 'format_call' argument indicates whether this type came from % interpolation or from\n a str.format() call, the meaning of few formatting types are different.\n \"\"\"\n NUMERIC_TYPES = NUMERIC_TYPES_NEW if format_call else NUMERIC_TYPES_OLD\n INT_TYPES = REQUIRE_INT_NEW if format_call else REQUIRE_INT_OLD\n if p == \"b\" and not format_call:\n if not isinstance(expr, BytesExpr):\n self.msg.fail(\n 'Format character \"b\" is only supported on bytes patterns',\n context,\n code=codes.STRING_FORMATTING,\n )\n return None\n return self.named_type(\"builtins.bytes\")\n elif p == \"a\":\n # TODO: return type object?\n return AnyType(TypeOfAny.special_form)\n elif p in [\"s\", \"r\"]:\n return AnyType(TypeOfAny.special_form)\n elif p in NUMERIC_TYPES:\n if p in INT_TYPES:\n numeric_types = [self.named_type(\"builtins.int\")]\n else:\n numeric_types = [\n self.named_type(\"builtins.int\"),\n self.named_type(\"builtins.float\"),\n ]\n if not format_call:\n if p in FLOAT_TYPES:\n numeric_types.append(self.named_type(\"typing.SupportsFloat\"))\n else:\n numeric_types.append(self.named_type(\"typing.SupportsInt\"))\n return UnionType.make_union(numeric_types)\n elif p in [\"c\"]:\n if isinstance(expr, BytesExpr):\n return UnionType(\n [self.named_type(\"builtins.int\"), self.named_type(\"builtins.bytes\")]\n )\n else:\n return UnionType(\n [self.named_type(\"builtins.int\"), self.named_type(\"builtins.str\")]\n )\n else:\n self.msg.unsupported_placeholder(p, context)\n return None\n\n #\n # Helpers\n #\n\n def named_type(self, name: str) -> Instance:\n \"\"\"Return an instance type with type given by the name and no type\n arguments. Alias for TypeChecker.named_type.\n \"\"\"\n return self.chk.named_type(name)\n\n def accept(self, expr: Expression, context: Type | None = None) -> Type:\n \"\"\"Type check a node. Alias for TypeChecker.accept.\"\"\"\n return self.chk.expr_checker.accept(expr, context)\n\n\ndef has_type_component(typ: Type, fullname: str) -> bool:\n \"\"\"Is this a specific instance type, or a union that contains it?\n\n We use this ad-hoc function instead of a proper visitor or subtype check\n because some str vs bytes errors are strictly speaking not runtime errors,\n but rather highly counter-intuitive behavior. This is similar to what is used for\n --strict-equality.\n \"\"\"\n typ = get_proper_type(typ)\n if isinstance(typ, Instance):\n return typ.type.has_base(fullname)\n elif isinstance(typ, TypeVarType):\n return has_type_component(typ.upper_bound, fullname) or any(\n has_type_component(v, fullname) for v in typ.values\n )\n elif isinstance(typ, UnionType):\n return any(has_type_component(t, fullname) for t in typ.relevant_items())\n return False\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/checkstrformat.py","language":"Python","license":"NOASSERTION","size":46273} {"code":"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 typing import (\n Any,\n Callable,\n Dict,\n Final,\n Iterable,\n List,\n Mapping,\n MutableMapping,\n Sequence,\n TextIO,\n Tuple,\n Union,\n)\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 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 '{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 = None\n # We have to keep new_semantic_analyzer in Options\n # for plugin compatibility but it is not a valid option anymore.\n assert hasattr(template, \"new_semantic_analyzer\")\n if key != \"new_semantic_analyzer\":\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/config_parser.py","language":"Python","license":"NOASSERTION","size":23389} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/constant_fold.py","language":"Python","license":"NOASSERTION","size":6071} {"code":"\"\"\"Type inference constraints.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Final, Iterable, List, Sequence\n\nimport mypy.subtypes\nimport mypy.typeops\nfrom mypy.argmap import ArgTypeExpander\nfrom mypy.erasetype import erase_typevars\nfrom mypy.maptype import map_instance_to_supertype\nfrom mypy.nodes import (\n ARG_OPT,\n ARG_POS,\n ARG_STAR,\n ARG_STAR2,\n CONTRAVARIANT,\n COVARIANT,\n ArgKind,\n TypeInfo,\n)\nfrom mypy.types import (\n TUPLE_LIKE_INSTANCE_NAMES,\n AnyType,\n CallableType,\n DeletedType,\n ErasedType,\n Instance,\n LiteralType,\n NoneType,\n NormalizedCallableType,\n Overloaded,\n Parameters,\n ParamSpecType,\n PartialType,\n ProperType,\n TupleType,\n Type,\n TypeAliasType,\n TypedDictType,\n TypeOfAny,\n 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\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 # If the template is simply a type variable, emit a Constraint directly.\n # We need to handle this case before handling Unions for two reasons:\n # 1. \"T <: Union[U1, U2]\" is not equivalent to \"T <: U1 or T <: U2\",\n # because T can itself be a union (notably, Union[U1, U2] itself).\n # 2. \"T :> Union[U1, U2]\" is logically equivalent to \"T :> U1 and\n # T :> U2\", but they are not equivalent to the constraint solver,\n # which never introduces new Union types (it uses join() instead).\n if isinstance(template, TypeVarType):\n return [Constraint(template, direction, actual)]\n\n if (\n isinstance(actual, TypeVarType)\n and not actual.id.is_meta_var()\n and direction == SUPERTYPE_OF\n ):\n # Unless template is also a type variable (or a union that contains one), using the upper\n # bound for inference will usually give better result for actual that is a type variable.\n if not isinstance(template, UnionType) or not any(\n isinstance(t, TypeVarType) for t in template.items\n ):\n actual = get_proper_type(actual.upper_bound)\n\n # Now handle the case of either template or actual being a Union.\n # For a Union to be a subtype of another type, every item of the Union\n # must be a subtype of that type, so concatenate the constraints.\n if direction == SUBTYPE_OF and isinstance(template, UnionType):\n res = []\n for t_item in template.items:\n res.extend(infer_constraints(t_item, actual, direction))\n return res\n if direction == SUPERTYPE_OF and isinstance(actual, UnionType):\n res = []\n for a_item in actual.items:\n 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 # Remaining cases are handled by ConstraintBuilderVisitor.\n return template.accept(ConstraintBuilderVisitor(actual, direction, skip_neg_op))\n\n\ndef infer_constraints_if_possible(\n template: Type, actual: Type, direction: int\n) -> list[Constraint] | None:\n \"\"\"Like infer_constraints, but return None if the input relation is\n known to be unsatisfiable, for example if template=List[T] and actual=int.\n (In this case infer_constraints would return [], just like it would for\n an automatically satisfied relation like template=List[T] and actual=object.)\n \"\"\"\n if direction == SUBTYPE_OF and not mypy.subtypes.is_subtype(erase_typevars(template), actual):\n return None\n if direction == SUPERTYPE_OF and not mypy.subtypes.is_subtype(\n actual, erase_typevars(template)\n ):\n return None\n if (\n direction == SUPERTYPE_OF\n and isinstance(template, TypeVarType)\n and not mypy.subtypes.is_subtype(actual, erase_typevars(template.upper_bound))\n ):\n # This is not caught by the above branch because of the erase_typevars() call,\n # that would return 'Any' for a type variable.\n return None\n return infer_constraints(template, actual, direction)\n\n\ndef select_trivial(options: Sequence[list[Constraint] | None]) -> list[list[Constraint]]:\n \"\"\"Select only those lists where each item is a constraint against Any.\"\"\"\n res = []\n for option in options:\n if option is None:\n continue\n if all(isinstance(get_proper_type(c.target), AnyType) for c in option):\n res.append(option)\n return res\n\n\ndef merge_with_any(constraint: Constraint) -> Constraint:\n \"\"\"Transform a constraint target into a union with given Any type.\"\"\"\n target = constraint.target\n if is_union_with_any(target):\n # Do not produce redundant unions.\n return constraint\n # TODO: if we will support multiple sources Any, use this here instead.\n any_type = AnyType(TypeOfAny.implementation_artifact)\n return Constraint(\n constraint.origin_type_var,\n constraint.op,\n UnionType.make_union([target, any_type], target.line, target.column),\n )\n\n\ndef handle_recursive_union(template: UnionType, actual: Type, direction: int) -> list[Constraint]:\n # This is a hack to special-case things like Union[T, Inst[T]] in recursive types. Although\n # it is quite arbitrary, it is a relatively common pattern, so we should handle it well.\n # This function may be called when inferring against such union resulted in different\n # constraints for each item. Normally we give up in such case, but here we instead split\n # the union in two parts, and try inferring sequentially.\n non_type_var_items = [t for t in template.items if not isinstance(t, TypeVarType)]\n type_var_items = [t for t in template.items if isinstance(t, TypeVarType)]\n return infer_constraints(\n UnionType.make_union(non_type_var_items), actual, direction\n ) or infer_constraints(UnionType.make_union(type_var_items), actual, direction)\n\n\ndef any_constraints(options: list[list[Constraint] | None], eager: bool) -> list[Constraint]:\n \"\"\"Deduce what we can from a collection of constraint lists.\n\n It's a given that at least one of the lists must be satisfied. A\n None element in the list of options represents an unsatisfiable\n constraint and is ignored. Ignore empty constraint lists if eager\n is true -- they are always trivially satisfiable.\n \"\"\"\n if eager:\n valid_options = [option for option in options if option]\n else:\n valid_options = [option for option in options if option is not None]\n\n if not valid_options:\n return []\n\n if len(valid_options) == 1:\n return valid_options[0]\n\n if all(is_same_constraints(valid_options[0], c) for c in valid_options[1:]):\n # Multiple sets of constraints that are all the same. Just pick any one of them.\n return valid_options[0]\n\n if all(is_similar_constraints(valid_options[0], c) for c in valid_options[1:]):\n # All options have same structure. In this case we can merge-in trivial\n # options (i.e. those that only have Any) and try again.\n # TODO: More generally, if a given (variable, direction) pair appears in\n # every option, combine the bounds with meet\/join always, not just for Any.\n trivial_options = select_trivial(valid_options)\n if trivial_options and len(trivial_options) < len(valid_options):\n merged_options = []\n for option in valid_options:\n if option in trivial_options:\n continue\n 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\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\n cactual_ret_type = cactual.type_guard\n elif template.type_guard is not None:\n template_ret_type = AnyType(TypeOfAny.special_form)\n elif cactual.type_guard is not None:\n cactual_ret_type = AnyType(TypeOfAny.special_form)\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 elif template.type_is is not None:\n template_ret_type = AnyType(TypeOfAny.special_form)\n elif cactual.type_is is not None:\n cactual_ret_type = AnyType(TypeOfAny.special_form)\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_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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/constraints.py","language":"Python","license":"NOASSERTION","size":76919} {"code":"from __future__ import annotations\n\nfrom typing import Any, cast\n\nfrom mypy.types import (\n AnyType,\n CallableType,\n DeletedType,\n ErasedType,\n Instance,\n LiteralType,\n NoneType,\n Overloaded,\n Parameters,\n ParamSpecType,\n PartialType,\n ProperType,\n TupleType,\n TypeAliasType,\n TypedDictType,\n TypeType,\n TypeVarTupleType,\n TypeVarType,\n UnboundType,\n UninhabitedType,\n UnionType,\n UnpackType,\n)\n\n# type_visitor needs to be imported after types\nfrom mypy.type_visitor import TypeVisitor # ruff: isort: skip\n\n\ndef copy_type(t: ProperType) -> ProperType:\n \"\"\"Create a shallow copy of a type.\n\n This can be used to mutate the copy with truthiness information.\n\n Classes compiled with mypyc don't support copy.copy(), so we need\n a custom implementation.\n \"\"\"\n return t.accept(TypeShallowCopier())\n\n\nclass TypeShallowCopier(TypeVisitor[ProperType]):\n def visit_unbound_type(self, t: UnboundType) -> ProperType:\n return t\n\n def visit_any(self, t: AnyType) -> ProperType:\n return self.copy_common(t, AnyType(t.type_of_any, t.source_any, t.missing_import_name))\n\n def visit_none_type(self, t: NoneType) -> ProperType:\n return self.copy_common(t, NoneType())\n\n def visit_uninhabited_type(self, t: UninhabitedType) -> ProperType:\n dup = UninhabitedType()\n dup.ambiguous = t.ambiguous\n return self.copy_common(t, dup)\n\n def visit_erased_type(self, t: ErasedType) -> ProperType:\n return self.copy_common(t, ErasedType())\n\n def visit_deleted_type(self, t: DeletedType) -> ProperType:\n return self.copy_common(t, DeletedType(t.source))\n\n def visit_instance(self, t: Instance) -> ProperType:\n dup = Instance(t.type, t.args, last_known_value=t.last_known_value)\n 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_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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/copytype.py","language":"Python","license":"NOASSERTION","size":4451} {"code":"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, 8)\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\nCACHE_DIR: Final = \".mypy_cache\"\nCONFIG_FILE: Final = [\"mypy.ini\", \".mypy.ini\"]\nPYPROJECT_CONFIG_FILES: Final = [\"pyproject.toml\"]\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/defaults.py","language":"Python","license":"NOASSERTION","size":1558} {"code":"","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/dmypy\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"from __future__ import annotations\n\nfrom mypy.dmypy.client import console_entry\n\nif __name__ == \"__main__\":\n console_entry()\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/dmypy\/__main__.py","language":"Python","license":"NOASSERTION","size":128} {"code":"\"\"\"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 typing import Any, Callable, Mapping, 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 __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\", description=\"Client for mypy daemon mode\", fromfile_prefix_chars=\"@\"\n)\nparser.set_defaults(action=None)\nparser.add_argument(\n \"--status-file\", default=DEFAULT_STATUS_FILE, help=\"status file to retrieve daemon details\"\n)\nparser.add_argument(\n \"-V\",\n \"--version\",\n action=\"version\",\n version=\"%(prog)s \" + __version__,\n help=\"Show program's version number and exit\",\n)\nsubparsers = parser.add_subparsers()\n\nstart_parser = p = subparsers.add_parser(\"start\", help=\"Start daemon\")\np.add_argument(\"--log-file\", metavar=\"FILE\", type=str, help=\"Direct daemon stdout\/stderr to FILE\")\np.add_argument(\n \"--timeout\", metavar=\"TIMEOUT\", type=int, help=\"Server shutdown timeout (in seconds)\"\n)\np.add_argument(\n \"flags\", metavar=\"FLAG\", nargs=\"*\", type=str, help=\"Regular mypy flags (precede with --)\"\n)\n\nrestart_parser = p = subparsers.add_parser(\n \"restart\", help=\"Restart daemon (stop or kill followed by start)\"\n)\np.add_argument(\"--log-file\", metavar=\"FILE\", type=str, help=\"Direct daemon stdout\/stderr to FILE\")\np.add_argument(\n \"--timeout\", metavar=\"TIMEOUT\", type=int, help=\"Server shutdown timeout (in seconds)\"\n)\np.add_argument(\n \"flags\", metavar=\"FLAG\", nargs=\"*\", type=str, help=\"Regular mypy flags (precede with --)\"\n)\n\nstatus_parser = p = subparsers.add_parser(\"status\", help=\"Show daemon status\")\np.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"Print detailed status\")\np.add_argument(\"--fswatcher-dump-file\", help=\"Collect information about the current file state\")\n\nstop_parser = p = subparsers.add_parser(\"stop\", help=\"Stop daemon (asks it politely to go away)\")\n\nkill_parser = p = subparsers.add_parser(\"kill\", help=\"Kill daemon (kills the process)\")\n\ncheck_parser = p = subparsers.add_parser(\n \"check\", formatter_class=AugmentedHelpFormatter, help=\"Check some files (requires daemon)\"\n)\np.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"Print detailed status\")\np.add_argument(\"-q\", \"--quiet\", action=\"store_true\", help=argparse.SUPPRESS) # Deprecated\np.add_argument(\"--junit-xml\", help=\"Write junit.xml to the given file\")\np.add_argument(\"--perf-stats-file\", help=\"write performance information to the given file\")\np.add_argument(\"files\", metavar=\"FILE\", nargs=\"+\", help=\"File (or directory) to check\")\np.add_argument(\n \"--export-types\",\n action=\"store_true\",\n help=\"Store types of all expressions in a shared location (useful for inspections)\",\n)\n\nrun_parser = p = subparsers.add_parser(\n \"run\",\n formatter_class=AugmentedHelpFormatter,\n help=\"Check some files, [re]starting daemon if necessary\",\n)\np.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"Print detailed status\")\np.add_argument(\"--junit-xml\", help=\"Write junit.xml to the given file\")\np.add_argument(\"--perf-stats-file\", help=\"write performance information to the given file\")\np.add_argument(\n \"--timeout\", metavar=\"TIMEOUT\", type=int, help=\"Server shutdown timeout (in seconds)\"\n)\np.add_argument(\"--log-file\", metavar=\"FILE\", type=str, help=\"Direct daemon stdout\/stderr to FILE\")\np.add_argument(\n \"--export-types\",\n action=\"store_true\",\n help=\"Store types of all expressions in a shared location (useful for inspections)\",\n)\np.add_argument(\n \"flags\",\n metavar=\"ARG\",\n nargs=\"*\",\n type=str,\n help=\"Regular mypy flags and files (precede with --)\",\n)\n\nrecheck_parser = p = subparsers.add_parser(\n \"recheck\",\n formatter_class=AugmentedHelpFormatter,\n help=\"Re-check the previous list of files, with optional modifications (requires daemon)\",\n)\np.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"Print detailed status\")\np.add_argument(\"-q\", \"--quiet\", action=\"store_true\", help=argparse.SUPPRESS) # Deprecated\np.add_argument(\"--junit-xml\", help=\"Write junit.xml to the given file\")\np.add_argument(\"--perf-stats-file\", help=\"write performance information to the given file\")\np.add_argument(\n \"--export-types\",\n action=\"store_true\",\n help=\"Store types of all expressions in a shared location (useful for inspections)\",\n)\np.add_argument(\n \"--update\",\n metavar=\"FILE\",\n nargs=\"*\",\n help=\"Files in the run to add or check again (default: all from previous run)\",\n)\np.add_argument(\"--remove\", metavar=\"FILE\", nargs=\"*\", help=\"Files to remove from the run\")\n\nsuggest_parser = p = subparsers.add_parser(\n \"suggest\", help=\"Suggest a signature or show call sites for a specific function\"\n)\np.add_argument(\n \"function\",\n metavar=\"FUNCTION\",\n type=str,\n help=\"Function specified as '[package.]module.[class.]function'\",\n)\np.add_argument(\n \"--json\",\n action=\"store_true\",\n help=\"Produce json that pyannotate can use to apply a suggestion\",\n)\np.add_argument(\n \"--no-errors\", action=\"store_true\", help=\"Only produce suggestions that cause no errors\"\n)\np.add_argument(\n \"--no-any\", action=\"store_true\", help=\"Only produce suggestions that don't contain Any\"\n)\np.add_argument(\n \"--flex-any\",\n type=float,\n help=\"Allow anys in types if they go above a certain score (scores are from 0-1)\",\n)\np.add_argument(\n \"--callsites\", action=\"store_true\", help=\"Find callsites instead of suggesting a type\"\n)\np.add_argument(\n \"--use-fixme\",\n metavar=\"NAME\",\n type=str,\n help=\"A dummy name to use instead of Any for types that can't be inferred\",\n)\np.add_argument(\n \"--max-guesses\",\n type=int,\n help=\"Set the maximum number of types to try for a function (default 64)\",\n)\n\ninspect_parser = p = subparsers.add_parser(\n \"inspect\", help=\"Locate and statically inspect expression(s)\"\n)\np.add_argument(\n \"location\",\n metavar=\"LOCATION\",\n type=str,\n help=\"Location specified as path\/to\/file.py:line:column[:end_line:end_column].\"\n \" If position is given (i.e. only line and column), this will return all\"\n \" enclosing expressions\",\n)\np.add_argument(\n \"--show\",\n metavar=\"INSPECTION\",\n type=str,\n default=\"type\",\n choices=[\"type\", \"attrs\", \"definition\"],\n help=\"What kind of inspection to run\",\n)\np.add_argument(\n \"--verbose\",\n \"-v\",\n action=\"count\",\n default=0,\n help=\"Increase verbosity of the type string representation (can be repeated)\",\n)\np.add_argument(\n \"--limit\",\n metavar=\"NUM\",\n type=int,\n default=0,\n help=\"Return at most NUM innermost expressions (if position is given); 0 means no limit\",\n)\np.add_argument(\n \"--include-span\",\n action=\"store_true\",\n help=\"Prepend each inspection result with the span of corresponding expression\"\n ' (e.g. 1:2:3:4:\"int\")',\n)\np.add_argument(\n \"--include-kind\",\n action=\"store_true\",\n help=\"Prepend each inspection result with the kind of corresponding expression\"\n ' (e.g. NameExpr:\"int\")',\n)\np.add_argument(\n \"--include-object-attrs\",\n action=\"store_true\",\n help='Include attributes of \"object\" in \"attrs\" inspection',\n)\np.add_argument(\n \"--union-attrs\",\n action=\"store_true\",\n help=\"Include attributes valid for some of possible expression types\"\n \" (by default an intersection is returned)\",\n)\np.add_argument(\n \"--force-reload\",\n action=\"store_true\",\n help=\"Re-parse and re-type-check file before inspection (may be slow)\",\n)\n\nhang_parser = p = subparsers.add_parser(\"hang\", help=\"Hang for 100 seconds\")\n\ndaemon_parser = p = subparsers.add_parser(\"daemon\", help=\"Run daemon in foreground\")\np.add_argument(\n \"--timeout\", metavar=\"TIMEOUT\", type=int, help=\"Server shutdown timeout (in seconds)\"\n)\np.add_argument(\"--log-file\", metavar=\"FILE\", type=str, help=\"Direct daemon stdout\/stderr to FILE\")\np.add_argument(\n \"flags\", metavar=\"FLAG\", nargs=\"*\", type=str, help=\"Regular mypy flags (precede with --)\"\n)\np.add_argument(\"--options-data\", help=argparse.SUPPRESS)\nhelp_parser = p = subparsers.add_parser(\"help\")\n\ndel p\n\n\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 not args.action:\n parser.print_usage()\n else:\n try:\n args.action(args)\n except BadStatus as err:\n fail(err.args[0])\n except Exception:\n # We do this explicitly to avoid exceptions percolating up\n # through mypy.api invocations\n traceback.print_exc()\n sys.exit(2)\n\n\ndef fail(msg: str) -> NoReturn:\n print(msg, file=sys.stderr)\n sys.exit(2)\n\n\nActionFunction = Callable[[argparse.Namespace], None]\n\n\ndef action(subparser: argparse.ArgumentParser) -> Callable[[ActionFunction], ActionFunction]:\n \"\"\"Decorator to tie an action function to a subparser.\"\"\"\n\n def register(func: ActionFunction) -> ActionFunction:\n subparser.set_defaults(action=func)\n return func\n\n return register\n\n\n# Action functions (run in client from command line).\n\n\n@action(start_parser)\ndef do_start(args: argparse.Namespace) -> None:\n \"\"\"Start daemon (it must not already be running).\n\n This is where mypy flags are set from the command line.\n\n Setting flags is a bit awkward; you have to use e.g.:\n\n dmypy start -- --strict\n\n since we don't want to duplicate mypy's huge list of flags.\n \"\"\"\n try:\n get_status(args.status_file)\n except BadStatus:\n # Bad or missing status file or dead process; good to start.\n pass\n else:\n fail(\"Daemon is still alive\")\n start_server(args)\n\n\n@action(restart_parser)\ndef do_restart(args: argparse.Namespace) -> None:\n \"\"\"Restart daemon (it may or may not be running; but not hanging).\n\n We first try to stop it politely if it's running. This also sets\n mypy flags from the command line (see do_start()).\n \"\"\"\n restart_server(args)\n\n\ndef restart_server(args: argparse.Namespace, allow_sources: bool = False) -> None:\n \"\"\"Restart daemon (it may or may not be running; but not hanging).\"\"\"\n try:\n do_stop(args)\n except BadStatus:\n # Bad or missing status file or dead process; good to start.\n pass\n start_server(args, allow_sources)\n\n\ndef start_server(args: argparse.Namespace, allow_sources: bool = False) -> None:\n \"\"\"Start the server from command arguments and wait for it.\"\"\"\n # Lazy import so this import doesn't slow down other commands.\n from mypy.dmypy_server import daemonize, process_start_options\n\n start_options = process_start_options(args.flags, allow_sources)\n if daemonize(start_options, args.status_file, timeout=args.timeout, log_file=args.log_file):\n sys.exit(2)\n wait_for_server(args.status_file)\n\n\ndef wait_for_server(status_file: str, timeout: float = 5.0) -> None:\n \"\"\"Wait until the server is up.\n\n Exit if it doesn't happen within the timeout.\n \"\"\"\n endtime = time.time() + timeout\n while time.time() < endtime:\n try:\n data = read_status(status_file)\n except BadStatus:\n # If the file isn't there yet, retry later.\n time.sleep(0.1)\n continue\n # If the file's content is bogus or the process is dead, fail.\n check_status(data)\n print(\"Daemon started\")\n return\n fail(\"Timed out waiting for daemon to start\")\n\n\n@action(run_parser)\ndef do_run(args: argparse.Namespace) -> None:\n \"\"\"Do a check, starting (or restarting) the daemon as necessary\n\n Restarts the daemon if the running daemon reports that it is\n required (due to a configuration change, for example).\n\n Setting flags is a bit awkward; you have to use e.g.:\n\n dmypy run -- --strict a.py b.py ...\n\n since we don't want to duplicate mypy's huge list of flags.\n (The -- is only necessary if flags are specified.)\n \"\"\"\n if not is_running(args.status_file):\n # Bad or missing status file or dead process; good to start.\n start_server(args, allow_sources=True)\n t0 = time.time()\n response = request(\n args.status_file,\n \"run\",\n version=__version__,\n args=args.flags,\n export_types=args.export_types,\n )\n # If the daemon signals that a restart is necessary, do it\n if \"restart\" in response:\n print(f\"Restarting: {response['restart']}\")\n restart_server(args, allow_sources=True)\n response = request(\n args.status_file,\n \"run\",\n version=__version__,\n args=args.flags,\n export_types=args.export_types,\n )\n\n t1 = time.time()\n response[\"roundtrip_time\"] = t1 - t0\n check_output(response, args.verbose, args.junit_xml, args.perf_stats_file)\n\n\n@action(status_parser)\ndef do_status(args: argparse.Namespace) -> None:\n \"\"\"Print daemon status.\n\n This verifies that it is responsive to requests.\n \"\"\"\n status = read_status(args.status_file)\n if args.verbose:\n show_stats(status)\n # Both check_status() and request() may raise BadStatus,\n # which will be handled by main().\n check_status(status)\n response = request(\n args.status_file, \"status\", fswatcher_dump_file=args.fswatcher_dump_file, timeout=5\n )\n if args.verbose or \"error\" in response:\n show_stats(response)\n if \"error\" in response:\n fail(f\"Daemon is stuck; 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 is stuck; 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 from mypy.dmypy_server import Server, process_start_options\n\n if args.log_file:\n sys.stdout = sys.stderr = open(args.log_file, \"a\", buffering=1)\n fd = sys.stdout.fileno()\n os.dup2(fd, 2)\n os.dup2(fd, 1)\n\n if args.options_data:\n from mypy.options import Options\n\n options_dict = pickle.loads(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 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': } 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 = 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/dmypy\/client.py","language":"Python","license":"NOASSERTION","size":24616} {"code":"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\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/dmypy_os.py","language":"Python","license":"NOASSERTION","size":1154} {"code":"\"\"\"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 contextlib import redirect_stderr, redirect_stdout\nfrom typing import AbstractSet, Any, Callable, Final, List, Sequence, Tuple\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\nfrom mypy.version import __version__\n\nMEM_PROFILE: Final = False # If True, dump memory profile after initialization\n\nif sys.platform == \"win32\":\n from subprocess import STARTUPINFO\n\n def daemonize(\n options: Options, status_file: str, timeout: int | None = None, log_file: str | None = None\n ) -> int:\n \"\"\"Create the daemon process via \"dmypy daemon\" and pass options via command line\n\n When creating the daemon grandchild, we create it in a new console, which is\n started hidden. We cannot use DETACHED_PROCESS since it will cause console windows\n to pop up when starting. See\n https:\/\/github.com\/python\/cpython\/pull\/4150#issuecomment-340215696\n for more on why we can't have nice things.\n\n It also pickles the options to be unpickled by mypy.\n \"\"\"\n command = [sys.executable, \"-m\", \"mypy.dmypy\", \"--status-file\", status_file, \"daemon\"]\n pickled_options = pickle.dumps(options.snapshot())\n command.append(f'--options-data=\"{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 info = STARTUPINFO()\n info.dwFlags = 0x1 # STARTF_USESHOWWINDOW aka use wShowWindow's value\n info.wShowWindow = 0 # SW_HIDE aka make the window invisible\n try:\n subprocess.Popen(command, creationflags=0x10, startupinfo=info) # CREATE_NEW_CONSOLE\n return 0\n except subprocess.CalledProcessError as e:\n return e.returncode\n\nelse:\n\n def _daemonize_cb(func: Callable[[], None], log_file: str | None = None) -> int:\n \"\"\"Arrange to call func() in a grandchild of the current process.\n\n Return 0 for success, exit status for failure, negative if\n subprocess killed by signal.\n \"\"\"\n # See https:\/\/stackoverflow.com\/questions\/473620\/how-do-you-create-a-daemon-in-python\n sys.stdout.flush()\n sys.stderr.flush()\n pid = os.fork()\n if pid:\n # Parent process: wait for child in case things go bad there.\n npid, sts = os.waitpid(pid, 0)\n sig = sts & 0xFF\n if sig:\n print(\"Child killed by signal\", sig)\n return -sig\n sts = sts >> 8\n if sts:\n print(\"Child exit status\", sts)\n return sts\n # Child process: do a bunch of UNIX stuff and then fork a grandchild.\n try:\n os.setsid() # Detach controlling terminal\n os.umask(0o27)\n devnull = os.open(\"\/dev\/null\", os.O_RDWR)\n os.dup2(devnull, 0)\n os.dup2(devnull, 1)\n os.dup2(devnull, 2)\n os.close(devnull)\n pid = os.fork()\n if pid:\n # Child is done, exit to parent.\n os._exit(0)\n # Grandchild: run the server.\n if log_file:\n sys.stdout = sys.stderr = open(log_file, \"a\", buffering=1)\n fd = sys.stdout.fileno()\n os.dup2(fd, 2)\n os.dup2(fd, 1)\n func()\n finally:\n # Make sure we never get back into the caller.\n os._exit(1)\n\n def daemonize(\n options: Options, status_file: str, timeout: int | None = None, log_file: str | None = None\n ) -> int:\n \"\"\"Run the mypy daemon in a grandchild of the current process\n\n Return 0 for success, exit status for failure, negative if\n subprocess killed by signal.\n \"\"\"\n return _daemonize_cb(Server(options, status_file, timeout).serve, log_file)\n\n\n# Server code.\n\nCONNECTION_NAME: Final = \"dmypy\"\n\n\ndef process_start_options(flags: list[str], allow_sources: bool) -> Options:\n _, options = mypy.main.process_options(\n [\"-i\"] + flags, require_targets=False, server_options=True\n )\n if options.report_dirs:\n print(\"dmypy: Ignoring report generation settings. Start\/restart cannot generate reports.\")\n if options.junit_xml:\n print(\n \"dmypy: Ignoring report generation settings. \"\n \"Start\/restart does not support --junit-xml. Pass it to check\/recheck instead\"\n )\n options.junit_xml = None\n if not options.incremental:\n sys.exit(\"dmypy: start\/restart should not disable incremental mode\")\n if options.follow_imports not in (\"skip\", \"error\", \"normal\"):\n sys.exit(\"dmypy: follow-imports=silent not supported\")\n return options\n\n\ndef ignore_suppressed_imports(module: str) -> bool:\n \"\"\"Can we skip looking for newly unsuppressed imports to module?\"\"\"\n # Various submodules of 'encodings' can be suppressed, since it\n # uses module-level '__getattr__'. Skip them since there are many\n # of them, and following imports to them is kind of pointless.\n return module.startswith(\"encodings.\")\n\n\nModulePathPair: _TypeAlias = Tuple[str, str]\nModulePathPairs: _TypeAlias = List[ModulePathPair]\nChangesAndRemovals: _TypeAlias = Tuple[ModulePathPairs, ModulePathPairs]\n\n\nclass Server:\n # NOTE: the instance is constructed in the parent process but\n # serve() is called in the grandchild (by daemonize()).\n\n def __init__(self, options: Options, status_file: str, timeout: int | None = None) -> None:\n \"\"\"Initialize the server with the desired mypy flags.\"\"\"\n self.options = options\n # Snapshot the options info before we muck with it, to detect changes\n self.options_snapshot = options.snapshot()\n self.timeout = timeout\n self.fine_grained_manager: FineGrainedBuildManager | None = None\n\n if os.path.isfile(status_file):\n os.unlink(status_file)\n\n self.fscache = FileSystemCache()\n\n options.raise_exceptions = True\n options.incremental = True\n options.fine_grained_incremental = True\n options.show_traceback = True\n if options.use_fine_grained_cache:\n # Using fine_grained_cache implies generating and caring\n # about the fine grained cache\n options.cache_fine_grained = True\n else:\n options.cache_dir = os.devnull\n # Fine-grained incremental doesn't support general partial types\n # (details in https:\/\/github.com\/python\/mypy\/issues\/4492)\n options.local_partial_types = True\n self.status_file = status_file\n\n # Since the object is created in the parent process we can check\n # the output terminal options here.\n self.formatter = FancyFormatter(sys.stdout, sys.stderr, options.hide_error_codes)\n\n def _response_metadata(self) -> dict[str, str]:\n py_version = f\"{self.options.python_version[0]}_{self.options.python_version[1]}\"\n return {\"platform\": self.options.platform, \"python_version\": py_version}\n\n def serve(self) -> None:\n \"\"\"Serve requests, synchronously (no thread or fork).\"\"\"\n\n command = None\n server = IPCServer(CONNECTION_NAME, self.timeout)\n orig_stdout = sys.stdout\n orig_stderr = sys.stderr\n\n try:\n with open(self.status_file, \"w\") as f:\n json.dump({\"pid\": os.getpid(), \"connection_name\": server.connection_name}, f)\n f.write(\"\\n\") # I like my JSON with a trailing newline\n while True:\n with server:\n data = receive(server)\n sys.stdout = WriteToConn(server, \"stdout\", sys.stdout.isatty())\n sys.stderr = WriteToConn(server, \"stderr\", sys.stderr.isatty())\n resp: dict[str, Any] = {}\n if \"command\" not in data:\n resp = {\"error\": \"No command found in request\"}\n else:\n command = data[\"command\"]\n if not isinstance(command, str):\n resp = {\"error\": \"Command is not a string\"}\n else:\n command = data.pop(\"command\")\n try:\n resp = self.run_command(command, data)\n except Exception:\n # If we are crashing, report the crash to the client\n tb = traceback.format_exception(*sys.exc_info())\n resp = {\"error\": \"Daemon crashed!\\n\" + \"\".join(tb)}\n resp.update(self._response_metadata())\n resp[\"final\"] = True\n send(server, resp)\n raise\n resp[\"final\"] = True\n try:\n resp.update(self._response_metadata())\n send(server, resp)\n except OSError:\n pass # Maybe the client hung up\n if command == \"stop\":\n reset_global_state()\n sys.exit(0)\n finally:\n # Revert stdout\/stderr so we can see any errors.\n sys.stdout = orig_stdout\n sys.stderr = orig_stderr\n\n # If the final command is something other than a clean\n # stop, remove the status file. (We can't just\n # simplify the logic and always remove the file, since\n # that could cause us to remove a future server's\n # status file.)\n if command != \"stop\":\n os.unlink(self.status_file)\n try:\n server.cleanup() # try to remove the socket dir on Linux\n except OSError:\n pass\n exc_info = sys.exc_info()\n if exc_info[0] and exc_info[0] is not SystemExit:\n traceback.print_exception(*exc_info)\n\n def run_command(self, command: str, data: dict[str, object]) -> dict[str, object]:\n \"\"\"Run a specific command from the registry.\"\"\"\n key = \"cmd_\" + command\n method = getattr(self.__class__, key, None)\n if method is None:\n return {\"error\": f\"Unrecognized command '{command}'\"}\n else:\n if command not in {\"check\", \"recheck\", \"run\"}:\n # Only the above commands use some error formatting.\n del data[\"is_tty\"]\n del data[\"terminal_width\"]\n ret = method(self, **data)\n assert isinstance(ret, dict)\n return ret\n\n # Command functions (run in the server via RPC).\n\n def cmd_status(self, fswatcher_dump_file: str | None = None) -> dict[str, object]:\n \"\"\"Return daemon status.\"\"\"\n res: dict[str, object] = {}\n res.update(get_meminfo())\n if fswatcher_dump_file:\n data = self.fswatcher.dump_file_data() if hasattr(self, \"fswatcher\") else {}\n # Using .dumps and then writing was noticeably faster than using dump\n s = json.dumps(data)\n with open(fswatcher_dump_file, \"w\") as f:\n f.write(s)\n return res\n\n def cmd_stop(self) -> dict[str, object]:\n \"\"\"Stop daemon.\"\"\"\n # We need to remove the status file *before* we complete the\n # RPC. Otherwise a race condition exists where a subsequent\n # command can see a status file from a dying server and think\n # it is a live one.\n os.unlink(self.status_file)\n return {}\n\n def cmd_run(\n self,\n version: str,\n args: Sequence[str],\n export_types: bool,\n is_tty: bool,\n terminal_width: int,\n ) -> dict[str, object]:\n \"\"\"Check a list of files, triggering a restart if needed.\"\"\"\n stderr = io.StringIO()\n stdout = io.StringIO()\n try:\n # Process options can exit on improper arguments, so we need to catch that and\n # capture stderr so the client can report it\n with redirect_stderr(stderr):\n with redirect_stdout(stdout):\n sources, options = mypy.main.process_options(\n [\"-i\"] + list(args),\n require_targets=True,\n server_options=True,\n fscache=self.fscache,\n program=\"mypy-daemon\",\n header=argparse.SUPPRESS,\n )\n # Signal that we need to restart if the options have changed\n if not options.compare_stable(self.options_snapshot):\n return {\"restart\": \"configuration changed\"}\n if __version__ != version:\n return {\"restart\": \"mypy version changed\"}\n if self.fine_grained_manager:\n manager = self.fine_grained_manager.manager\n start_plugins_snapshot = manager.plugins_snapshot\n _, current_plugins_snapshot = mypy.build.load_plugins(\n options, manager.errors, sys.stdout, extra_plugins=()\n )\n if current_plugins_snapshot != start_plugins_snapshot:\n return {\"restart\": \"plugins changed\"}\n except InvalidSourceList as err:\n return {\"out\": \"\", \"err\": str(err), \"status\": 2}\n except SystemExit as e:\n return {\"out\": stdout.getvalue(), \"err\": stderr.getvalue(), \"status\": e.code}\n return self.check(sources, export_types, is_tty, terminal_width)\n\n def cmd_check(\n self, files: Sequence[str], export_types: bool, is_tty: bool, terminal_width: int\n ) -> dict[str, object]:\n \"\"\"Check a list of files.\"\"\"\n try:\n sources = create_source_list(files, self.options, self.fscache)\n except InvalidSourceList as err:\n return {\"out\": \"\", \"err\": str(err), \"status\": 2}\n return self.check(sources, export_types, is_tty, terminal_width)\n\n def cmd_recheck(\n self,\n is_tty: bool,\n terminal_width: int,\n export_types: bool,\n remove: list[str] | None = None,\n update: list[str] | None = None,\n ) -> dict[str, object]:\n \"\"\"Check the same list of files we checked most recently.\n\n If remove\/update is given, they modify the previous list;\n if all are None, stat() is called for each file in the previous list.\n \"\"\"\n t0 = time.time()\n if not self.fine_grained_manager:\n return {\"error\": \"Command 'recheck' is only valid after a 'check' command\"}\n sources = self.previous_sources\n if remove:\n removals = set(remove)\n sources = [s for s in sources if s.path and s.path not in removals]\n if update:\n # Sort list of file updates by extension, so *.pyi files are first.\n update.sort(key=lambda f: os.path.splitext(f)[1], reverse=True)\n\n known = {s.path for s in sources if s.path}\n added = [p for p in update if p not in known]\n try:\n added_sources = create_source_list(added, self.options, self.fscache)\n except InvalidSourceList as err:\n return {\"out\": \"\", \"err\": str(err), \"status\": 2}\n sources = sources + added_sources # Make a copy!\n t1 = time.time()\n manager = self.fine_grained_manager.manager\n manager.log(f\"fine-grained increment: cmd_recheck: {t1 - t0:.3f}s\")\n old_export_types = self.options.export_types\n self.options.export_types = self.options.export_types or export_types\n if not self.following_imports():\n messages = self.fine_grained_increment(\n sources, remove, update, explicit_export_types=export_types\n )\n else:\n assert remove is None and update is None\n messages = self.fine_grained_increment_follow_imports(\n sources, explicit_export_types=export_types\n )\n res = self.increment_output(messages, sources, is_tty, terminal_width)\n self.flush_caches()\n self.update_stats(res)\n self.options.export_types = old_export_types\n return res\n\n def check(\n self, sources: list[BuildSource], export_types: bool, is_tty: bool, terminal_width: int\n ) -> dict[str, Any]:\n \"\"\"Check using fine-grained incremental mode.\n\n If is_tty is True format the output nicely with colors and summary line\n (unless disabled in self.options). Also pass the terminal_width to formatter.\n \"\"\"\n old_export_types = self.options.export_types\n self.options.export_types = self.options.export_types or export_types\n if not self.fine_grained_manager:\n res = self.initialize_fine_grained(sources, is_tty, terminal_width)\n else:\n if not self.following_imports():\n messages = self.fine_grained_increment(sources, explicit_export_types=export_types)\n else:\n messages = self.fine_grained_increment_follow_imports(\n sources, explicit_export_types=export_types\n )\n res = self.increment_output(messages, sources, is_tty, terminal_width)\n self.flush_caches()\n self.update_stats(res)\n self.options.export_types = old_export_types\n return res\n\n def flush_caches(self) -> None:\n self.fscache.flush()\n if self.fine_grained_manager:\n self.fine_grained_manager.flush_cache()\n\n def update_stats(self, res: dict[str, Any]) -> None:\n if self.fine_grained_manager:\n manager = self.fine_grained_manager.manager\n manager.dump_stats()\n res[\"stats\"] = manager.stats\n manager.stats = {}\n\n def following_imports(self) -> bool:\n \"\"\"Are we following imports?\"\"\"\n # TODO: What about silent?\n return self.options.follow_imports == \"normal\"\n\n def initialize_fine_grained(\n self, sources: list[BuildSource], is_tty: bool, terminal_width: int\n ) -> dict[str, Any]:\n self.fswatcher = FileSystemWatcher(self.fscache)\n t0 = time.time()\n self.update_sources(sources)\n t1 = time.time()\n try:\n result = mypy.build.build(sources=sources, options=self.options, fscache=self.fscache)\n except mypy.errors.CompileError as e:\n output = \"\".join(s + \"\\n\" for s in e.messages)\n if e.use_stdout:\n out, err = output, \"\"\n else:\n out, err = \"\", output\n return {\"out\": out, \"err\": err, \"status\": 2}\n messages = result.errors\n self.fine_grained_manager = FineGrainedBuildManager(result)\n\n original_sources_len = len(sources)\n if self.following_imports():\n sources = find_all_sources_in_build(self.fine_grained_manager.graph, sources)\n self.update_sources(sources)\n\n self.previous_sources = sources\n\n # If we are using the fine-grained cache, build hasn't actually done\n # the typechecking on the updated files yet.\n # Run a fine-grained update starting from the cached data\n if result.used_cache:\n t2 = time.time()\n # Pull times and hashes out of the saved_cache and stick them into\n # the fswatcher, so we pick up the changes.\n for state in self.fine_grained_manager.graph.values():\n meta = state.meta\n if meta is None:\n continue\n assert state.path is not None\n self.fswatcher.set_file_data(\n state.path,\n FileData(st_mtime=float(meta.mtime), st_size=meta.size, hash=meta.hash),\n )\n\n changed, removed = self.find_changed(sources)\n changed += self.find_added_suppressed(\n self.fine_grained_manager.graph,\n set(),\n self.fine_grained_manager.manager.search_paths,\n )\n\n # Find anything that has had its dependency list change\n for state in self.fine_grained_manager.graph.values():\n if not state.is_fresh():\n assert state.path is not None\n changed.append((state.id, state.path))\n\n t3 = time.time()\n # Run an update\n messages = self.fine_grained_manager.update(changed, removed)\n\n if self.following_imports():\n # We need to do another update to any new files found by following imports.\n messages = self.fine_grained_increment_follow_imports(sources)\n\n t4 = time.time()\n self.fine_grained_manager.manager.add_stats(\n update_sources_time=t1 - t0,\n build_time=t2 - t1,\n find_changes_time=t3 - t2,\n fg_update_time=t4 - t3,\n files_changed=len(removed) + len(changed),\n )\n\n else:\n # Stores the initial state of sources as a side effect.\n self.fswatcher.find_changed()\n\n if MEM_PROFILE:\n from mypy.memprofile import print_memory_profile\n\n print_memory_profile(run_gc=False)\n\n __, n_notes, __ = count_stats(messages)\n status = 1 if messages and n_notes < len(messages) else 0\n # We use explicit sources length to match the logic in non-incremental mode.\n messages = self.pretty_messages(messages, original_sources_len, is_tty, terminal_width)\n return {\"out\": \"\".join(s + \"\\n\" for s in messages), \"err\": \"\", \"status\": status}\n\n def fine_grained_increment(\n self,\n sources: list[BuildSource],\n remove: list[str] | None = None,\n update: list[str] | None = None,\n explicit_export_types: bool = False,\n ) -> list[str]:\n \"\"\"Perform a fine-grained type checking increment.\n\n If remove and update are None, determine changed paths by using\n fswatcher. Otherwise, assume that only these files have changes.\n\n Args:\n sources: sources passed on the command line\n remove: paths of files that have been removed\n update: paths of files that have been changed or created\n explicit_export_types: --export-type was passed in a check command\n (as opposite to being set in dmypy start)\n \"\"\"\n assert self.fine_grained_manager is not None\n manager = self.fine_grained_manager.manager\n\n t0 = time.time()\n if remove is None and update is None:\n # Use the fswatcher to determine which files were changed\n # (updated or added) or removed.\n self.update_sources(sources)\n changed, removed = self.find_changed(sources)\n else:\n # Use the remove\/update lists to update fswatcher.\n # This avoids calling stat() for unchanged files.\n changed, removed = self.update_changed(sources, remove or [], update or [])\n if explicit_export_types:\n # If --export-types is given, we need to force full re-checking of all\n # explicitly passed files, since we need to visit each expression.\n add_all_sources_to_changed(sources, changed)\n changed += self.find_added_suppressed(\n self.fine_grained_manager.graph, set(), manager.search_paths\n )\n manager.search_paths = compute_search_paths(sources, manager.options, manager.data_dir)\n t1 = time.time()\n manager.log(f\"fine-grained increment: find_changed: {t1 - t0:.3f}s\")\n messages = self.fine_grained_manager.update(changed, removed)\n t2 = time.time()\n manager.log(f\"fine-grained increment: update: {t2 - t1:.3f}s\")\n manager.add_stats(\n find_changes_time=t1 - t0,\n fg_update_time=t2 - t1,\n files_changed=len(removed) + len(changed),\n )\n\n self.previous_sources = sources\n return messages\n\n def fine_grained_increment_follow_imports(\n self, sources: list[BuildSource], explicit_export_types: bool = False\n ) -> list[str]:\n \"\"\"Like fine_grained_increment, but follow imports.\"\"\"\n t0 = time.time()\n\n # TODO: Support file events\n\n assert self.fine_grained_manager is not None\n fine_grained_manager = self.fine_grained_manager\n graph = fine_grained_manager.graph\n manager = fine_grained_manager.manager\n\n orig_modules = list(graph.keys())\n\n self.update_sources(sources)\n changed_paths = self.fswatcher.find_changed()\n manager.search_paths = compute_search_paths(sources, manager.options, manager.data_dir)\n\n t1 = time.time()\n manager.log(f\"fine-grained increment: find_changed: {t1 - t0:.3f}s\")\n\n 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 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_supressed_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 # 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 # 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 cmd_inspect(\n self,\n show: str,\n location: str,\n verbosity: int = 0,\n limit: int = 0,\n include_span: bool = False,\n include_kind: bool = False,\n include_object_attrs: bool = False,\n union_attrs: bool = False,\n force_reload: bool = False,\n ) -> dict[str, object]:\n \"\"\"Locate and inspect expression(s).\"\"\"\n if not self.fine_grained_manager:\n return {\n \"error\": 'Command \"inspect\" is only valid after a \"check\" command'\n \" (that produces no parse errors)\"\n }\n engine = InspectionEngine(\n self.fine_grained_manager,\n verbosity=verbosity,\n limit=limit,\n include_span=include_span,\n include_kind=include_kind,\n include_object_attrs=include_object_attrs,\n union_attrs=union_attrs,\n force_reload=force_reload,\n )\n old_inspections = self.options.inspections\n self.options.inspections = True\n try:\n if show == \"type\":\n result = engine.get_type(location)\n elif show == \"attrs\":\n result = engine.get_attrs(location)\n elif show == \"definition\":\n result = engine.get_definition(location)\n else:\n assert False, \"Unknown inspection kind\"\n finally:\n self.options.inspections = old_inspections\n if \"out\" in result:\n assert isinstance(result[\"out\"], str)\n result[\"out\"] += \"\\n\"\n return result\n\n def cmd_suggest(self, function: str, callsites: bool, **kwargs: Any) -> dict[str, object]:\n \"\"\"Suggest a signature for a function.\"\"\"\n if not self.fine_grained_manager:\n return {\n \"error\": \"Command 'suggest' is only valid after a 'check' command\"\n \" (that produces no parse errors)\"\n }\n engine = SuggestionEngine(self.fine_grained_manager, **kwargs)\n try:\n if callsites:\n out = engine.suggest_callsites(function)\n else:\n out = engine.suggest(function)\n except SuggestionFailure as err:\n return {\"error\": str(err)}\n else:\n if not out:\n out = \"No suggestions\\n\"\n elif not out.endswith(\"\\n\"):\n out += \"\\n\"\n return {\"out\": out, \"err\": \"\", \"status\": 0}\n finally:\n self.flush_caches()\n\n def cmd_hang(self) -> dict[str, object]:\n \"\"\"Hang for 100 seconds, as a debug hack.\"\"\"\n time.sleep(100)\n return {}\n\n\n# Misc utilities.\n\n\nMiB: Final = 2**20\n\n\ndef get_meminfo() -> dict[str, Any]:\n res: dict[str, Any] = {}\n try:\n import psutil\n except ImportError:\n res[\"memory_psutil_missing\"] = (\n \"psutil not found, run pip install mypy[dmypy] \"\n \"to install the needed components for dmypy\"\n )\n else:\n process = psutil.Process()\n meminfo = process.memory_info()\n res[\"memory_rss_mib\"] = meminfo.rss \/ MiB\n res[\"memory_vms_mib\"] = meminfo.vms \/ MiB\n if sys.platform == \"win32\":\n res[\"memory_maxrss_mib\"] = meminfo.peak_wset \/ MiB\n else:\n # See https:\/\/stackoverflow.com\/questions\/938733\/total-memory-used-by-python-process\n import resource # Since it doesn't exist on Windows.\n\n rusage = resource.getrusage(resource.RUSAGE_SELF)\n if sys.platform == \"darwin\":\n factor = 1\n else:\n factor = 1024 # Linux\n res[\"memory_maxrss_mib\"] = rusage.ru_maxrss * factor \/ MiB\n return res\n\n\ndef find_all_sources_in_build(\n graph: mypy.build.Graph, extra: Sequence[BuildSource] = ()\n) -> list[BuildSource]:\n result = list(extra)\n seen = {source.module for source in result}\n for module, state in graph.items():\n if module not in seen:\n result.append(BuildSource(state.path, module))\n return result\n\n\ndef add_all_sources_to_changed(sources: list[BuildSource], changed: list[tuple[str, str]]) -> None:\n \"\"\"Add all (explicit) sources to the list changed files in place.\n\n Use this when re-processing of unchanged files is needed (e.g. for\n the purpose of exporting types for inspections).\n \"\"\"\n changed_set = set(changed)\n changed.extend(\n [\n (bs.module, bs.path)\n for bs in sources\n if bs.path and (bs.module, bs.path) not in changed_set\n ]\n )\n\n\ndef fix_module_deps(graph: mypy.build.Graph) -> None:\n \"\"\"After an incremental update, update module dependencies to reflect the new state.\n\n This can make some suppressed dependencies non-suppressed, and vice versa (if modules\n have been added to or removed from the build).\n \"\"\"\n for state in graph.values():\n new_suppressed = []\n new_dependencies = []\n for dep in state.dependencies + state.suppressed:\n if dep in graph:\n new_dependencies.append(dep)\n else:\n new_suppressed.append(dep)\n state.dependencies = new_dependencies\n state.dependencies_set = set(new_dependencies)\n state.suppressed = new_suppressed\n state.suppressed_set = set(new_suppressed)\n\n\ndef filter_out_missing_top_level_packages(\n packages: set[str], search_paths: SearchPaths, fscache: FileSystemCache\n) -> set[str]:\n \"\"\"Quickly filter out obviously missing top-level packages.\n\n Return packages with entries that can't be found removed.\n\n This is approximate: some packages that aren't actually valid may be\n included. However, all potentially valid packages must be returned.\n \"\"\"\n # Start with a empty set and add all potential top-level packages.\n found = set()\n paths = (\n search_paths.python_path\n + search_paths.mypy_path\n + search_paths.package_path\n + search_paths.typeshed_path\n )\n for p in paths:\n try:\n entries = fscache.listdir(p)\n except Exception:\n entries = []\n for entry in entries:\n # The code is hand-optimized for mypyc since this may be somewhat\n # performance-critical.\n if entry.endswith(\".py\"):\n entry = entry[:-3]\n elif entry.endswith(\".pyi\"):\n entry = entry[:-4]\n elif entry.endswith(\"-stubs\"):\n # Possible PEP 561 stub package\n entry = entry[:-6]\n if entry in packages:\n found.add(entry)\n return found\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/dmypy_server.py","language":"Python","license":"NOASSERTION","size":44745} {"code":"\"\"\"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 types import TracebackType\nfrom typing import Any, Final, Iterable, Iterator, 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] = {}\n resp[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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/dmypy_util.py","language":"Python","license":"NOASSERTION","size":2995} {"code":"from __future__ import annotations\n\nfrom typing import Callable, Container, cast\n\nfrom mypy.nodes import ARG_STAR, ARG_STAR2\nfrom mypy.types import (\n AnyType,\n CallableType,\n DeletedType,\n ErasedType,\n Instance,\n LiteralType,\n NoneType,\n Overloaded,\n Parameters,\n ParamSpecType,\n PartialType,\n ProperType,\n TupleType,\n Type,\n TypeAliasType,\n TypedDictType,\n TypeOfAny,\n TypeTranslator,\n TypeType,\n TypeVarId,\n TypeVarTupleType,\n TypeVarType,\n TypeVisitor,\n UnboundType,\n UninhabitedType,\n UnionType,\n UnpackType,\n get_proper_type,\n get_proper_types,\n)\nfrom mypy.typevartuples import erased_vars\n\n\ndef erase_type(typ: Type) -> ProperType:\n \"\"\"Erase any type variables from a type.\n\n Also replace tuple types with the corresponding concrete types.\n\n Examples:\n A -> A\n B[X] -> B[Any]\n Tuple[A, B] -> tuple\n Callable[[A1, A2, ...], R] -> Callable[..., Any]\n Type[X] -> Type[Any]\n \"\"\"\n typ = get_proper_type(typ)\n return typ.accept(EraseTypeVisitor())\n\n\nclass EraseTypeVisitor(TypeVisitor[ProperType]):\n def visit_unbound_type(self, t: UnboundType) -> ProperType:\n # TODO: replace with an assert after UnboundType can't leak from semantic analysis.\n return AnyType(TypeOfAny.from_error)\n\n def visit_any(self, t: AnyType) -> ProperType:\n return t\n\n def visit_none_type(self, t: NoneType) -> ProperType:\n return t\n\n def visit_uninhabited_type(self, t: UninhabitedType) -> ProperType:\n return t\n\n def visit_erased_type(self, t: ErasedType) -> ProperType:\n return t\n\n def visit_partial_type(self, t: PartialType) -> ProperType:\n # Should not get here.\n raise RuntimeError(\"Cannot erase partial types\")\n\n def visit_deleted_type(self, t: DeletedType) -> ProperType:\n return t\n\n def visit_instance(self, t: Instance) -> ProperType:\n args = erased_vars(t.type.defn.type_vars, TypeOfAny.special_form)\n return Instance(t.type, args, t.line)\n\n def visit_type_var(self, t: TypeVarType) -> ProperType:\n return AnyType(TypeOfAny.special_form)\n\n def visit_param_spec(self, t: ParamSpecType) -> ProperType:\n return AnyType(TypeOfAny.special_form)\n\n def visit_parameters(self, t: Parameters) -> ProperType:\n raise RuntimeError(\"Parameters should have been bound to a class\")\n\n def visit_type_var_tuple(self, t: TypeVarTupleType) -> ProperType:\n # Likely, we can never get here because of aggressive erasure of types that\n # can contain this, but better still return a valid replacement.\n return t.tuple_fallback.copy_modified(args=[AnyType(TypeOfAny.special_form)])\n\n def visit_unpack_type(self, t: UnpackType) -> ProperType:\n return AnyType(TypeOfAny.special_form)\n\n def visit_callable_type(self, t: CallableType) -> ProperType:\n # We must preserve the fallback type for overload resolution to work.\n any_type = AnyType(TypeOfAny.special_form)\n return CallableType(\n arg_types=[any_type, any_type],\n arg_kinds=[ARG_STAR, ARG_STAR2],\n arg_names=[None, None],\n ret_type=any_type,\n fallback=t.fallback,\n is_ellipsis_args=True,\n implicit=True,\n )\n\n def visit_overloaded(self, t: Overloaded) -> ProperType:\n return t.fallback.accept(self)\n\n def visit_tuple_type(self, t: TupleType) -> ProperType:\n return t.partial_fallback.accept(self)\n\n def visit_typeddict_type(self, t: TypedDictType) -> ProperType:\n return t.fallback.accept(self)\n\n def visit_literal_type(self, t: LiteralType) -> ProperType:\n # The fallback for literal types should always be either\n # something like int or str, or an enum class -- types that\n # don't contain any TypeVars. So there's no need to visit it.\n return t\n\n def visit_union_type(self, t: UnionType) -> ProperType:\n erased_items = [erase_type(item) for item in t.items]\n from mypy.typeops import make_simplified_union\n\n return make_simplified_union(erased_items)\n\n def visit_type_type(self, t: TypeType) -> ProperType:\n return TypeType.make_normalized(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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/erasetype.py","language":"Python","license":"NOASSERTION","size":10059} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/error_formatter.py","language":"Python","license":"NOASSERTION","size":1115} {"code":"\"\"\"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\"\"\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)\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)\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)\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\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\n# This copy will not include any error codes defined later in the plugins.\nmypy_error_codes = error_codes.copy()\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/errorcodes.py","language":"Python","license":"NOASSERTION","size":11169} {"code":"from __future__ import annotations\n\nimport os.path\nimport sys\nimport traceback\nfrom collections import defaultdict\nfrom typing import Callable, Final, Iterable, NoReturn, Optional, TextIO, Tuple, TypeVar\nfrom typing_extensions import Literal, TypeAlias as _TypeAlias\n\nfrom mypy import errorcodes as codes\nfrom mypy.error_formatter import ErrorFormatter\nfrom mypy.errorcodes import IMPORT, IMPORT_NOT_FOUND, IMPORT_UNTYPED, ErrorCode, mypy_error_codes\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 __version__ as mypy_version\n\nT = TypeVar(\"T\")\n\n# Show error codes for some note-level messages (these usually appear alone\n# and not as a comment for a previous error-level message).\nSHOW_NOTE_CODES: Final = {codes.ANNOTATION_UNCHECKED}\n\n# Do not add notes with links to error code docs to errors with these codes.\n# We can tweak this set as we get more experience about what is helpful and what is not.\nHIDE_LINK_CODES: Final = {\n # This is a generic error code, so it has no useful docs\n codes.MISC,\n # These are trivial and have some custom notes (e.g. for list being invariant)\n codes.ASSIGNMENT,\n codes.ARG_TYPE,\n codes.RETURN_VALUE,\n # Undefined name\/attribute errors are self-explanatory\n codes.ATTR_DEFINED,\n codes.NAME_DEFINED,\n # Overrides have a custom link to docs\n codes.OVERRIDE,\n}\n\nallowed_duplicates: Final = [\"@overload\", \"Got:\", \"Expected:\"]\n\nBASE_RTD_URL: Final = \"https:\/\/mypy.rtfd.io\/en\/stable\/_refs.html#code\"\n\n# Keep track of the original error code when the error code of a message is changed.\n# This is used to give notes about out-of-date \"type: ignore\" comments.\noriginal_error_codes: Final = {codes.LITERAL_REQ: codes.MISC, codes.TYPE_ABSTRACT: codes.MISC}\n\n\nclass ErrorInfo:\n \"\"\"Representation of a single error message.\"\"\"\n\n # Description of a sequence of imports that refer to the source file\n # related to this error. Each item is a (path, line number) tuple.\n import_ctx: list[tuple[str, int]]\n\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 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.priority = priority\n\n\n# Type used internally to represent errors:\n# (path, line, column, end_line, end_column, severity, message, allow_dups, code)\nErrorTuple: _TypeAlias = Tuple[\n Optional[str], int, int, int, int, str, str, bool, Optional[ErrorCode]\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 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 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 # Ths 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 def __init__(\n self,\n options: Options,\n *,\n read_source: Callable[[str], list[str] | None] | None = None,\n hide_error_codes: bool | None = None,\n ) -> None:\n self.options = options\n self.hide_error_codes = (\n hide_error_codes if hide_error_codes is not None else options.hide_error_codes\n )\n # We use fscache to read source code when showing snippets.\n self.read_source = read_source\n self.initialize()\n\n def initialize(self) -> None:\n self.error_info_map = {}\n self.flushed_files = set()\n self.import_ctx = []\n self.function_or_member = [None]\n self.ignored_lines = {}\n self.skipped_lines = {}\n self.used_ignored_lines = defaultdict(lambda: defaultdict(list))\n self.ignored_files = set()\n self.only_once_messages = set()\n self.has_blockers = set()\n self.scope = None\n self.target_module = None\n self.seen_import_error = False\n\n def reset(self) -> None:\n self.initialize()\n\n def set_ignore_prefix(self, prefix: str) -> None:\n \"\"\"Set path prefix that will be removed from all paths.\"\"\"\n prefix = os.path.normpath(prefix)\n # Add separator to the end, if not given.\n if os.path.basename(prefix) != \"\":\n prefix += os.sep\n self.ignore_prefix = prefix\n\n def simplify_path(self, file: str) -> str:\n if self.options.show_absolute_path:\n return os.path.abspath(file)\n else:\n file = os.path.normpath(file)\n return remove_path_prefix(file, self.ignore_prefix)\n\n def set_file(\n self, file: str, module: str | None, options: Options, scope: Scope | None = None\n ) -> None:\n \"\"\"Set the path and module id of the current file.\"\"\"\n # The path will be simplified later, in render_messages. That way\n # * 'file' is always a key that uniquely identifies a source file\n # that mypy read (simplified paths might not be unique); and\n # * we only have to simplify in one place, while still supporting\n # reporting errors for files other than the one currently being\n # processed.\n self.file = file\n self.target_module = module\n self.scope = scope\n self.options = options\n\n def set_file_ignored_lines(\n self, file: str, ignored_lines: dict[int, list[str]], ignore_all: bool = False\n ) -> None:\n self.ignored_lines[file] = ignored_lines\n if ignore_all:\n self.ignored_files.add(file)\n\n def set_skipped_lines(self, file: str, skipped_lines: set[int]) -> None:\n self.skipped_lines[file] = skipped_lines\n\n def current_target(self) -> str | None:\n \"\"\"Retrieves the current target from the associated scope.\n\n If there is no associated scope, use the target module.\"\"\"\n if self.scope is not None:\n return self.scope.current_target()\n return self.target_module\n\n def current_module(self) -> str | None:\n return self.target_module\n\n def import_context(self) -> list[tuple[str, int]]:\n \"\"\"Return a copy of the import context.\"\"\"\n return self.import_ctx.copy()\n\n def set_import_context(self, ctx: list[tuple[str, int]]) -> None:\n \"\"\"Replace the entire import context with a new value.\"\"\"\n self.import_ctx = ctx.copy()\n\n def report(\n self,\n line: int,\n column: int | None,\n message: str,\n code: ErrorCode | None = None,\n *,\n blocker: bool = False,\n severity: str = \"error\",\n 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 ) -> 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\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:\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 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 message in self.only_once_messages:\n return\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 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 # 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\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 ) 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 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 file_messages(self, path: str, formatter: ErrorFormatter | None = None) -> 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 if path not in self.error_info_map:\n return []\n\n error_info = self.error_info_map[path]\n error_info = [info for info in error_info if not info.hidden]\n error_tuples = self.render_messages(self.sort_messages(error_info))\n error_tuples = self.remove_duplicates(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 source_lines = self.read_source(path)\n return self.format_messages(error_tuples, source_lines)\n\n def new_messages(self) -> list[str]:\n \"\"\"Return a string list of new error messages.\n\n Use a form suitable for displaying to the user.\n Errors from different files are ordered based on the order in which\n they first generated an error.\n \"\"\"\n msgs = []\n for path in self.error_info_map.keys():\n if path not in self.flushed_files:\n msgs.extend(self.file_messages(path))\n return msgs\n\n def targets(self) -> set[str]:\n \"\"\"Return a set of all targets that contain errors.\"\"\"\n # TODO: Make sure that either target is always defined or that not being defined\n # is okay for fine-grained incremental checking.\n return {\n info.target for errs in self.error_info_map.values() for info in errs if info.target\n }\n\n def render_messages(self, errors: list[ErrorInfo]) -> list[ErrorTuple]:\n \"\"\"Translate the messages into a sequence of tuples.\n\n Each tuple is of form (path, line, col, severity, message, 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 (None, -1, -1, -1, -1, \"note\", fmt.format(path, line), e.allow_dups, None)\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 (file, -1, -1, -1, -1, \"note\", \"At top level:\", e.allow_dups, None)\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 )\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 )\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 )\n )\n elif e.type != prev_type:\n if e.type is None:\n result.append(\n (file, -1, -1, -1, -1, \"note\", \"At top level:\", e.allow_dups, None)\n )\n else:\n result.append(\n (file, -1, -1, -1, -1, \"note\", f'In class \"{e.type}\":', e.allow_dups, None)\n )\n\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 )\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 )\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 j >= 0 and errors[j][0] == errors[i][0] and errors[j][1] == errors[i][1]:\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\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 mypy master on GitHub:\\n\"\n \"https:\/\/mypy.readthedocs.io\/en\/stable\/common_issues.html\"\n \"#using-a-development-mypy-build\",\n file=stderr,\n )\n if options.show_traceback:\n print(\"Please report a bug at https:\/\/github.com\/python\/mypy\/issues\", file=stderr)\n else:\n print(\n \"If this issue continues with mypy master, \"\n \"please report a bug at https:\/\/github.com\/python\/mypy\/issues\",\n file=stderr,\n )\n print(f\"version: {mypy_version}\", file=stderr)\n\n # If requested, drop into pdb. This overrides show_tb.\n if options.pdb:\n print(\"Dropping into pdb\", file=stderr)\n import pdb\n\n pdb.post_mortem(sys.exc_info()[2])\n\n # If requested, print traceback, else print note explaining how to get one.\n if options.raise_exceptions:\n raise err\n if not options.show_traceback:\n if not options.pdb:\n print(\n \"{}: note: please use --show-traceback to print a traceback \"\n \"when reporting a bug\".format(prefix),\n file=stderr,\n )\n else:\n tb = traceback.extract_stack()[:-2]\n tb2 = traceback.extract_tb(sys.exc_info()[2])\n print(\"Traceback (most recent call last):\")\n for s in traceback.format_list(tb + tb2):\n print(s.rstrip(\"\\n\"))\n print(f\"{type(err).__name__}: {err}\", file=stdout)\n print(f\"{prefix}: note: use --pdb to drop into pdb\", file=stderr)\n\n # Exit. The caller has nothing more to say.\n # We use exit code 2 to signal that this is no ordinary error.\n raise SystemExit(2)\n\n\nclass MypyError:\n def __init__(\n self,\n file_path: str,\n line: int,\n column: int,\n 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/errors.py","language":"Python","license":"NOASSERTION","size":49818} {"code":"\"\"\"\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/evalexpr.py","language":"Python","license":"NOASSERTION","size":6562} {"code":"from __future__ import annotations\n\nfrom typing import Final, Iterable, Mapping, Sequence, 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 LiteralType,\n NoneType,\n Overloaded,\n Parameters,\n ParamSpecFlavor,\n ParamSpecType,\n PartialType,\n ProperType,\n TrivialSyntheticTypeTranslator,\n TupleType,\n Type,\n TypeAliasType,\n TypedDictType,\n TypeOfAny,\n TypeType,\n TypeVarId,\n TypeVarLikeType,\n TypeVarTupleType,\n TypeVarType,\n UnboundType,\n UninhabitedType,\n UnionType,\n UnpackType,\n flatten_nested_unions,\n get_proper_type,\n split_with_prefix_and_suffix,\n)\nfrom mypy.typevartuples import split_with_instance\n\n# Solving the import cycle:\nimport mypy.type_visitor # ruff: isort: skip\n\n# WARNING: these functions should never (directly or indirectly) depend on\n# is_subtype(), meet_types(), join_types() etc.\n# TODO: add a static dependency test for this.\n\n\n@overload\ndef expand_type(typ: CallableType, env: Mapping[TypeVarId, Type]) -> CallableType: ...\n\n\n@overload\ndef expand_type(typ: ProperType, env: Mapping[TypeVarId, Type]) -> ProperType: ...\n\n\n@overload\ndef expand_type(typ: Type, env: Mapping[TypeVarId, Type]) -> Type: ...\n\n\ndef expand_type(typ: Type, env: Mapping[TypeVarId, Type]) -> Type:\n \"\"\"Substitute any type variable references in a type given by a type\n environment.\n \"\"\"\n return typ.accept(ExpandTypeVisitor(env))\n\n\n@overload\ndef expand_type_by_instance(typ: CallableType, instance: Instance) -> CallableType: ...\n\n\n@overload\ndef expand_type_by_instance(typ: ProperType, instance: Instance) -> ProperType: ...\n\n\n@overload\ndef expand_type_by_instance(typ: Type, instance: Instance) -> Type: ...\n\n\ndef expand_type_by_instance(typ: Type, instance: Instance) -> Type:\n \"\"\"Substitute type variables in type using values from an Instance.\n Type variables are considered to be bound by the class declaration.\"\"\"\n if not instance.args and not instance.type.has_type_var_tuple_type:\n return typ\n else:\n variables: dict[TypeVarId, Type] = {}\n if instance.type.has_type_var_tuple_type:\n assert instance.type.type_var_tuple_prefix is not None\n assert instance.type.type_var_tuple_suffix is not None\n\n args_prefix, args_middle, args_suffix = split_with_instance(instance)\n tvars_prefix, tvars_middle, tvars_suffix = split_with_prefix_and_suffix(\n tuple(instance.type.defn.type_vars),\n instance.type.type_var_tuple_prefix,\n instance.type.type_var_tuple_suffix,\n )\n tvar = tvars_middle[0]\n assert isinstance(tvar, TypeVarTupleType)\n variables = {tvar.id: TupleType(list(args_middle), tvar.tuple_fallback)}\n instance_args = args_prefix + args_suffix\n tvars = tvars_prefix + tvars_suffix\n else:\n tvars = tuple(instance.type.defn.type_vars)\n instance_args = instance.args\n\n for binder, arg in zip(tvars, instance_args):\n assert isinstance(binder, TypeVarLikeType)\n variables[binder.id] = arg\n\n return expand_type(typ, variables)\n\n\nF = TypeVar(\"F\", bound=FunctionLike)\n\n\ndef freshen_function_type_vars(callee: F) -> F:\n \"\"\"Substitute fresh type variables for generic function type variables.\"\"\"\n if isinstance(callee, CallableType):\n if not callee.is_generic():\n return cast(F, callee)\n tvs = []\n tvmap: dict[TypeVarId, Type] = {}\n for v in callee.variables:\n tv = v.new_unification_variable(v)\n tvs.append(tv)\n tvmap[v.id] = tv\n fresh = expand_type(callee, tvmap).copy_modified(variables=tvs)\n return cast(F, fresh)\n else:\n assert isinstance(callee, Overloaded)\n fresh_overload = Overloaded([freshen_function_type_vars(item) for item in callee.items])\n return cast(F, fresh_overload)\n\n\nclass HasGenericCallable(BoolTypeQuery):\n def __init__(self) -> None:\n super().__init__(ANY_STRATEGY)\n\n def visit_callable_type(self, t: CallableType) -> bool:\n return t.is_generic() or super().visit_callable_type(t)\n\n\n# Share a singleton since this is performance sensitive\nhas_generic_callable: Final = HasGenericCallable()\n\n\nT = TypeVar(\"T\", bound=Type)\n\n\ndef freshen_all_functions_type_vars(t: T) -> T:\n result: Type\n has_generic_callable.reset()\n if not t.accept(has_generic_callable):\n return t # Fast path to avoid expensive freshening\n else:\n result = t.accept(FreshenCallableVisitor())\n assert isinstance(result, type(t))\n return result\n\n\nclass FreshenCallableVisitor(mypy.type_visitor.TypeTranslator):\n def visit_callable_type(self, t: CallableType) -> Type:\n result = super().visit_callable_type(t)\n assert isinstance(result, ProperType) and isinstance(result, CallableType)\n return freshen_function_type_vars(result)\n\n def visit_type_alias_type(self, t: TypeAliasType) -> Type:\n # Same as for ExpandTypeVisitor\n return t.copy_modified(args=[arg.accept(self) for arg in t.args])\n\n\nclass ExpandTypeVisitor(TrivialSyntheticTypeTranslator):\n \"\"\"Visitor that substitutes type variables with values.\"\"\"\n\n variables: Mapping[TypeVarId, Type] # TypeVar id -> TypeVar value\n\n def __init__(self, variables: Mapping[TypeVarId, Type]) -> None:\n super().__init__()\n self.variables = variables\n self.recursive_tvar_guard: dict[TypeVarId, Type | None] = {}\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 (\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.accept(self) if t.type_guard is not None else None),\n type_is=(t.type_is.accept(self) if t.type_is is not None else None),\n imprecise_arg_kinds=(t.imprecise_arg_kinds or repl.imprecise_arg_kinds),\n variables=[*repl.variables, *t.variables],\n )\n var_arg = expanded.var_arg()\n if var_arg is not None and isinstance(var_arg.typ, UnpackType):\n # Sometimes we get new unpacks after expanding ParamSpec.\n expanded.normalize_trivial_unpack()\n return expanded\n elif isinstance(repl, ParamSpecType):\n # We're substituting one ParamSpec for another; this can mean that the prefix\n # changes, e.g. substitute Concatenate[int, P] in place of Q.\n prefix = repl.prefix\n clean_repl = repl.copy_modified(prefix=Parameters([], [], []))\n return t.copy_modified(\n arg_types=self.expand_types(t.arg_types[:-2])\n + prefix.arg_types\n + [\n clean_repl.with_flavor(ParamSpecFlavor.ARGS),\n clean_repl.with_flavor(ParamSpecFlavor.KWARGS),\n ],\n arg_kinds=t.arg_kinds[:-2] + prefix.arg_kinds + t.arg_kinds[-2:],\n arg_names=t.arg_names[:-2] + prefix.arg_names + t.arg_names[-2:],\n ret_type=t.ret_type.accept(self),\n from_concatenate=t.from_concatenate or bool(repl.prefix.arg_types),\n imprecise_arg_kinds=(t.imprecise_arg_kinds or prefix.imprecise_arg_kinds),\n )\n\n var_arg = t.var_arg()\n needs_normalization = False\n if var_arg is not None and isinstance(var_arg.typ, UnpackType):\n needs_normalization = True\n arg_types = self.interpolate_args_for_unpack(t, var_arg.typ)\n else:\n arg_types = self.expand_types(t.arg_types)\n expanded = t.copy_modified(\n arg_types=arg_types,\n ret_type=t.ret_type.accept(self),\n type_guard=(t.type_guard.accept(self) if t.type_guard is not None else None),\n type_is=(t.type_is.accept(self) if t.type_is is not None else None),\n )\n if needs_normalization:\n return expanded.with_normalized_var_args()\n return expanded\n\n def visit_overloaded(self, t: Overloaded) -> Type:\n items: list[CallableType] = []\n for item in t.items:\n new_item = item.accept(self)\n assert isinstance(new_item, ProperType)\n assert isinstance(new_item, CallableType)\n items.append(new_item)\n return Overloaded(items)\n\n def expand_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_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 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/expandtype.py","language":"Python","license":"NOASSERTION","size":23834} {"code":"\"\"\"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 AnyType,\n CallableArgument,\n EllipsisType,\n Instance,\n ProperType,\n RawExpressionType,\n Type,\n TypedDictType,\n TypeList,\n TypeOfAny,\n UnboundType,\n UnionType,\n UnpackType,\n)\n\n\nclass TypeTranslationError(Exception):\n \"\"\"Exception raised when an expression is not valid as a type.\"\"\"\n\n\ndef _extract_argument_name(expr: Expression) -> str | None:\n if isinstance(expr, NameExpr) and expr.name == \"None\":\n return None\n elif isinstance(expr, StrExpr):\n return expr.value\n else:\n raise TypeTranslationError()\n\n\ndef expr_to_unanalyzed_type(\n expr: Expression,\n options: Options,\n allow_new_syntax: bool = False,\n _parent: Expression | None = None,\n allow_unpack: bool = False,\n lookup_qualified: Callable[[str, Context], SymbolTableNode | None] | None = None,\n) -> ProperType:\n \"\"\"Translate an expression to the corresponding type.\n\n The result is not semantically analyzed. It can be UnboundType or TypeList.\n Raise TypeTranslationError if the expression cannot represent a type.\n\n If lookup_qualified is not provided, the expression is expected to be semantically\n analyzed.\n\n If allow_new_syntax is True, allow all type syntax independent of the target\n Python version (used in stubs).\n\n # TODO: a lot of code here is duplicated in fastparse.py, refactor this.\n \"\"\"\n # The `parent` parameter is used in recursive calls to provide context for\n # understanding whether an CallableArgument is ok.\n name: str | None = None\n if isinstance(expr, NameExpr):\n name = expr.name\n if name == \"True\":\n return RawExpressionType(True, \"builtins.bool\", line=expr.line, column=expr.column)\n elif name == \"False\":\n return RawExpressionType(False, \"builtins.bool\", line=expr.line, column=expr.column)\n else:\n return UnboundType(name, line=expr.line, column=expr.column)\n elif isinstance(expr, MemberExpr):\n fullname = get_member_expr_fullname(expr)\n if fullname:\n return UnboundType(fullname, line=expr.line, column=expr.column)\n else:\n raise TypeTranslationError()\n elif isinstance(expr, IndexExpr):\n base = expr_to_unanalyzed_type(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 (\n isinstance(expr, OpExpr)\n and expr.op == \"|\"\n and ((options.python_version >= (3, 10)) or allow_new_syntax)\n ):\n return UnionType(\n [\n expr_to_unanalyzed_type(expr.left, options, allow_new_syntax),\n expr_to_unanalyzed_type(expr.right, options, allow_new_syntax),\n ],\n uses_pep604_syntax=True,\n )\n elif isinstance(expr, CallExpr) and isinstance(_parent, ListExpr):\n c = expr.callee\n names = []\n # Go through the dotted member expr chain to get the full arg\n # constructor name to look up\n while True:\n if isinstance(c, NameExpr):\n names.append(c.name)\n break\n elif isinstance(c, MemberExpr):\n names.append(c.name)\n c = c.expr\n else:\n raise TypeTranslationError()\n arg_const = \".\".join(reversed(names))\n\n # Go through the constructor args to get its name and type.\n name = None\n default_type = AnyType(TypeOfAny.unannotated)\n typ: Type = default_type\n for i, arg in enumerate(expr.args):\n if expr.arg_names[i] is not None:\n if expr.arg_names[i] == \"name\":\n if name is not None:\n # Two names\n raise TypeTranslationError()\n name = _extract_argument_name(arg)\n continue\n elif expr.arg_names[i] == \"type\":\n if typ is not default_type:\n # Two types\n raise TypeTranslationError()\n typ = expr_to_unanalyzed_type(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(expr.value, \"builtins.int\", line=expr.line, column=expr.column)\n elif isinstance(expr, FloatExpr):\n # Floats are not valid parameters for RawExpressionType , so we just\n # pass in 'None' for now. We'll report the appropriate error at a later stage.\n return RawExpressionType(None, \"builtins.float\", line=expr.line, column=expr.column)\n elif isinstance(expr, ComplexExpr):\n # Same thing as above with complex numbers.\n return RawExpressionType(None, \"builtins.complex\", line=expr.line, column=expr.column)\n elif isinstance(expr, EllipsisExpr):\n return EllipsisType(expr.line)\n elif allow_unpack and isinstance(expr, StarExpr):\n return UnpackType(\n expr_to_unanalyzed_type(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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/exprtotype.py","language":"Python","license":"NOASSERTION","size":9431} {"code":"from __future__ import annotations\n\nimport copy\nimport re\nimport sys\nimport warnings\nfrom typing import Any, Callable, Final, List, Optional, Sequence, TypeVar, Union, cast\nfrom typing_extensions import Literal, overload\n\nfrom mypy import defaults, errorcodes as codes, message_registry\nfrom mypy.errors import Errors\nfrom mypy.message_registry import ErrorMessage\nfrom mypy.nodes import (\n ARG_NAMED,\n ARG_NAMED_OPT,\n ARG_OPT,\n ARG_POS,\n ARG_STAR,\n ARG_STAR2,\n MISSING_FALLBACK,\n PARAM_SPEC_KIND,\n TYPE_VAR_KIND,\n TYPE_VAR_TUPLE_KIND,\n ArgKind,\n Argument,\n AssertStmt,\n AssignmentExpr,\n AssignmentStmt,\n AwaitExpr,\n Block,\n BreakStmt,\n BytesExpr,\n CallExpr,\n ClassDef,\n ComparisonExpr,\n ComplexExpr,\n ConditionalExpr,\n ContinueStmt,\n Decorator,\n DelStmt,\n DictExpr,\n DictionaryComprehension,\n EllipsisExpr,\n Expression,\n ExpressionStmt,\n FloatExpr,\n ForStmt,\n FuncDef,\n GeneratorExpr,\n GlobalDecl,\n IfStmt,\n Import,\n ImportAll,\n ImportBase,\n ImportFrom,\n IndexExpr,\n IntExpr,\n LambdaExpr,\n ListComprehension,\n ListExpr,\n MatchStmt,\n MemberExpr,\n MypyFile,\n NameExpr,\n Node,\n NonlocalDecl,\n OperatorAssignmentStmt,\n OpExpr,\n OverloadedFuncDef,\n OverloadPart,\n PassStmt,\n RaiseStmt,\n RefExpr,\n ReturnStmt,\n SetComprehension,\n SetExpr,\n SliceExpr,\n StarExpr,\n Statement,\n StrExpr,\n SuperExpr,\n 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 ProperType,\n RawExpressionType,\n TupleType,\n Type,\n TypedDictType,\n TypeList,\n TypeOfAny,\n UnboundType,\n UnionType,\n UnpackType,\n)\nfrom mypy.util import bytes_to_human_readable_repr, unnamed_function\n\n# pull this into a final variable to make mypyc be quiet about the\n# the default argument warning\nPY_MINOR_VERSION: Final = sys.version_info[1]\n\nimport ast as ast3\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\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 # alias to please mypyc\n is_py38_or_earlier = sys.version_info < (3, 9)\n if is_py38_or_earlier and e.filename == \"\":\n # In Python 3.8 and earlier, syntax errors in f-strings have lineno relative to the\n # start of the f-string. This would be misleading, as mypy will report the error as the\n # lineno within the file.\n e.lineno = None\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\n) -> tuple[list[str] | None, ProperType | None]:\n \"\"\"Parse type portion of a type comment (+ optional type ignore).\n\n Return (ignore info, parsed type).\n \"\"\"\n try:\n typ = ast3_parse(type_comment, \"\", \"eval\")\n except SyntaxError:\n if errors is not None:\n stripped_type = type_comment.split(\"#\", 2)[0].strip()\n err_msg = message_registry.TYPE_COMMENT_SYNTAX_ERROR_VALUE.format(stripped_type)\n errors.report(line, column, err_msg.value, blocker=True, code=err_msg.code)\n return None, None\n else:\n raise\n else:\n extra_ignore = TYPE_IGNORE_PATTERN.match(type_comment)\n if extra_ignore:\n tag: str | None = extra_ignore.group(1)\n ignored: list[str] | None = parse_type_ignore_tag(tag)\n if ignored is None:\n if errors is not None:\n errors.report(\n line, column, message_registry.INVALID_TYPE_IGNORE.value, code=codes.SYNTAX\n )\n else:\n raise SyntaxError\n else:\n ignored = None\n assert isinstance(typ, ast3.Expression)\n converted = TypeConverter(\n errors, line=line, override_column=column, is_evaluated=False\n ).visit(typ.body)\n return ignored, converted\n\n\ndef parse_type_string(\n expr_string: str, expr_fallback_name: str, line: int, column: int\n) -> ProperType:\n \"\"\"Parses a type that was originally present inside of an explicit string.\n\n For example, suppose we have the type `Foo[\"blah\"]`. We should parse the\n string expression \"blah\" using this function.\n \"\"\"\n try:\n _, node = parse_type_comment(f\"({expr_string})\", line=line, column=column, errors=None)\n if isinstance(node, (UnboundType, UnionType)) and node.original_str_expr is None:\n node.original_str_expr = expr_string\n node.original_str_fallback = expr_fallback_name\n return node\n else:\n return RawExpressionType(expr_string, expr_fallback_name, line, column)\n except (SyntaxError, ValueError):\n # Note: the parser will raise a `ValueError` instead of a SyntaxError if\n # the string happens to contain things like \\x00.\n return RawExpressionType(expr_string, expr_fallback_name, line, column)\n\n\ndef is_no_type_check_decorator(expr: ast3.expr) -> bool:\n if isinstance(expr, Name):\n return expr.id == \"no_type_check\"\n elif isinstance(expr, Attribute):\n if isinstance(expr.value, Name):\n return expr.value.id == \"typing\" and expr.attr == \"no_type_check\"\n return False\n\n\ndef find_disallowed_expression_in_annotation_scope(expr: ast3.expr | None) -> ast3.expr | None:\n if expr is None:\n return None\n for node in ast3.walk(expr):\n if isinstance(node, (ast3.Yield, ast3.YieldFrom, ast3.NamedExpr, ast3.Await)):\n return node\n return None\n\n\nclass ASTConverter:\n def __init__(\n self,\n options: Options,\n is_stub: bool,\n errors: Errors,\n *,\n strip_function_bodies: bool,\n path: str,\n ) -> None:\n # 'C' for class, 'D' for function signature, 'F' for function, 'L' for lambda\n self.class_and_function_stack: list[Literal[\"C\", \"D\", \"F\", \"L\"]] = []\n self.imports: list[ImportBase] = []\n\n self.options = options\n self.is_stub = is_stub\n self.errors = errors\n self.strip_function_bodies = strip_function_bodies\n self.path = path\n\n self.type_ignores: dict[int, list[str]] = {}\n\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\")\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 (\n a.type_annotation\n if a.type_annotation is not None\n else AnyType(TypeOfAny.unannotated)\n )\n for a in args\n ]\n else:\n # PEP 484 disallows both type annotations and type comments\n if n.returns or any(a.type_annotation is not None for a in args):\n self.fail(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 AnyType(TypeOfAny.unannotated) for a in arg_types],\n arg_kinds,\n arg_names,\n return_type if return_type is not None else AnyType(TypeOfAny.unannotated),\n _dummy_fallback,\n )\n\n # End position is always the same.\n end_line = 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.line = lineno\n\n if n.decorator_list:\n # Set deco_line to the old pre-3.8 lineno, in order to keep\n # existing \"# type: ignore\" comments working:\n deco_line = n.decorator_list[0].lineno\n\n var = Var(func_def.name)\n var.is_ready = False\n var.set_line(lineno)\n\n func_def.is_decorated = True\n func_def.deco_line = deco_line\n func_def.set_line(lineno, n.col_offset, end_line, end_column)\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 # FuncDef overrides set_line -- can't use self.set_line\n func_def.set_line(lineno, n.col_offset, end_line, end_column)\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 # Set lines to match the old mypy 0.700 lines, in order to keep\n # existing \"# type: ignore\" comments working:\n cdef.line = n.lineno\n cdef.deco_line = n.decorator_list[0].lineno if n.decorator_list else None\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 = None\n values: list[Type] = []\n if sys.version_info >= (3, 13) and p.default_value is not None:\n self.fail(\n message_registry.TYPE_PARAM_DEFAULT_NOT_SUPPORTED,\n p.lineno,\n p.col_offset,\n blocker=False,\n )\n if isinstance(p, ast_ParamSpec): # type: ignore[misc]\n explicit_type_params.append(TypeParam(p.name, PARAM_SPEC_KIND, None, []))\n elif isinstance(p, ast_TypeVarTuple): # type: ignore[misc]\n explicit_type_params.append(TypeParam(p.name, TYPE_VAR_TUPLE_KIND, None, []))\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(TypeParam(p.name, TYPE_VAR_KIND, bound, values))\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 rvalue.line = line\n rvalue.column = n.col_offset\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)))\n return self.set_line(e, n)\n\n # SetComp(expr elt, comprehension* generators)\n def visit_SetComp(self, n: ast3.SetComp) -> SetComprehension:\n e = SetComprehension(self.visit_GeneratorExp(cast(ast3.GeneratorExp, n)))\n return self.set_line(e, n)\n\n # DictComp(expr key, expr value, comprehension* generators)\n def visit_DictComp(self, n: ast3.DictComp) -> DictionaryComprehension:\n targets = [self.visit(c.target) for c in n.generators]\n iters = [self.visit(c.iter) for c in n.generators]\n ifs_list = [self.translate_expr_list(c.ifs) for c in n.generators]\n is_async = [bool(c.is_async) for c in n.generators]\n e = DictionaryComprehension(\n self.visit(n.key), self.visit(n.value), targets, iters, ifs_list, is_async\n )\n return self.set_line(e, n)\n\n # GeneratorExp(expr elt, comprehension* generators)\n def visit_GeneratorExp(self, n: ast3.GeneratorExp) -> GeneratorExpr:\n targets = [self.visit(c.target) for c in n.generators]\n iters = [self.visit(c.iter) for c in n.generators]\n ifs_list = [self.translate_expr_list(c.ifs) for c in n.generators]\n is_async = [bool(c.is_async) for c in n.generators]\n e = GeneratorExpr(self.visit(n.elt), targets, iters, ifs_list, is_async)\n return self.set_line(e, n)\n\n # Await(expr value)\n def visit_Await(self, n: ast3.Await) -> AwaitExpr:\n v = self.visit(n.value)\n e = AwaitExpr(v)\n return self.set_line(e, n)\n\n # Yield(expr? value)\n def visit_Yield(self, n: ast3.Yield) -> YieldExpr:\n e = YieldExpr(self.visit(n.value))\n return self.set_line(e, n)\n\n # YieldFrom(expr value)\n def visit_YieldFrom(self, n: ast3.YieldFrom) -> YieldFromExpr:\n e = YieldFromExpr(self.visit(n.value))\n return self.set_line(e, n)\n\n # Compare(expr left, cmpop* ops, expr* comparators)\n def visit_Compare(self, n: ast3.Compare) -> ComparisonExpr:\n operators = [self.from_comp_operator(o) for o in n.ops]\n operands = self.translate_expr_list([n.left] + n.comparators)\n e = ComparisonExpr(operators, operands)\n return self.set_line(e, n)\n\n # Call(expr func, expr* args, keyword* keywords)\n # keyword = (identifier? arg, expr value)\n def visit_Call(self, n: Call) -> CallExpr:\n args = n.args\n keywords = n.keywords\n keyword_names = [k.arg for k in keywords]\n arg_types = self.translate_expr_list(\n [a.value if isinstance(a, Starred) else a for a in args] + [k.value for k in keywords]\n )\n arg_kinds = [ARG_STAR if type(a) is Starred else ARG_POS for a in args] + [\n ARG_STAR2 if arg is None else ARG_NAMED for arg in keyword_names\n ]\n e = CallExpr(\n self.visit(n.func),\n arg_types,\n arg_kinds,\n cast(\"List[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 # 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 self.set_line(e, n)\n # alias to please mypyc\n is_py38_or_earlier = sys.version_info < (3, 9)\n if isinstance(n.slice, ast3.Slice) or (\n is_py38_or_earlier and isinstance(n.slice, ast3.ExtSlice)\n ):\n # Before Python 3.9, Slice has no line\/column in the raw ast. To avoid incompatibility\n # visit_Slice doesn't set_line, even in Python 3.9 on.\n # ExtSlice also has no line\/column info. In Python 3.9 on, line\/column is set for\n # e.index when visiting n.slice.\n e.index.line = e.line\n e.index.column = e.column\n return e\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 return SliceExpr(self.visit(n.lower), self.visit(n.upper), self.visit(n.step))\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):\n return self.invalid_type(n)\n\n left = self.visit(n.left)\n right = self.visit(n.right)\n return UnionType(\n [left, right],\n line=self.line,\n column=self.convert_column(n.col_offset),\n is_evaluated=self.is_evaluated,\n uses_pep604_syntax=True,\n )\n\n def visit_Constant(self, n: 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 # noqa: E721\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, slice slice, expr_context ctx) # Python 3.8 and before\n # Subscript(expr value, expr slice, expr_context ctx) # Python 3.9 and later\n def visit_Subscript(self, n: ast3.Subscript) -> Type:\n if sys.version_info >= (3, 9): # Really 3.9a5 or later\n sliceval: Any = n.slice\n # Python 3.8 or earlier use a different AST structure for subscripts\n elif isinstance(n.slice, ast3.Index):\n sliceval: Any = n.slice.value\n elif isinstance(n.slice, ast3.Slice):\n sliceval = copy.deepcopy(n.slice) # so we don't mutate passed AST\n if getattr(sliceval, \"col_offset\", None) is None:\n # Fix column information so that we get Python 3.9+ message order\n sliceval.col_offset = sliceval.lower.col_offset\n else:\n assert isinstance(n.slice, ast3.ExtSlice)\n dims = cast(List[ast3.expr], copy.deepcopy(n.slice.dims))\n for s in dims:\n # These fields don't actually have a col_offset attribute but we add\n # it manually.\n if getattr(s, \"col_offset\", None) is None:\n if isinstance(s, ast3.Index):\n s.col_offset = s.value.col_offset\n elif isinstance(s, ast3.Slice):\n assert s.lower is not None\n s.col_offset = s.lower.col_offset\n sliceval = ast3.Tuple(dims, n.ctx)\n\n empty_tuple_index = False\n if isinstance(sliceval, ast3.Tuple):\n params = self.translate_expr_list(sliceval.elts)\n if len(sliceval.elts) == 0:\n empty_tuple_index = True\n else:\n params = [self.visit(sliceval)]\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/fastparse.py","language":"Python","license":"NOASSERTION","size":87516} {"code":"\"\"\"Routines for finding the sources that mypy will check\"\"\"\n\nfrom __future__ import annotations\n\nimport functools\nimport os\nfrom typing import Final, Sequence\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/find_sources.py","language":"Python","license":"NOASSERTION","size":9362} {"code":"\"\"\"Fix up various things after deserialization.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Any, Final\n\nfrom mypy.lookup import lookup_fully_qualified\nfrom mypy.nodes import (\n Block,\n ClassDef,\n Decorator,\n FuncDef,\n MypyFile,\n OverloadedFuncDef,\n ParamSpecExpr,\n SymbolTable,\n TypeAlias,\n TypeInfo,\n TypeVarExpr,\n TypeVarTupleExpr,\n Var,\n)\nfrom mypy.types import (\n NOT_READY,\n AnyType,\n CallableType,\n Instance,\n LiteralType,\n Overloaded,\n Parameters,\n ParamSpecType,\n 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, value in list(symtab.items()):\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.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_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 = \"\"\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, \"\")\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/fixup.py","language":"Python","license":"NOASSERTION","size":15988} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/freetree.py","language":"Python","license":"NOASSERTION","size":617} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/fscache.py","language":"Python","license":"NOASSERTION","size":10975} {"code":"\"\"\"Watch parts of the file system for changes.\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nfrom typing import AbstractSet, Iterable, 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/fswatcher.py","language":"Python","license":"NOASSERTION","size":3951} {"code":"from __future__ import annotations\n\nimport gc\nimport time\nfrom typing 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 result[\"gc_time\"] = self.gc_time\n result[\"gc_calls\"] = self.gc_calls\n result[\"gc_collected\"] = self.gc_collected\n result[\"gc_uncollectable\"] = self.gc_uncollectable\n result[\"build_time\"] = end_time - self.start_time\n return result\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/gclogger.py","language":"Python","license":"NOASSERTION","size":1641} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/git.py","language":"Python","license":"NOASSERTION","size":980} {"code":"\"\"\"Helpers for manipulations with graphs.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import AbstractSet, Iterable, Iterator, 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 = {v: frozenset(scc) for scc in sccs for v in scc}\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/graph_utils.py","language":"Python","license":"NOASSERTION","size":3343} {"code":"from __future__ import annotations\n\nfrom typing import Iterable, Set\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[Set[str]]):\n \"\"\"Returns all module references within a particular type.\"\"\"\n\n def __init__(self) -> None:\n self.cache: dict[types.Type, set[str]] = {}\n self.seen_aliases: set[types.TypeAliasType] = set()\n\n def find_modules(self, typs: Iterable[types.Type]) -> set[str]:\n self.seen_aliases.clear()\n return self._visit(typs)\n\n def _visit(self, typ_or_typs: types.Type | Iterable[types.Type]) -> set[str]:\n typs = [typ_or_typs] if isinstance(typ_or_typs, types.Type) else typ_or_typs\n output: set[str] = set()\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 if typ in self.cache:\n modules = self.cache[typ]\n else:\n modules = typ.accept(self)\n self.cache[typ] = set(modules)\n output.update(modules)\n return output\n\n def visit_unbound_type(self, t: types.UnboundType) -> set[str]:\n return self._visit(t.args)\n\n def visit_any(self, t: types.AnyType) -> set[str]:\n return set()\n\n def visit_none_type(self, t: types.NoneType) -> set[str]:\n return set()\n\n def visit_uninhabited_type(self, t: types.UninhabitedType) -> set[str]:\n return set()\n\n def visit_erased_type(self, t: types.ErasedType) -> set[str]:\n return set()\n\n def visit_deleted_type(self, t: types.DeletedType) -> set[str]:\n return set()\n\n def visit_type_var(self, t: types.TypeVarType) -> set[str]:\n return self._visit(t.values) | self._visit(t.upper_bound) | self._visit(t.default)\n\n def visit_param_spec(self, t: types.ParamSpecType) -> set[str]:\n return self._visit(t.upper_bound) | self._visit(t.default)\n\n def visit_type_var_tuple(self, t: types.TypeVarTupleType) -> set[str]:\n return self._visit(t.upper_bound) | self._visit(t.default)\n\n def visit_unpack_type(self, t: types.UnpackType) -> set[str]:\n return t.type.accept(self)\n\n def visit_parameters(self, t: types.Parameters) -> set[str]:\n return self._visit(t.arg_types)\n\n def visit_instance(self, t: types.Instance) -> set[str]:\n out = 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 out.update(split_module_names(s.module_name))\n if t.type.metaclass_type is not None:\n out.update(split_module_names(t.type.metaclass_type.type.module_name))\n return out\n\n def visit_callable_type(self, t: types.CallableType) -> set[str]:\n out = self._visit(t.arg_types) | self._visit(t.ret_type)\n if t.definition is not None:\n out.update(extract_module_names(t.definition.fullname))\n return out\n\n def visit_overloaded(self, t: types.Overloaded) -> set[str]:\n return self._visit(t.items) | self._visit(t.fallback)\n\n def visit_tuple_type(self, t: types.TupleType) -> set[str]:\n return self._visit(t.items) | self._visit(t.partial_fallback)\n\n def visit_typeddict_type(self, t: types.TypedDictType) -> set[str]:\n return self._visit(t.items.values()) | self._visit(t.fallback)\n\n def visit_literal_type(self, t: types.LiteralType) -> set[str]:\n return self._visit(t.fallback)\n\n def visit_union_type(self, t: types.UnionType) -> set[str]:\n return self._visit(t.items)\n\n def visit_partial_type(self, t: types.PartialType) -> set[str]:\n return set()\n\n def visit_type_type(self, t: types.TypeType) -> set[str]:\n return self._visit(t.item)\n\n def visit_type_alias_type(self, t: types.TypeAliasType) -> set[str]:\n return self._visit(types.get_proper_type(t))\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/indirection.py","language":"Python","license":"NOASSERTION","size":4595} {"code":"\"\"\"Utilities for type argument inference.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import NamedTuple, Sequence\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/infer.py","language":"Python","license":"NOASSERTION","size":2511} {"code":"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 ths 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__}\"'\n f\" 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/inspections.py","language":"Python","license":"NOASSERTION","size":23820} {"code":"\"\"\"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 ctypes\n\n import _winapi\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/ipc.py","language":"Python","license":"NOASSERTION","size":11702} {"code":"\"\"\"Calculation of the least upper bound types (joins).\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Sequence, overload\n\nimport mypy.typeops\nfrom mypy.expandtype import expand_type\nfrom mypy.maptype import map_instance_to_supertype\nfrom mypy.nodes import CONTRAVARIANT, COVARIANT, INVARIANT, VARIANCE_NOT_READY\nfrom mypy.state import state\nfrom mypy.subtypes import (\n SubtypeContext,\n find_member,\n is_equivalent,\n is_proper_subtype,\n is_protocol_implementation,\n is_subtype,\n)\nfrom mypy.types import (\n AnyType,\n CallableType,\n DeletedType,\n ErasedType,\n FunctionLike,\n Instance,\n LiteralType,\n NoneType,\n Overloaded,\n Parameters,\n ParamSpecType,\n PartialType,\n ProperType,\n TupleType,\n Type,\n TypeAliasType,\n TypedDictType,\n TypeOfAny,\n TypeType,\n TypeVarId,\n TypeVarLikeType,\n TypeVarTupleType,\n TypeVarType,\n TypeVisitor,\n UnboundType,\n UninhabitedType,\n UnionType,\n UnpackType,\n find_unpack_in_list,\n get_proper_type,\n get_proper_types,\n split_with_prefix_and_suffix,\n)\n\n\nclass InstanceJoiner:\n def __init__(self) -> None:\n self.seen_instances: list[tuple[Instance, Instance]] = []\n\n def join_instances(self, t: Instance, s: Instance) -> ProperType:\n if (t, s) in self.seen_instances or (s, t) in self.seen_instances:\n return object_from_instance(t)\n\n self.seen_instances.append((t, s))\n\n # Calculate the join of two instance types\n if t.type == s.type:\n # Simplest case: join two types with the same base type (but\n # potentially different arguments).\n\n # Combine type arguments.\n args: list[Type] = []\n # N.B: We use zip instead of indexing because the lengths might have\n # mismatches during daemon reprocessing.\n if t.type.has_type_var_tuple_type:\n # We handle joins of variadic instances by simply creating correct mapping\n # for type arguments and compute the individual joins same as for regular\n # instances. All the heavy lifting is done in the join of tuple types.\n assert s.type.type_var_tuple_prefix is not None\n assert s.type.type_var_tuple_suffix is not None\n prefix = s.type.type_var_tuple_prefix\n suffix = s.type.type_var_tuple_suffix\n tvt = s.type.defn.type_vars[prefix]\n assert isinstance(tvt, TypeVarTupleType)\n fallback = tvt.tuple_fallback\n s_prefix, s_middle, s_suffix = split_with_prefix_and_suffix(s.args, prefix, suffix)\n t_prefix, t_middle, t_suffix = split_with_prefix_and_suffix(t.args, prefix, suffix)\n s_args = s_prefix + (TupleType(list(s_middle), fallback),) + s_suffix\n t_args = t_prefix + (TupleType(list(t_middle), fallback),) + t_suffix\n else:\n t_args = t.args\n s_args = s.args\n for ta, sa, type_var in zip(t_args, s_args, t.type.defn.type_vars):\n ta_proper = get_proper_type(ta)\n sa_proper = get_proper_type(sa)\n new_type: Type | None = None\n if isinstance(ta_proper, AnyType):\n new_type = AnyType(TypeOfAny.from_another_any, ta_proper)\n elif isinstance(sa_proper, AnyType):\n new_type = AnyType(TypeOfAny.from_another_any, sa_proper)\n elif isinstance(type_var, TypeVarType):\n if type_var.variance in (COVARIANT, VARIANCE_NOT_READY):\n new_type = join_types(ta, sa, self)\n if len(type_var.values) != 0 and new_type not in type_var.values:\n self.seen_instances.pop()\n return object_from_instance(t)\n if not is_subtype(new_type, type_var.upper_bound):\n self.seen_instances.pop()\n return object_from_instance(t)\n # TODO: contravariant case should use meet but pass seen instances as\n # an argument to keep track of recursive checks.\n elif type_var.variance in (INVARIANT, CONTRAVARIANT):\n if isinstance(ta_proper, UninhabitedType) and ta_proper.ambiguous:\n new_type = sa\n elif isinstance(sa_proper, UninhabitedType) and sa_proper.ambiguous:\n new_type = ta\n elif not is_equivalent(ta, sa):\n self.seen_instances.pop()\n return object_from_instance(t)\n else:\n # If the types are different but equivalent, then an Any is involved\n # so using a join in the contravariant case is also OK.\n new_type = join_types(ta, sa, self)\n elif isinstance(type_var, TypeVarTupleType):\n new_type = get_proper_type(join_types(ta, sa, self))\n # Put the joined arguments back into instance in the normal form:\n # a) Tuple[X, Y, Z] -> [X, Y, Z]\n # b) tuple[X, ...] -> [*tuple[X, ...]]\n if isinstance(new_type, Instance):\n assert new_type.type.fullname == \"builtins.tuple\"\n new_type = UnpackType(new_type)\n else:\n assert isinstance(new_type, TupleType)\n args.extend(new_type.items)\n continue\n else:\n # ParamSpec type variables behave the same, independent of variance\n if not is_equivalent(ta, sa):\n return get_proper_type(type_var.upper_bound)\n new_type = join_types(ta, sa, self)\n assert new_type is not None\n args.append(new_type)\n result: ProperType = Instance(t.type, args)\n elif t.type.bases and is_proper_subtype(\n t, s, subtype_context=SubtypeContext(ignore_type_params=True)\n ):\n result = self.join_instances_via_supertype(t, s)\n else:\n # Now t is not a subtype of s, and t != s. Now s could be a subtype\n # of t; alternatively, we need to find a common supertype. This works\n # in of the both cases.\n result = self.join_instances_via_supertype(s, t)\n\n self.seen_instances.pop()\n return result\n\n def join_instances_via_supertype(self, t: Instance, s: Instance) -> ProperType:\n # Give preference to joins via duck typing relationship, so that\n # join(int, float) == float, for example.\n for p in t.type._promote:\n if is_subtype(p, s):\n return join_types(p, s, self)\n for p in s.type._promote:\n if is_subtype(p, t):\n return join_types(t, p, self)\n\n # Compute the \"best\" supertype of t when joined with s.\n # The definition of \"best\" may evolve; for now it is the one with\n # the longest MRO. Ties are broken by using the earlier base.\n 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\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\n@overload\ndef join_types(\n s: ProperType, t: ProperType, instance_joiner: InstanceJoiner | None = None\n) -> ProperType: ...\n\n\n@overload\ndef join_types(s: Type, t: Type, instance_joiner: InstanceJoiner | None = None) -> Type: ...\n\n\ndef join_types(s: Type, t: Type, instance_joiner: InstanceJoiner | None = None) -> Type:\n \"\"\"Return the least upper bound of s and t.\n\n For example, the join of 'int' and 'object' is 'object'.\n \"\"\"\n if mypy.typeops.is_recursive_pair(s, t):\n # This case can trigger an infinite recursion, general support for this will be\n # tricky so we use a trivial join (like for protocols).\n return trivial_join(s, t)\n s = get_proper_type(s)\n t = get_proper_type(t)\n\n if (s.can_be_true, s.can_be_false) != (t.can_be_true, t.can_be_false):\n # if types are restricted in different ways, use the more general versions\n s = mypy.typeops.true_or_false(s)\n t = mypy.typeops.true_or_false(t)\n\n if isinstance(s, UnionType) and not isinstance(t, UnionType):\n s, t = t, s\n\n if isinstance(s, AnyType):\n return s\n\n if isinstance(s, ErasedType):\n return t\n\n if isinstance(s, NoneType) and not isinstance(t, NoneType):\n s, t = t, s\n\n if isinstance(s, UninhabitedType) and not isinstance(t, UninhabitedType):\n s, t = t, s\n\n # Meets\/joins require callable type normalization.\n s, t = normalize_callables(s, t)\n\n # Use a visitor to handle non-trivial cases.\n return t.accept(TypeJoinVisitor(s, instance_joiner))\n\n\nclass TypeJoinVisitor(TypeVisitor[ProperType]):\n \"\"\"Implementation of the least upper bound algorithm.\n\n Attributes:\n s: The other (left) type operand.\n \"\"\"\n\n def __init__(self, s: ProperType, instance_joiner: InstanceJoiner | None = None) -> None:\n self.s = s\n self.instance_joiner = instance_joiner\n\n def visit_unbound_type(self, t: UnboundType) -> ProperType:\n return AnyType(TypeOfAny.special_form)\n\n def visit_union_type(self, t: UnionType) -> ProperType:\n if is_proper_subtype(self.s, t):\n return t\n else:\n return mypy.typeops.make_simplified_union([self.s, t])\n\n def visit_any(self, t: AnyType) -> ProperType:\n return t\n\n def visit_none_type(self, t: NoneType) -> ProperType:\n if state.strict_optional:\n if isinstance(self.s, (NoneType, UninhabitedType)):\n return t\n elif isinstance(self.s, UnboundType):\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 if t.fallback.type.fullname == \"builtins.function\":\n fallback = t.fallback\n else:\n fallback = s.fallback\n return t.copy_modified(\n arg_types=arg_types,\n arg_names=combine_arg_names(t, s),\n ret_type=join_types(t.ret_type, s.ret_type),\n fallback=fallback,\n name=None,\n )\n\n\ndef safe_join(t: Type, s: Type) -> Type:\n # This is a temporary solution to prevent crashes in combine_similar_callables() etc.,\n # until relevant TODOs on handling arg_kinds will be addressed there.\n if not isinstance(t, UnpackType) and not isinstance(s, UnpackType):\n return join_types(t, s)\n if isinstance(t, UnpackType) and isinstance(s, UnpackType):\n return UnpackType(join_types(t.type, s.type))\n return object_or_any_from_type(get_proper_type(t))\n\n\ndef safe_meet(t: Type, s: Type) -> Type:\n # Similar to above but for meet_types().\n from mypy.meet import meet_types\n\n if not isinstance(t, UnpackType) and not isinstance(s, UnpackType):\n return meet_types(t, s)\n if isinstance(t, UnpackType) and isinstance(s, UnpackType):\n unpacked = get_proper_type(t.type)\n if isinstance(unpacked, TypeVarTupleType):\n fallback_type = unpacked.tuple_fallback.type\n elif isinstance(unpacked, TupleType):\n fallback_type = unpacked.partial_fallback.type\n else:\n assert isinstance(unpacked, Instance) and unpacked.type.fullname == \"builtins.tuple\"\n fallback_type = unpacked.type\n res = meet_types(t.type, s.type)\n if isinstance(res, UninhabitedType):\n res = Instance(fallback_type, [res])\n return UnpackType(res)\n return UninhabitedType()\n\n\ndef combine_similar_callables(t: CallableType, s: CallableType) -> CallableType:\n t, s = match_generic_callables(t, s)\n arg_types: list[Type] = []\n for i in range(len(t.arg_types)):\n arg_types.append(safe_join(t.arg_types[i], s.arg_types[i]))\n # TODO kinds and argument names\n # TODO what should happen if one fallback is 'type' and the other is a user-provided metaclass?\n # The fallback type can be either 'function', 'type', or some user-provided metaclass.\n # The result should always use 'function' as a fallback if either operands are using it.\n if t.fallback.type.fullname == \"builtins.function\":\n fallback = t.fallback\n else:\n fallback = s.fallback\n return t.copy_modified(\n arg_types=arg_types,\n arg_names=combine_arg_names(t, s),\n ret_type=join_types(t.ret_type, s.ret_type),\n fallback=fallback,\n name=None,\n )\n\n\ndef combine_arg_names(\n t: CallableType | Parameters, s: CallableType | Parameters\n) -> list[str | None]:\n \"\"\"Produces a list of argument names compatible with both callables.\n\n For example, suppose 't' and 's' have the following signatures:\n\n - t: (a: int, b: str, X: str) -> None\n - s: (a: int, b: str, Y: str) -> None\n\n This function would return [\"a\", \"b\", None]. This information\n is then used above to compute the join of t and s, which results\n in a signature of (a: int, b: str, str) -> None.\n\n Note that the third argument's name is omitted and 't' and 's'\n are both valid subtypes of this inferred signature.\n\n Precondition: is_similar_types(t, s) is true.\n \"\"\"\n num_args = len(t.arg_types)\n new_names = []\n for i in range(num_args):\n t_name = t.arg_names[i]\n s_name = s.arg_names[i]\n if t_name == s_name or t.arg_kinds[i].is_named() or s.arg_kinds[i].is_named():\n new_names.append(t_name)\n else:\n new_names.append(None)\n return new_names\n\n\ndef object_from_instance(instance: Instance) -> Instance:\n \"\"\"Construct the type 'builtins.object' from an instance type.\"\"\"\n # Use the fact that 'object' is always the last class in the mro.\n res = Instance(instance.type.mro[-1], [])\n return res\n\n\ndef object_or_any_from_type(typ: ProperType) -> ProperType:\n # Similar to object_from_instance() but tries hard for all types.\n # TODO: find a better way to get object, or make this more reliable.\n if isinstance(typ, Instance):\n return object_from_instance(typ)\n elif isinstance(typ, (CallableType, TypedDictType, LiteralType)):\n return object_from_instance(typ.fallback)\n elif isinstance(typ, TupleType):\n return object_from_instance(typ.partial_fallback)\n elif isinstance(typ, TypeType):\n return object_or_any_from_type(typ.item)\n elif isinstance(typ, TypeVarLikeType) and isinstance(typ.upper_bound, ProperType):\n return object_or_any_from_type(typ.upper_bound)\n elif isinstance(typ, UnionType):\n for item in typ.items:\n if isinstance(item, ProperType):\n candidate = object_or_any_from_type(item)\n if isinstance(candidate, Instance):\n return candidate\n elif isinstance(typ, UnpackType):\n object_or_any_from_type(get_proper_type(typ.type))\n return AnyType(TypeOfAny.implementation_artifact)\n\n\ndef join_type_list(types: Sequence[Type]) -> Type:\n if not types:\n # This is a little arbitrary but reasonable. Any empty tuple should be compatible\n # with all variable length tuples, and this makes it possible.\n return UninhabitedType()\n joined = types[0]\n for t in types[1:]:\n joined = join_types(joined, t)\n return joined\n\n\ndef unpack_callback_protocol(t: Instance) -> ProperType | None:\n assert t.type.is_protocol\n if t.type.protocol_members == [\"__call__\"]:\n return get_proper_type(find_member(\"__call__\", t, t, is_operator=True))\n return None\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/join.py","language":"Python","license":"NOASSERTION","size":38174} {"code":"from __future__ import annotations\n\nfrom typing import Any, Final, Iterable, Optional, Tuple\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/literals.py","language":"Python","license":"NOASSERTION","size":8749} {"code":"\"\"\"\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/lookup.py","language":"Python","license":"NOASSERTION","size":2054} {"code":"\"\"\"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 gettext import gettext\nfrom typing import IO, Any, Final, NoReturn, Sequence, TextIO\n\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 BuildSource, FindModuleCache, SearchPaths, get_search_dirs, mypy_path\nfrom mypy.options import INCOMPLETE_FEATURES, BuildType, Options\nfrom mypy.split_namespace import SplitNamespace\nfrom mypy.version import __version__\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(2**14)\n if args is None:\n args = sys.argv[1:]\n\n fscache = FileSystemCache()\n sources, options = process_options(args, stdout=stdout, stderr=stderr, fscache=fscache)\n if clean_exit:\n options.fast_exit = False\n\n formatter = util.FancyFormatter(\n stdout, stderr, options.hide_error_codes, hide_success=bool(options.output)\n )\n\n if options.install_types and (stdout is not sys.stdout or stderr is not sys.stderr):\n # Since --install-types performs user input, we want regular stdout and stderr.\n fail(\"error: --install-types not supported in this mode of running mypy\", stderr, options)\n\n if options.non_interactive and not options.install_types:\n fail(\"error: --non-interactive is only supported with --install-types\", stderr, options)\n\n if options.install_types and not options.incremental:\n fail(\n \"error: --install-types not supported with incremental mode disabled\", stderr, options\n )\n\n if options.install_types and options.python_executable is None:\n fail(\n \"error: --install-types not supported without python executable or site packages\",\n stderr,\n options,\n )\n\n if options.install_types and not sources:\n install_types(formatter, options, non_interactive=options.non_interactive)\n return\n\n res, messages, blockers = run_build(sources, options, fscache, t0, stdout, stderr)\n\n if options.non_interactive:\n missing_pkgs = read_types_packages_to_install(options.cache_dir, after_run=True)\n if missing_pkgs:\n # Install missing type packages and rerun build.\n install_types(formatter, options, after_run=True, non_interactive=True)\n fscache.flush()\n print()\n res, messages, blockers = run_build(sources, options, fscache, t0, stdout, stderr)\n show_messages(messages, stderr, formatter, options)\n\n if MEM_PROFILE:\n from mypy.memprofile import print_memory_profile\n\n print_memory_profile()\n\n code = 0\n n_errors, n_notes, n_files = util.count_stats(messages)\n if messages and n_notes < len(messages):\n code = 2 if blockers else 1\n if options.error_summary:\n if n_errors:\n summary = formatter.format_error(\n n_errors, n_files, len(sources), blockers=blockers, use_color=options.color_output\n )\n stdout.write(summary + \"\\n\")\n # Only notes should also output success\n elif not messages or n_notes == len(messages):\n stdout.write(formatter.format_success(len(sources), options.color_output) + \"\\n\")\n stdout.flush()\n\n if options.install_types and not options.non_interactive:\n result = install_types(formatter, options, after_run=True, non_interactive=False)\n if result:\n print()\n print(\"note: Run mypy again for up-to-date results with installed types\")\n code = 2\n\n if options.fast_exit:\n # Exit without freeing objects -- it's faster.\n #\n # NOTE: We don't flush all open files on exit (or run other destructors)!\n util.hard_exit(code)\n elif code:\n sys.exit(code)\n\n # HACK: keep res alive so that mypyc won't free it before the hard_exit\n list([res]) # noqa: C410\n\n\ndef run_build(\n sources: list[BuildSource],\n options: Options,\n fscache: FileSystemCache,\n t0: float,\n stdout: TextIO,\n stderr: TextIO,\n) -> tuple[build.BuildResult | None, list[str], bool]:\n formatter = util.FancyFormatter(\n stdout, stderr, options.hide_error_codes, hide_success=bool(options.output)\n )\n\n messages = []\n messages_by_file = defaultdict(list)\n\n def flush_errors(filename: str | None, new_messages: list[str], serious: bool) -> None:\n if options.pretty:\n new_messages = formatter.fit_in_terminal(new_messages)\n messages.extend(new_messages)\n if new_messages:\n messages_by_file[filename].extend(new_messages)\n if options.non_interactive:\n # Collect messages and possibly show them later.\n return\n f = stderr if serious else stdout\n show_messages(new_messages, f, formatter, options)\n\n serious = False\n blockers = False\n res = None\n try:\n # Keep a dummy reference (res) for memory profiling afterwards, as otherwise\n # the result could be freed.\n res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)\n except CompileError as e:\n blockers = True\n if not e.use_stdout:\n serious = True\n 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 = \"\"\"\nMypy is a program that will type check your Python code.\n\nPass in any files or folders you want to type check. Mypy will\nrecursively traverse any provided folders to find .py files:\n\n $ mypy my_program.py my_src_folder\n\nFor more information on getting started, see:\n\n- https:\/\/mypy.readthedocs.io\/en\/stable\/getting_started.html\n\nFor more details on both running mypy and using the flags below, see:\n\n- https:\/\/mypy.readthedocs.io\/en\/stable\/running_mypy.html\n- https:\/\/mypy.readthedocs.io\/en\/stable\/command_line.html\n\nYou can also use a config file to configure mypy instead of using\ncommand line flags. For more details, see:\n\n- https:\/\/mypy.readthedocs.io\/en\/stable\/config_file.html\n\"\"\"\n\nFOOTER: Final = \"\"\"Environment variables:\n Define MYPYPATH for additional module search path entries.\n Define MYPY_CACHE_DIR to override configuration cache_dir path.\"\"\"\n\n\nclass CapturableArgumentParser(argparse.ArgumentParser):\n \"\"\"Override ArgumentParser methods that use sys.stdout\/sys.stderr directly.\n\n This is needed because hijacking sys.std* is not thread-safe,\n yet output must be captured to properly support mypy.api.run.\n \"\"\"\n\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n self.stdout = kwargs.pop(\"stdout\", sys.stdout)\n self.stderr = kwargs.pop(\"stderr\", sys.stderr)\n super().__init__(*args, **kwargs)\n\n # =====================\n # Help-printing methods\n # =====================\n def print_usage(self, file: IO[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: IO[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: IO[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 strict_flag_names: list[str] = []\n strict_flag_assignments: list[tuple[str, bool]] = []\n\n def add_invertible_flag(\n flag: str,\n *,\n inverse: str | None = None,\n default: bool,\n dest: str | None = None,\n help: str,\n strict_flag: bool = False,\n group: argparse._ActionsContainer | None = None,\n ) -> None:\n if inverse is None:\n inverse = invert_flag_name(flag)\n if group is None:\n group = parser\n\n if help is not argparse.SUPPRESS:\n help += f\" (inverse: {inverse})\"\n\n arg = group.add_argument(\n flag, action=\"store_false\" if default else \"store_true\", dest=dest, help=help\n )\n dest = arg.dest\n group.add_argument(\n inverse,\n action=\"store_true\" if default else \"store_false\",\n dest=dest,\n help=argparse.SUPPRESS,\n )\n if strict_flag:\n assert dest is not None\n strict_flag_names.append(flag)\n strict_flag_assignments.append((dest, not default))\n\n # Unless otherwise specified, arguments will be parsed directly onto an\n # Options object. Options that require further processing should have\n # their `dest` prefixed with `special-opts:`, which will cause them to be\n # parsed into the separate special_opts namespace object.\n\n # 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=\"%(prog)s \" + __version__ + f\" (compiled: {compilation_status})\",\n help=\"Show program's version number and exit\",\n stdout=stdout,\n )\n\n general_group.add_argument(\n \"-O\",\n \"--output\",\n metavar=\"FORMAT\",\n help=\"Set a custom output format\",\n choices=OUTPUT_CHOICES,\n )\n\n config_group = parser.add_argument_group(\n title=\"Config file\",\n description=\"Use a config file instead of command line arguments. \"\n \"This is useful if you are using many flags or want \"\n \"to set different options per each module.\",\n )\n config_group.add_argument(\n \"--config-file\",\n help=\"Configuration file, must have a [mypy] section \"\n \"(defaults to {})\".format(\", \".join(defaults.CONFIG_FILES)),\n )\n add_invertible_flag(\n \"--warn-unused-configs\",\n default=False,\n strict_flag=True,\n help=\"Warn about unused '[mypy-]' or '[[tool.mypy.overrides]]' \"\n \"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-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\"\n \" 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 \"\n \"(defaults to sys.platform)\",\n )\n platform_group.add_argument(\n \"--always-true\",\n metavar=\"NAME\",\n action=\"append\",\n default=[],\n help=\"Additional variable to be considered True (may be repeated)\",\n )\n platform_group.add_argument(\n \"--always-false\",\n metavar=\"NAME\",\n action=\"append\",\n default=[],\n help=\"Additional variable to be considered False (may be repeated)\",\n )\n\n disallow_any_group = parser.add_argument_group(\n title=\"Disallow dynamic typing\",\n description=\"Disallow the use of the dynamic 'Any' type under certain conditions.\",\n )\n disallow_any_group.add_argument(\n \"--disallow-any-unimported\",\n default=False,\n action=\"store_true\",\n help=\"Disallow Any types resulting from unfollowed imports\",\n )\n disallow_any_group.add_argument(\n \"--disallow-any-expr\",\n default=False,\n action=\"store_true\",\n help=\"Disallow all expressions that have type Any\",\n )\n disallow_any_group.add_argument(\n \"--disallow-any-decorated\",\n default=False,\n action=\"store_true\",\n help=\"Disallow functions that have Any in their signature \"\n \"after decorator transformation\",\n )\n disallow_any_group.add_argument(\n \"--disallow-any-explicit\",\n default=False,\n action=\"store_true\",\n help=\"Disallow explicit Any in type positions\",\n )\n add_invertible_flag(\n \"--disallow-any-generics\",\n default=False,\n strict_flag=True,\n help=\"Disallow usage of generic types that do not specify explicit type parameters\",\n group=disallow_any_group,\n )\n add_invertible_flag(\n \"--disallow-subclassing-any\",\n default=False,\n strict_flag=True,\n help=\"Disallow subclassing values of type 'Any' when defining classes\",\n group=disallow_any_group,\n )\n\n untyped_group = parser.add_argument_group(\n title=\"Untyped definitions and calls\",\n description=\"Configure how untyped definitions and calls are handled. \"\n \"Note: by default, mypy ignores any untyped function definitions \"\n \"and assumes any calls to such functions have a return \"\n \"type of 'Any'.\",\n )\n add_invertible_flag(\n \"--disallow-untyped-calls\",\n default=False,\n strict_flag=True,\n help=\"Disallow calling functions without type annotations\"\n \" from functions with type annotations\",\n group=untyped_group,\n )\n untyped_group.add_argument(\n \"--untyped-calls-exclude\",\n metavar=\"MODULE\",\n action=\"append\",\n default=[],\n help=\"Disable --disallow-untyped-calls for functions\/methods coming\"\n \" from specific package, module, or class\",\n )\n add_invertible_flag(\n \"--disallow-untyped-defs\",\n default=False,\n strict_flag=True,\n help=\"Disallow defining functions without type annotations\"\n \" or with incomplete type annotations\",\n group=untyped_group,\n )\n add_invertible_flag(\n \"--disallow-incomplete-defs\",\n default=False,\n strict_flag=True,\n help=\"Disallow defining functions with incomplete type annotations \"\n \"(while still allowing entirely unannotated definitions)\",\n group=untyped_group,\n )\n add_invertible_flag(\n \"--check-untyped-defs\",\n default=False,\n strict_flag=True,\n help=\"Type check the interior of functions without type annotations\",\n group=untyped_group,\n )\n add_invertible_flag(\n \"--disallow-untyped-decorators\",\n default=False,\n strict_flag=True,\n help=\"Disallow decorating typed functions with untyped decorators\",\n group=untyped_group,\n )\n\n none_group = parser.add_argument_group(\n title=\"None and Optional handling\",\n description=\"Adjust how values of type 'None' are handled. For more context on \"\n \"how mypy handles values of type 'None', see: \"\n \"https:\/\/mypy.readthedocs.io\/en\/stable\/kinds_of_types.html#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 \"--warn-redundant-casts\",\n default=False,\n strict_flag=True,\n help=\"Warn about casting an expression to its inferred type\",\n group=lint_group,\n )\n add_invertible_flag(\n \"--warn-unused-ignores\",\n default=False,\n strict_flag=True,\n help=\"Warn about unneeded '# type: ignore' comments\",\n group=lint_group,\n )\n add_invertible_flag(\n \"--no-warn-no-return\",\n dest=\"warn_no_return\",\n default=True,\n help=\"Do not warn about functions that end without returning\",\n group=lint_group,\n )\n add_invertible_flag(\n \"--warn-return-any\",\n default=False,\n strict_flag=True,\n help=\"Warn about returning values of type Any from non-Any typed functions\",\n group=lint_group,\n )\n add_invertible_flag(\n \"--warn-unreachable\",\n default=False,\n strict_flag=False,\n help=\"Warn about statements or expressions inferred to be unreachable\",\n group=lint_group,\n )\n\n # Note: this group is intentionally added here even though we don't add\n # --strict to this group near the end.\n #\n # That way, this group will appear after the various strictness groups\n # but before the remaining flags.\n # We add `--strict` near the end so we don't accidentally miss any strictness\n # flags that are added after this group.\n strictness_group = parser.add_argument_group(title=\"Miscellaneous strictness flags\")\n\n add_invertible_flag(\n \"--allow-untyped-globals\",\n default=False,\n strict_flag=False,\n help=\"Suppress toplevel errors caused by missing annotations\",\n group=strictness_group,\n )\n\n add_invertible_flag(\n \"--allow-redefinition\",\n default=False,\n strict_flag=False,\n help=\"Allow unconditional variable redefinition with a new type\",\n group=strictness_group,\n )\n\n add_invertible_flag(\n \"--no-implicit-reexport\",\n default=True,\n strict_flag=True,\n dest=\"implicit_reexport\",\n help=\"Treat imports as private unless aliased\",\n group=strictness_group,\n )\n\n add_invertible_flag(\n \"--strict-equality\",\n default=False,\n strict_flag=True,\n help=\"Prohibit equality, identity, and container checks for non-overlapping types\",\n group=strictness_group,\n )\n\n add_invertible_flag(\n \"--extra-checks\",\n default=False,\n strict_flag=True,\n help=\"Enable additional checks that are technically correct but may be impractical \"\n \"in real code. For example, this prohibits partial overlap in TypedDict updates, \"\n \"and makes arguments prepended via Concatenate positional-only\",\n group=strictness_group,\n )\n\n strict_help = \"Strict mode; enables the following flags: {}\".format(\n \", \".join(strict_flag_names)\n )\n strictness_group.add_argument(\n \"--strict\", action=\"store_true\", dest=\"special-opts:strict\", help=strict_help\n )\n\n strictness_group.add_argument(\n \"--disable-error-code\",\n metavar=\"NAME\",\n action=\"append\",\n default=[],\n help=\"Disable a specific error code\",\n )\n strictness_group.add_argument(\n \"--enable-error-code\",\n metavar=\"NAME\",\n action=\"append\",\n default=[],\n help=\"Enable a specific error code\",\n )\n\n error_group = parser.add_argument_group(\n title=\"Configuring error messages\",\n description=\"Adjust the amount of detail shown in error messages.\",\n )\n add_invertible_flag(\n \"--show-error-context\",\n default=False,\n dest=\"show_error_context\",\n help='Precede errors with \"note:\" messages explaining context',\n group=error_group,\n )\n add_invertible_flag(\n \"--show-column-numbers\",\n default=False,\n help=\"Show column numbers in error messages\",\n group=error_group,\n )\n add_invertible_flag(\n \"--show-error-end\",\n default=False,\n help=\"Show end line\/end column numbers in error messages.\"\n \" This implies --show-column-numbers\",\n group=error_group,\n )\n add_invertible_flag(\n \"--hide-error-codes\",\n default=False,\n help=\"Hide error codes in error messages\",\n group=error_group,\n )\n add_invertible_flag(\n \"--show-error-code-links\",\n default=False,\n help=\"Show links to error code documentation\",\n group=error_group,\n )\n add_invertible_flag(\n \"--pretty\",\n default=False,\n help=\"Use visually nicer output in error messages:\"\n \" Use soft word wrap, show source code snippets,\"\n \" and show error location markers\",\n group=error_group,\n )\n add_invertible_flag(\n \"--no-color-output\",\n dest=\"color_output\",\n default=True,\n help=\"Do not colorize error messages\",\n group=error_group,\n )\n add_invertible_flag(\n \"--no-error-summary\",\n dest=\"error_summary\",\n default=True,\n help=\"Do not show error stats summary\",\n group=error_group,\n )\n add_invertible_flag(\n \"--show-absolute-path\",\n default=False,\n help=\"Show absolute paths to files\",\n group=error_group,\n )\n error_group.add_argument(\n \"--soft-error-limit\",\n default=defaults.MANY_ERRORS_THRESHOLD,\n type=int,\n dest=\"many_errors_threshold\",\n help=argparse.SUPPRESS,\n )\n\n incremental_group = parser.add_argument_group(\n title=\"Incremental mode\",\n description=\"Adjust how mypy incrementally type checks and caches modules. \"\n \"Mypy caches type information about modules into a cache to \"\n \"let you speed up future invocations of mypy. Also see \"\n \"mypy's daemon mode: \"\n \"mypy.readthedocs.io\/en\/stable\/mypy_daemon.html#mypy-daemon\",\n )\n incremental_group.add_argument(\n \"-i\", \"--incremental\", action=\"store_true\", help=argparse.SUPPRESS\n )\n incremental_group.add_argument(\n \"--no-incremental\",\n action=\"store_false\",\n dest=\"incremental\",\n help=\"Disable module cache (inverse: --incremental)\",\n )\n incremental_group.add_argument(\n \"--cache-dir\",\n action=\"store\",\n metavar=\"DIR\",\n help=\"Store module cache info in the given folder in incremental mode \"\n \"(defaults to '{}')\".format(defaults.CACHE_DIR),\n )\n add_invertible_flag(\n \"--sqlite-cache\",\n default=False,\n help=\"Use a sqlite database to store the cache\",\n group=incremental_group,\n )\n incremental_group.add_argument(\n \"--cache-fine-grained\",\n action=\"store_true\",\n help=\"Include fine-grained dependency information in the cache for the mypy daemon\",\n )\n 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\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 strict_flag=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 strict_flag=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 parser.add_argument(\"--local-partial-types\", action=\"store_true\", help=argparse.SUPPRESS)\n # --logical-deps adds some more dependencies that are not semantically needed, but\n # may be helpful to determine relative importance of classes and functions for overall\n # type precision in a code base. It also _removes_ some deps, so this flag should be never\n # used except for generating code stats. This also automatically enables --cache-fine-grained.\n # NOTE: This is an experimental option that may be modified or removed at any time.\n parser.add_argument(\"--logical-deps\", action=\"store_true\", help=argparse.SUPPRESS)\n # --bazel changes some behaviors for use with Bazel (https:\/\/bazel.build).\n parser.add_argument(\"--bazel\", action=\"store_true\", help=argparse.SUPPRESS)\n # --package-root adds a directory below which directories are considered\n # packages even without __init__.py. May be repeated.\n parser.add_argument(\n \"--package-root\", metavar=\"ROOT\", action=\"append\", default=[], help=argparse.SUPPRESS\n )\n # --cache-map FILE ... gives a mapping from source files to cache files.\n # Each triple of arguments is a source file, a cache meta file, and a cache data file.\n # Modules not mentioned in the file will go through cache_dir.\n # Must be followed by another flag or by '--' (and then only file args may follow).\n parser.add_argument(\n \"--cache-map\", nargs=\"+\", dest=\"special-opts:cache_map\", help=argparse.SUPPRESS\n )\n # --debug-serialize will run tree.serialize() even if cache generation is disabled.\n # Useful for mypy_primer to detect serialize errors earlier.\n parser.add_argument(\"--debug-serialize\", action=\"store_true\", help=argparse.SUPPRESS)\n\n parser.add_argument(\n \"--disable-bytearray-promotion\", action=\"store_true\", help=argparse.SUPPRESS\n )\n parser.add_argument(\n \"--disable-memoryview-promotion\", action=\"store_true\", help=argparse.SUPPRESS\n )\n # This flag is deprecated, it has been moved to --extra-checks\n parser.add_argument(\"--strict-concatenate\", action=\"store_true\", help=argparse.SUPPRESS)\n\n # options specifying code to check\n code_group = parser.add_argument_group(\n title=\"Running code\",\n description=\"Specify the code you want to type check. For more details, see \"\n \"mypy.readthedocs.io\/en\/stable\/running_mypy.html#running-mypy\",\n )\n add_invertible_flag(\n \"--explicit-package-bases\",\n default=False,\n help=\"Use current directory and MYPYPATH to determine module names of files passed\",\n group=code_group,\n )\n add_invertible_flag(\n \"--fast-module-lookup\", default=False, help=argparse.SUPPRESS, group=code_group\n )\n code_group.add_argument(\n \"--exclude\",\n action=\"append\",\n metavar=\"PATTERN\",\n default=[],\n help=(\n \"Regular expression to match file names, directory names or paths which mypy should \"\n \"ignore while recursively discovering files to check, e.g. --exclude '\/setup\\\\.py$'. \"\n \"May be specified more than once, eg. --exclude a --exclude b\"\n ),\n )\n 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 options = Options()\n strict_option_set = False\n\n def set_strict_flags() -> None:\n nonlocal strict_option_set\n strict_option_set = True\n for dest, value in strict_flag_assignments:\n setattr(options, dest, value)\n\n # Parse config file first, so command line can override.\n parse_config_file(options, set_strict_flags, config_file, stdout, stderr)\n\n # Set strict flags before parsing (if strict mode enabled), so other command\n # line options can override.\n if getattr(dummy, \"special-opts:strict\"):\n set_strict_flags()\n\n # Override cache_dir if provided in the environment\n environ_cache_dir = os.getenv(\"MYPY_CACHE_DIR\", \"\")\n if environ_cache_dir.strip():\n options.cache_dir = environ_cache_dir\n options.cache_dir = os.path.expanduser(options.cache_dir)\n\n # Parse command line for real, using a split namespace.\n special_opts = argparse.Namespace()\n parser.parse_args(args, SplitNamespace(options, special_opts, \"special-opts:\"))\n\n # The python_version is either the default, which can be overridden via a config file,\n # or stored in special_opts and is passed via the command line.\n options.python_version = special_opts.python_version or options.python_version\n if options.python_version < (3,):\n parser.error(\n \"Mypy no longer supports checking Python 2 code. \"\n \"Consider pinning to mypy<0.980 if you need to check Python 2 code.\"\n )\n try:\n infer_python_executable(options, special_opts)\n except PythonExecutableInferenceError as e:\n parser.error(str(e))\n\n if special_opts.no_executable or options.no_site_packages:\n options.python_executable = None\n\n # Paths listed in the config file will be ignored if any paths, modules or packages\n # are passed on the command line.\n if not (special_opts.files or special_opts.packages or special_opts.modules):\n if options.files:\n special_opts.files = options.files\n if options.packages:\n special_opts.packages = options.packages\n if options.modules:\n special_opts.modules = options.modules\n\n # Check for invalid argument combinations.\n if require_targets:\n code_methods = sum(\n bool(c)\n for c in [\n special_opts.modules + special_opts.packages,\n special_opts.command,\n special_opts.files,\n ]\n )\n if code_methods == 0 and not options.install_types:\n parser.error(\"Missing target module, package, files, or command.\")\n elif code_methods > 1:\n parser.error(\"May only specify one of: module\/package, files, or command.\")\n if options.explicit_package_bases and not options.namespace_packages:\n parser.error(\n \"Can only use --explicit-package-bases with --namespace-packages, since otherwise \"\n \"examining __init__.py's is sufficient to determine module names for files\"\n )\n\n # Check for overlapping `--always-true` and `--always-false` flags.\n overlap = set(options.always_true) & set(options.always_false)\n if overlap:\n parser.error(\n \"You can't make a variable always true and always false (%s)\"\n % \", \".join(sorted(overlap))\n )\n\n validate_package_allow_list(options.untyped_calls_exclude)\n\n options.process_error_codes(error_callback=parser.error)\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 # 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 # 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 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 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(\"error: --install-types failed (no mypy cache directory)\\n\")\n sys.exit(2)\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/main.py","language":"Python","license":"NOASSERTION","size":57730} {"code":"from __future__ import annotations\n\nfrom mypy.expandtype import expand_type_by_instance\nfrom mypy.nodes import TypeInfo\nfrom mypy.types import AnyType, Instance, TupleType, TypeOfAny, has_type_vars\n\n\ndef map_instance_to_supertype(instance: Instance, superclass: TypeInfo) -> Instance:\n \"\"\"Produce a supertype of `instance` that is an Instance\n of `superclass`, mapping type arguments up the chain of bases.\n\n If `superclass` is not a nominal superclass of `instance.type`,\n then all type arguments are mapped to 'Any'.\n \"\"\"\n if instance.type == superclass:\n # Fast path: `instance` already belongs to `superclass`.\n return instance\n\n if superclass.fullname == \"builtins.tuple\" and instance.type.tuple_type:\n if has_type_vars(instance.type.tuple_type):\n # We special case mapping generic tuple types to tuple base, because for\n # such tuples fallback can't be calculated before applying type arguments.\n alias = instance.type.special_alias\n assert alias is not None\n if not alias._is_recursive:\n # Unfortunately we can't support this for generic recursive tuples.\n # If we skip this special casing we will fall back to tuple[Any, ...].\n tuple_type = expand_type_by_instance(instance.type.tuple_type, instance)\n if isinstance(tuple_type, TupleType):\n # Make the import here to avoid cyclic imports.\n import mypy.typeops\n\n return mypy.typeops.tuple_fallback(tuple_type)\n elif isinstance(tuple_type, Instance):\n # This can happen after normalizing variadic tuples.\n return tuple_type\n\n if not superclass.type_vars:\n # Fast path: `superclass` has no type variables to map to.\n return Instance(superclass, [])\n\n return map_instance_to_supertypes(instance, superclass)[0]\n\n\ndef map_instance_to_supertypes(instance: Instance, supertype: TypeInfo) -> list[Instance]:\n # FIX: Currently we should only have one supertype per interface, so no\n # need to return an array\n result: list[Instance] = []\n for path in class_derivation_paths(instance.type, supertype):\n types = [instance]\n for sup in path:\n a: list[Instance] = []\n for t in types:\n a.extend(map_instance_to_direct_supertypes(t, sup))\n types = a\n result.extend(types)\n if result:\n return result\n else:\n # Nothing. Presumably due to an error. Construct a dummy using Any.\n any_type = AnyType(TypeOfAny.from_error)\n return [Instance(supertype, [any_type] * len(supertype.type_vars))]\n\n\ndef class_derivation_paths(typ: TypeInfo, supertype: TypeInfo) -> list[list[TypeInfo]]:\n \"\"\"Return an array of non-empty paths of direct base classes from\n type to supertype. Return [] if no such path could be found.\n\n InterfaceImplementationPaths(A, B) == [[B]] if A inherits B\n InterfaceImplementationPaths(A, C) == [[B, C]] if A inherits B and\n B inherits C\n \"\"\"\n # FIX: Currently we might only ever have a single path, so this could be\n # simplified\n result: list[list[TypeInfo]] = []\n\n for base in typ.bases:\n btype = base.type\n if btype == supertype:\n result.append([btype])\n else:\n # Try constructing a longer path via the base class.\n for path in class_derivation_paths(btype, supertype):\n result.append([btype] + path)\n\n return result\n\n\ndef map_instance_to_direct_supertypes(instance: Instance, supertype: TypeInfo) -> list[Instance]:\n # FIX: There should only be one supertypes, always.\n typ = instance.type\n result: list[Instance] = []\n\n for b in typ.bases:\n if b.type == supertype:\n t = expand_type_by_instance(b, instance)\n assert isinstance(t, Instance)\n result.append(t)\n\n if result:\n return result\n else:\n # Relationship with the supertype not specified explicitly. Use dynamic\n # type arguments implicitly.\n any_type = AnyType(TypeOfAny.unannotated)\n return [Instance(supertype, [any_type] * len(supertype.type_vars))]\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/maptype.py","language":"Python","license":"NOASSERTION","size":4331} {"code":"from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy import join\nfrom mypy.erasetype import erase_type\nfrom mypy.maptype import map_instance_to_supertype\nfrom mypy.state import state\nfrom mypy.subtypes import (\n are_parameters_compatible,\n find_member,\n is_callable_compatible,\n is_equivalent,\n is_proper_subtype,\n is_same_type,\n is_subtype,\n)\nfrom mypy.typeops import is_recursive_pair, make_simplified_union, tuple_fallback\nfrom mypy.types import (\n MYPYC_NATIVE_INT_NAMES,\n TUPLE_LIKE_INSTANCE_NAMES,\n AnyType,\n CallableType,\n DeletedType,\n ErasedType,\n FunctionLike,\n Instance,\n LiteralType,\n NoneType,\n Overloaded,\n Parameters,\n ParamSpecType,\n PartialType,\n ProperType,\n TupleType,\n Type,\n TypeAliasType,\n TypedDictType,\n TypeGuardedType,\n TypeOfAny,\n TypeType,\n TypeVarLikeType,\n TypeVarTupleType,\n TypeVarType,\n TypeVisitor,\n UnboundType,\n UninhabitedType,\n UnionType,\n UnpackType,\n find_unpack_in_list,\n get_proper_type,\n get_proper_types,\n split_with_prefix_and_suffix,\n)\n\n# TODO Describe this module.\n\n\ndef trivial_meet(s: Type, t: Type) -> ProperType:\n \"\"\"Return one of types (expanded) if it is a subtype of other, otherwise bottom type.\"\"\"\n if is_subtype(s, t):\n return get_proper_type(s)\n elif is_subtype(t, s):\n return get_proper_type(t)\n else:\n if state.strict_optional:\n return UninhabitedType()\n else:\n return NoneType()\n\n\ndef meet_types(s: Type, t: Type) -> ProperType:\n \"\"\"Return the greatest lower bound of two types.\"\"\"\n if is_recursive_pair(s, t):\n # This case can trigger an infinite recursion, general support for this will be\n # tricky, so we use a trivial meet (like for protocols).\n return trivial_meet(s, t)\n s = get_proper_type(s)\n t = get_proper_type(t)\n\n if isinstance(s, Instance) and isinstance(t, Instance) and s.type == t.type:\n # Code in checker.py should merge any extra_items where possible, so we\n # should have only compatible extra_items here. We check this before\n # the below subtype check, so that extra_attrs will not get erased.\n if (s.extra_attrs or t.extra_attrs) and is_same_type(s, t):\n if s.extra_attrs and t.extra_attrs:\n if len(s.extra_attrs.attrs) > len(t.extra_attrs.attrs):\n # Return the one that has more precise information.\n return s\n return t\n if s.extra_attrs:\n return s\n return t\n\n if not isinstance(s, UnboundType) and not isinstance(t, UnboundType):\n if is_proper_subtype(s, t, ignore_promotions=True):\n return s\n if is_proper_subtype(t, s, ignore_promotions=True):\n return t\n\n if isinstance(s, ErasedType):\n return s\n if isinstance(s, AnyType):\n return t\n if isinstance(s, UnionType) and not isinstance(t, UnionType):\n s, t = t, s\n\n # Meets\/joins require callable type normalization.\n s, t = join.normalize_callables(s, t)\n\n return t.accept(TypeMeetVisitor(s))\n\n\ndef narrow_declared_type(declared: Type, narrowed: Type) -> Type:\n \"\"\"Return the declared type narrowed down to another type.\"\"\"\n # TODO: check infinite recursion for aliases here.\n if isinstance(narrowed, TypeGuardedType): # 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 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 if state.strict_optional:\n return UninhabitedType()\n else:\n return NoneType()\n elif isinstance(narrowed, UnionType):\n return make_simplified_union(\n [narrow_declared_type(declared, x) for x in narrowed.relevant_items()]\n )\n elif isinstance(narrowed, AnyType):\n return original_narrowed\n elif isinstance(narrowed, TypeVarType) and is_subtype(narrowed.upper_bound, declared):\n return narrowed\n elif isinstance(declared, TypeType) and isinstance(narrowed, TypeType):\n return TypeType.make_normalized(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 return [typ.upper_bound]\n elif isinstance(typ, TypeVarTupleType):\n return [typ.upper_bound]\n elif isinstance(typ, UnionType):\n return list(typ.items)\n elif isinstance(typ, Overloaded):\n # Note: doing 'return typ.items()' makes mypy\n # infer a too-specific return type of List[CallableType]\n return list(typ.items)\n else:\n return [typ]\n\n\ndef is_enum_overlapping_union(x: ProperType, y: ProperType) -> bool:\n \"\"\"Return True if x is an Enum, and y is an Union with at least one Literal from x\"\"\"\n return (\n isinstance(x, Instance)\n and x.type.is_enum\n and isinstance(y, UnionType)\n and any(\n isinstance(p, LiteralType) and x.type == p.fallback.type\n for p in (get_proper_type(z) 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) -> 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 all(\n _is_overlapping_types(left_arg, right_arg)\n for left_arg, right_arg in zip(left.args, right.args)\n ):\n return True\n\n return False\n\n # We ought to have handled every case by now: we conclude the\n # two types are not overlapping, either completely or partially.\n #\n # Note: it's unclear however, whether returning False is the right thing\n # to do when inferring reachability -- see https:\/\/github.com\/python\/mypy\/issues\/5529\n\n assert type(left) != type(right), f\"{type(left)} vs {type(right)}\"\n return False\n\n\ndef is_overlapping_erased_types(\n left: Type, right: Type, *, ignore_promotions: bool = False\n) -> bool:\n \"\"\"The same as 'is_overlapping_erased_types', except the types are erased first.\"\"\"\n return is_overlapping_types(\n erase_type(left),\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 AnyType(TypeOfAny.special_form)\n else:\n return self.s\n elif isinstance(self.s, UninhabitedType):\n return self.s\n else:\n return AnyType(TypeOfAny.special_form)\n\n def visit_any(self, t: AnyType) -> ProperType:\n return self.s\n\n def visit_union_type(self, t: UnionType) -> ProperType:\n if isinstance(self.s, UnionType):\n meets: list[Type] = []\n for x in t.items:\n for y in self.s.items:\n meets.append(meet_types(x, y))\n else:\n meets = [meet_types(x, self.s) for x in t.items]\n return make_simplified_union(meets)\n\n def visit_none_type(self, t: NoneType) -> ProperType:\n if state.strict_optional:\n if isinstance(self.s, NoneType) or (\n isinstance(self.s, Instance) and self.s.type.fullname == \"builtins.object\"\n ):\n return t\n else:\n return UninhabitedType()\n else:\n return t\n\n def visit_uninhabited_type(self, t: UninhabitedType) -> ProperType:\n return t\n\n def visit_deleted_type(self, t: DeletedType) -> ProperType:\n if isinstance(self.s, NoneType):\n if state.strict_optional:\n return t\n else:\n return self.s\n elif isinstance(self.s, UninhabitedType):\n return self.s\n else:\n return t\n\n def visit_erased_type(self, t: ErasedType) -> ProperType:\n return self.s\n\n def visit_type_var(self, t: TypeVarType) -> ProperType:\n if isinstance(self.s, TypeVarType) and self.s.id == t.id:\n 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 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, ]\n if and only if every key type is overlapping with . 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, ] if and\n only if at least one of key types overlaps with . 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, ], 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/meet.py","language":"Python","license":"NOASSERTION","size":50002} {"code":"\"\"\"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 typing import Dict, Iterable, cast\n\nfrom mypy.nodes import FakeInfo, Node\nfrom mypy.types import Type\nfrom mypy.util import get_class_descriptors\n\n\ndef collect_memory_stats() -> tuple[dict[str, int], dict[str, int]]:\n \"\"\"Return stats about memory use.\n\n Return a tuple with these items:\n - Dict from object kind to number of instances of that kind\n - Dict from object kind to total bytes used by all instances of that kind\n \"\"\"\n objs = gc.get_objects()\n find_recursive_objects(objs)\n\n inferred = {}\n for obj in objs:\n if type(obj) is FakeInfo:\n # Processing these would cause a crash.\n continue\n n = type(obj).__name__\n if hasattr(obj, \"__dict__\"):\n # Keep track of which class a particular __dict__ is associated with.\n inferred[id(obj.__dict__)] = f\"{n} (__dict__)\"\n if isinstance(obj, (Node, Type)): # type: ignore[misc]\n if hasattr(obj, \"__dict__\"):\n for x in obj.__dict__.values():\n if isinstance(x, list):\n # Keep track of which node a list is associated with.\n inferred[id(x)] = f\"{n} (list)\"\n if isinstance(x, tuple):\n # Keep track of which node a list is associated with.\n inferred[id(x)] = f\"{n} (tuple)\"\n\n for k in get_class_descriptors(type(obj)):\n x = getattr(obj, k, None)\n if isinstance(x, list):\n inferred[id(x)] = f\"{n} (list)\"\n if isinstance(x, tuple):\n inferred[id(x)] = f\"{n} (tuple)\"\n\n freqs: dict[str, int] = {}\n memuse: dict[str, int] = {}\n for obj in objs:\n if id(obj) in inferred:\n name = inferred[id(obj)]\n else:\n name = type(obj).__name__\n freqs[name] = freqs.get(name, 0) + 1\n memuse[name] = memuse.get(name, 0) + sys.getsizeof(obj)\n\n return freqs, memuse\n\n\ndef print_memory_profile(run_gc: bool = True) -> None:\n if not sys.platform.startswith(\"win\"):\n import resource\n\n system_memuse = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\n else:\n system_memuse = -1 # TODO: Support this on Windows\n if run_gc:\n gc.collect()\n freqs, memuse = collect_memory_stats()\n print(\"%7s %7s %7s %s\" % (\"Freq\", \"Size(k)\", \"AvgSize\", \"Type\"))\n print(\"-------------------------------------------\")\n totalmem = 0\n i = 0\n for n, mem in sorted(memuse.items(), key=lambda x: -x[1]):\n f = freqs[n]\n if i < 50:\n print(\"%7d %7d %7.0f %s\" % (f, mem \/\/ 1024, mem \/ f, n))\n i += 1\n totalmem += mem\n print()\n print(\"Mem usage RSS \", system_memuse \/\/ 1024)\n print(\"Total reachable \", totalmem \/\/ 1024)\n\n\ndef find_recursive_objects(objs: list[object]) -> None:\n \"\"\"Find additional objects referenced by objs and append them to objs.\n\n We use this since gc.get_objects() does not return objects without pointers\n in them such as strings.\n \"\"\"\n seen = {id(o) for o in objs}\n\n def visit(o: object) -> None:\n if id(o) not in seen:\n objs.append(o)\n seen.add(id(o))\n\n for obj in objs.copy():\n if type(obj) is FakeInfo:\n # Processing these would cause a crash.\n continue\n if type(obj) in (dict, defaultdict):\n for key, val in cast(Dict[object, object], obj).items():\n visit(key)\n visit(val)\n if type(obj) in (list, tuple, set):\n for x in cast(Iterable[object], obj):\n visit(x)\n if hasattr(obj, \"__slots__\"):\n for base in type.mro(type(obj)):\n for slot in getattr(base, \"__slots__\", ()):\n if hasattr(obj, slot):\n visit(getattr(obj, slot))\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/memprofile.py","language":"Python","license":"NOASSERTION","size":4153} {"code":"\"\"\"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)\n\n# Type checker error message constants\nNO_RETURN_VALUE_EXPECTED: Final = ErrorMessage(\"No return value expected\", codes.RETURN_VALUE)\nMISSING_RETURN_STATEMENT: Final = ErrorMessage(\"Missing return statement\", codes.RETURN)\nEMPTY_BODY_ABSTRACT: Final = ErrorMessage(\n \"If the method is meant to be abstract, use @abc.abstractmethod\", codes.EMPTY_BODY\n)\nINVALID_IMPLICIT_RETURN: Final = ErrorMessage(\"Implicit return in function which does not return\")\nINCOMPATIBLE_RETURN_VALUE_TYPE: Final = ErrorMessage(\n \"Incompatible return value type\", codes.RETURN_VALUE\n)\nRETURN_VALUE_EXPECTED: Final = ErrorMessage(\"Return value expected\", codes.RETURN_VALUE)\nNO_RETURN_EXPECTED: Final = ErrorMessage(\"Return statement in function which does not return\")\nINVALID_EXCEPTION: Final = ErrorMessage(\"Exception must be derived from BaseException\")\nINVALID_EXCEPTION_TYPE: Final = ErrorMessage(\n \"Exception type must be derived from BaseException (or be a tuple of exception classes)\"\n)\nINVALID_EXCEPTION_GROUP: Final = ErrorMessage(\n \"Exception type in except* cannot derive from BaseExceptionGroup\"\n)\nRETURN_IN_ASYNC_GENERATOR: Final = ErrorMessage(\n '\"return\" with value in async generator is not allowed'\n)\nINVALID_RETURN_TYPE_FOR_GENERATOR: Final = ErrorMessage(\n 'The return type of a generator function should be \"Generator\" or one of its supertypes'\n)\nINVALID_RETURN_TYPE_FOR_ASYNC_GENERATOR: Final = ErrorMessage(\n 'The return type of an async generator function should be \"AsyncGenerator\" or one of its '\n \"supertypes\"\n)\nYIELD_VALUE_EXPECTED: Final = ErrorMessage(\"Yield value expected\")\nINCOMPATIBLE_TYPES: Final = ErrorMessage(\"Incompatible types\")\nINCOMPATIBLE_TYPES_IN_ASSIGNMENT: Final = ErrorMessage(\n \"Incompatible types in assignment\", code=codes.ASSIGNMENT\n)\nCOVARIANT_OVERRIDE_OF_MUTABLE_ATTRIBUTE: Final = ErrorMessage(\n \"Covariant override of a mutable attribute\", code=codes.MUTABLE_OVERRIDE\n)\nINCOMPATIBLE_TYPES_IN_AWAIT: Final = ErrorMessage('Incompatible types in \"await\"')\nINCOMPATIBLE_REDEFINITION: Final = ErrorMessage(\"Incompatible redefinition\")\nINCOMPATIBLE_TYPES_IN_ASYNC_WITH_AENTER: Final = (\n 'Incompatible types in \"async with\" for \"__aenter__\"'\n)\nINCOMPATIBLE_TYPES_IN_ASYNC_WITH_AEXIT: Final = (\n 'Incompatible types in \"async with\" for \"__aexit__\"'\n)\nINCOMPATIBLE_TYPES_IN_ASYNC_FOR: Final = 'Incompatible types in \"async for\"'\nINVALID_TYPE_FOR_SLOTS: Final = 'Invalid type for \"__slots__\"'\n\nASYNC_FOR_OUTSIDE_COROUTINE: Final = '\"async for\" outside async function'\nASYNC_WITH_OUTSIDE_COROUTINE: Final = '\"async with\" outside async function'\n\nINCOMPATIBLE_TYPES_IN_YIELD: Final = ErrorMessage('Incompatible types in \"yield\"')\nINCOMPATIBLE_TYPES_IN_YIELD_FROM: Final = ErrorMessage('Incompatible types in \"yield from\"')\nINCOMPATIBLE_TYPES_IN_STR_INTERPOLATION: Final = \"Incompatible types in string interpolation\"\nINCOMPATIBLE_TYPES_IN_CAPTURE: Final = ErrorMessage(\"Incompatible types in capture pattern\")\nMUST_HAVE_NONE_RETURN_TYPE: Final = ErrorMessage('The return type of \"{}\" must be None')\nTUPLE_INDEX_OUT_OF_RANGE: Final = ErrorMessage(\"Tuple index out of range\")\nAMBIGUOUS_SLICE_OF_VARIADIC_TUPLE: Final = ErrorMessage(\"Ambiguous slice of a variadic tuple\")\nTOO_MANY_TARGETS_FOR_VARIADIC_UNPACK: Final = ErrorMessage(\n \"Too many assignment targets for variadic unpack\"\n)\nINVALID_SLICE_INDEX: Final = ErrorMessage(\"Slice index must be an integer, SupportsIndex or None\")\nCANNOT_INFER_LAMBDA_TYPE: Final = ErrorMessage(\"Cannot infer type of lambda\")\nCANNOT_ACCESS_INIT: Final = (\n 'Accessing \"__init__\" on an instance is unsound, since instance.__init__ could be from'\n \" an incompatible subclass\"\n)\nNON_INSTANCE_NEW_TYPE: Final = ErrorMessage('\"__new__\" must return a class instance (got {})')\nINVALID_NEW_TYPE: Final = ErrorMessage('Incompatible return type for \"__new__\"')\nBAD_CONSTRUCTOR_TYPE: Final = ErrorMessage(\"Unsupported decorated constructor type\")\nCANNOT_ASSIGN_TO_METHOD: Final = \"Cannot assign to a method\"\nCANNOT_ASSIGN_TO_TYPE: Final = \"Cannot assign to a type\"\nINCONSISTENT_ABSTRACT_OVERLOAD: Final = ErrorMessage(\n \"Overloaded method has both abstract and non-abstract variants\"\n)\nMULTIPLE_OVERLOADS_REQUIRED: Final = ErrorMessage(\"Single overload definition, multiple required\")\nREAD_ONLY_PROPERTY_OVERRIDES_READ_WRITE: Final = ErrorMessage(\n \"Read-only property cannot override read-write property\"\n)\nFORMAT_REQUIRES_MAPPING: Final = \"Format requires a mapping\"\nRETURN_TYPE_CANNOT_BE_CONTRAVARIANT: Final = ErrorMessage(\n \"Cannot use a contravariant type variable as return type\"\n)\nFUNCTION_PARAMETER_CANNOT_BE_COVARIANT: Final = ErrorMessage(\n \"Cannot use a covariant type variable as a parameter\"\n)\nINCOMPATIBLE_IMPORT_OF: Final = ErrorMessage('Incompatible import of \"{}\"', code=codes.ASSIGNMENT)\nFUNCTION_TYPE_EXPECTED: Final = ErrorMessage(\n \"Function is missing a type annotation\", codes.NO_UNTYPED_DEF\n)\nONLY_CLASS_APPLICATION: Final = ErrorMessage(\n \"Type application is only supported for generic classes\"\n)\nRETURN_TYPE_EXPECTED: Final = ErrorMessage(\n \"Function is missing a return type annotation\", codes.NO_UNTYPED_DEF\n)\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 \"\n \"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_OVERRIDEN: 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)\")\nTYPE_GUARD_POS_ARG_REQUIRED: Final = ErrorMessage(\"Type {} requires positional argument\")\n\n# Match Statement\nMISSING_MATCH_ARGS: Final = 'Class \"{}\" doesn\\'t define \"__match_args__\"'\nOR_PATTERN_ALTERNATIVE_NAMES: Final = \"Alternative patterns bind different names\"\nCLASS_PATTERN_GENERIC_TYPE_ALIAS: Final = (\n \"Class pattern class must not be a type alias with type parameters\"\n)\nCLASS_PATTERN_TYPE_REQUIRED: Final = 'Expected type in class pattern; found \"{}\"'\nCLASS_PATTERN_TOO_MANY_POSITIONAL_ARGS: Final = \"Too many positional patterns for class pattern\"\nCLASS_PATTERN_KEYWORD_MATCHES_POSITIONAL: Final = (\n 'Keyword \"{}\" already matches a positional pattern'\n)\nCLASS_PATTERN_DUPLICATE_KEYWORD_PATTERN: Final = 'Duplicate keyword pattern \"{}\"'\nCLASS_PATTERN_UNKNOWN_KEYWORD: Final = 'Class \"{}\" has no attribute \"{}\"'\nCLASS_PATTERN_CLASS_OR_STATIC_METHOD: Final = \"Cannot have both classmethod and staticmethod\"\nMULTIPLE_ASSIGNMENTS_IN_PATTERN: Final = 'Multiple assignments to name \"{}\" in pattern'\nCANNOT_MODIFY_MATCH_ARGS: Final = 'Cannot assign to \"__match_args__\"'\n\nDATACLASS_FIELD_ALIAS_MUST_BE_LITERAL: Final = (\n '\"alias\" argument to dataclass field must be a string literal'\n)\nDATACLASS_POST_INIT_MUST_BE_A_FUNCTION: Final = '\"__post_init__\" method must be an instance method'\n\n# fastparse\nFAILED_TO_MERGE_OVERLOADS: Final = ErrorMessage(\n \"Condition can't be inferred, unable to merge overloads\"\n)\nTYPE_IGNORE_WITH_ERRCODE_ON_MODULE: Final = ErrorMessage(\n \"type ignore with error code is not supported for modules; \"\n 'use `# mypy: disable-error-code=\"{}\"`',\n codes.SYNTAX,\n)\nINVALID_TYPE_IGNORE: Final = ErrorMessage('Invalid \"type: ignore\" comment', codes.SYNTAX)\nTYPE_COMMENT_SYNTAX_ERROR_VALUE: Final = ErrorMessage(\n 'Syntax error in type comment \"{}\"', codes.SYNTAX\n)\nELLIPSIS_WITH_OTHER_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_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\nTYPE_PARAM_DEFAULT_NOT_SUPPORTED: Final = ErrorMessage(\n \"Type parameter default types not supported when using Python 3.12 type parameter syntax\",\n codes.MISC,\n)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/message_registry.py","language":"Python","license":"NOASSERTION","size":17128} {"code":"\"\"\"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 contextlib import contextmanager\nfrom textwrap import dedent\nfrom typing import Any, Callable, Collection, Final, Iterable, Iterator, List, Sequence, cast\n\nimport mypy.typeops\nfrom mypy import errorcodes as codes, message_registry\nfrom mypy.erasetype import erase_type\nfrom mypy.errorcodes import ErrorCode\nfrom mypy.errors import 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 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 LiteralType,\n NoneType,\n Overloaded,\n Parameters,\n ParamSpecType,\n PartialType,\n ProperType,\n TupleType,\n Type,\n TypeAliasType,\n TypedDictType,\n TypeOfAny,\n TypeStrVisitor,\n TypeType,\n TypeVarLikeType,\n TypeVarTupleType,\n TypeVarType,\n UnboundType,\n UninhabitedType,\n UnionType,\n UnpackType,\n flatten_nested_unions,\n get_proper_type,\n get_proper_types,\n)\nfrom mypy.typetraverser import TypeTraverserVisitor\nfrom mypy.util import plural_s, unmangle\n\nTYPES_FOR_UNIMPORTED_HINTS: Final = {\n \"typing.Any\",\n \"typing.Callable\",\n \"typing.Dict\",\n \"typing.Iterable\",\n \"typing.Iterator\",\n \"typing.List\",\n \"typing.Optional\",\n \"typing.Set\",\n \"typing.Tuple\",\n \"typing.TypeVar\",\n \"typing.Union\",\n \"typing.cast\",\n}\n\n\nARG_CONSTRUCTOR_NAMES: Final = {\n ARG_POS: \"Arg\",\n ARG_OPT: \"DefaultArg\",\n ARG_NAMED: \"NamedArg\",\n ARG_NAMED_OPT: \"DefaultNamedArg\",\n ARG_STAR: \"VarArg\",\n ARG_STAR2: \"KwArg\",\n}\n\n\n# Map from the full name of a missing definition to the test fixture (under\n# test-data\/unit\/fixtures\/) that provides the definition. This is used for\n# generating better error messages when running mypy tests only.\nSUGGESTED_TEST_FIXTURES: Final = {\n \"builtins.set\": \"set.pyi\",\n \"builtins.tuple\": \"tuple.pyi\",\n \"builtins.bool\": \"bool.pyi\",\n \"builtins.Exception\": \"exception.pyi\",\n \"builtins.BaseException\": \"exception.pyi\",\n \"builtins.isinstance\": \"isinstancelist.pyi\",\n \"builtins.property\": \"property.pyi\",\n \"builtins.classmethod\": \"classmethod.pyi\",\n \"typing._SpecialForm\": \"typing-medium.pyi\",\n}\n\nUNSUPPORTED_NUMBERS_TYPES: Final = {\n \"numbers.Number\",\n \"numbers.Complex\",\n \"numbers.Real\",\n \"numbers.Rational\",\n \"numbers.Integral\",\n}\n\nMAX_TUPLE_ITEMS = 10\nMAX_UNION_ITEMS = 10\n\n\nclass MessageBuilder:\n \"\"\"Helper class for reporting type checker error messages with parameters.\n\n The methods of this class need to be provided with the context within a\n file; the errors member manages the wider context.\n\n IDEA: Support a 'verbose mode' that includes full information about types\n in error messages and that may otherwise produce more detailed error\n messages.\n \"\"\"\n\n # Report errors using this instance. It knows about the current file and\n # import context.\n errors: Errors\n\n modules: dict[str, MypyFile]\n\n # Hack to deduplicate error messages from union types\n _disable_type_names: list[bool]\n\n def __init__(self, errors: Errors, modules: dict[str, MypyFile]) -> None:\n self.errors = errors\n self.options = errors.options\n self.modules = modules\n self._disable_type_names = []\n\n #\n # Helpers\n #\n\n def filter_errors(\n self,\n *,\n filter_errors: bool | Callable[[str, ErrorInfo], bool] = True,\n save_filtered_errors: bool = False,\n ) -> 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 ) -> 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.deco_line or 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 )\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 ) -> 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 )\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 == \"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 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}, \"\n f\"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 == \"\":\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 == \"\" 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 == \"\":\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 == \"\":\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 == \"\":\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 == \"\":\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 == \"\":\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\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:\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:\/\/mypy.readthedocs.io\/en\/stable\/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 \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:\/\/mypy.readthedocs.io\/en\/stable\/more_types.html#asynchronous-iterators\",\n context,\n )\n\n def override_target(self, name: str, name_in_super: str, supertype: str) -> str:\n target = f'supertype \"{supertype}\"'\n if name_in_super != name:\n target = f'\"{name_in_super}\" of {target}'\n return target\n\n def incompatible_type_application(\n self, min_arg_count: int, max_arg_count: int, actual_arg_count: int, context: Context\n ) -> None:\n if max_arg_count == 0:\n self.fail(\"Type application targets a non-generic function or class\", context)\n return\n\n if min_arg_count == max_arg_count:\n s = f\"{max_arg_count} expected\"\n else:\n s = f\"expected between {min_arg_count} and {max_arg_count}\"\n\n if actual_arg_count > max_arg_count:\n self.fail(f\"Type application has too many types ({s})\", context)\n else:\n self.fail(f\"Type application has too few types ({s})\", context)\n\n def could_not_infer_type_arguments(\n self, callee_type: CallableType, 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 == \"\":\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[, ]\",\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(\"List or tuple expected as variadic arguments\", 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 'Call to abstract method \"{}\" of \"{}\" with trivial body'\n \" via super() is unsafe\".format(method, cls),\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 'Cannot override final attribute \"{}\"'\n ' (previously declared in base class \"{}\")'.format(name, base_name),\n ctx,\n )\n\n def cant_assign_to_final(self, name: str, attr_assign: bool, ctx: Context) -> None:\n \"\"\"Warn about a prohibited assignment to a final attribute.\n\n Pass `attr_assign=True` if the assignment assigns to an attribute.\n \"\"\"\n kind = \"attribute\" if attr_assign else \"name\"\n self.fail(f'Cannot assign to final {kind} \"{unmangle(name)}\"', ctx)\n\n def protocol_members_cant_be_final(self, ctx: Context) -> None:\n self.fail(\"Protocol member cannot be final\", ctx)\n\n def final_without_value(self, ctx: Context) -> None:\n self.fail(\"Final name must be initialized with a value\", ctx)\n\n def read_only_property(self, name: str, type: TypeInfo, context: Context) -> None:\n self.fail(f'Property \"{name}\" defined in \"{type.name}\" is read-only', context)\n\n def incompatible_typevar_value(\n self, callee: CallableType, typ: Type, typevar_name: str, context: Context\n ) -> None:\n self.fail(\n message_registry.INCOMPATIBLE_TYPEVAR_VALUE.format(\n typevar_name, callable_name(callee) or \"function\", format_type(typ, self.options)\n ),\n context,\n code=codes.TYPE_VAR,\n )\n\n def dangerous_comparison(self, left: Type, right: Type, kind: str, ctx: Context) -> None:\n 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 \"Overloaded function implementation does not accept all possible arguments \"\n \"of signature {}\".format(index),\n context,\n )\n\n def overloaded_signatures_ret_specific(self, index: int, context: Context) -> None:\n self.fail(\n \"Overloaded function implementation cannot produce return type \"\n \"of signature {}\".format(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 {} '\n \"are unsafely overlapping\".format(\n reverse_method,\n reverse_class.name,\n forward_method,\n format_type(forward_class, self.options),\n ),\n context,\n )\n\n def forward_operator_not_callable(self, forward_method: str, context: Context) -> None:\n self.fail(f'Forward operator \"{forward_method}\" is not callable', context)\n\n def signatures_incompatible(self, method: str, other_method: str, context: Context) -> None:\n self.fail(f'Signatures of \"{method}\" and \"{other_method}\" are incompatible', context)\n\n def yield_from_invalid_operand_type(self, expr: Type, context: Context) -> Type:\n text = (\n format_type(expr, self.options)\n if format_type(expr, self.options) != \"object\"\n else expr\n )\n self.fail(f'\"yield from\" can\\'t be applied to {text}', context)\n return AnyType(TypeOfAny.from_error)\n\n def invalid_signature(self, func_type: Type, context: Context) -> None:\n self.fail(f\"Invalid signature {format_type(func_type, self.options)}\", context)\n\n def invalid_signature_for_special_method(\n self, func_type: Type, context: Context, method_name: str\n ) -> None:\n self.fail(\n f'Invalid signature {format_type(func_type, self.options)} for \"{method_name}\"',\n context,\n )\n\n def reveal_type(self, typ: Type, context: Context) -> None:\n visitor = TypeStrVisitor(options=self.options)\n self.note(f'Revealed type is \"{typ.accept(visitor)}\"', context)\n\n def reveal_locals(self, type_map: dict[str, Type | None], context: Context) -> None:\n # To ensure that the output is predictable on Python < 3.6,\n # use an ordered dictionary sorted by variable name\n sorted_locals = dict(sorted(type_map.items(), key=lambda t: t[0]))\n if sorted_locals:\n self.note(\"Revealed local types are:\", context)\n for k, v in sorted_locals.items():\n visitor = TypeStrVisitor(options=self.options)\n self.note(f\" {k}: {v.accept(visitor) if v is not None else None}\", context)\n else:\n self.note(\"There are no locals to reveal\", context)\n\n def unsupported_type_type(self, item: Type, context: Context) -> None:\n self.fail(\n f'Cannot instantiate type \"Type[{format_type_bare(item, self.options)}]\"', context\n )\n\n def redundant_cast(self, typ: Type, context: Context) -> None:\n self.fail(\n f\"Redundant cast to {format_type(typ, self.options)}\",\n context,\n code=codes.REDUNDANT_CAST,\n )\n\n def assert_type_fail(self, source_type: Type, target_type: Type, context: Context) -> None:\n (source, target) = format_type_distinctly(source_type, target_type, options=self.options)\n self.fail(f\"Expression is of type {source}, not {target}\", context, code=codes.ASSERT_TYPE)\n\n def unimported_type_becomes_any(self, prefix: str, typ: Type, ctx: Context) -> None:\n self.fail(\n f\"{prefix} becomes {format_type(typ, self.options)} due to an unfollowed import\",\n ctx,\n code=codes.NO_ANY_UNIMPORTED,\n )\n\n def need_annotation_for_var(\n self, node: SymbolNode, context: Context, 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 = \"\"\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 alias = reverse_builtin_aliases[node.type.type.fullname]\n alias = alias.split(\".\")[-1]\n if alias == \"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)\n\n def unsupported_target_for_star_typeddict(self, typ: Type, ctx: Context) -> None:\n self.fail(\n \"Unsupported type {} for ** expansion in TypedDict\".format(\n format_type(typ, self.options)\n ),\n ctx,\n code=codes.TYPEDDICT_ITEM,\n )\n\n def non_required_keys_absent_with_star(self, keys: list[str], ctx: Context) -> None:\n self.fail(\n \"Non-required {} not explicitly found in any ** item\".format(\n format_key_list(keys, short=True)\n ),\n ctx,\n code=codes.TYPEDDICT_ITEM,\n )\n\n def unexpected_typeddict_keys(\n self,\n typ: TypedDictType,\n expected_keys: list[str],\n actual_keys: list[str],\n context: Context,\n ) -> None:\n actual_set = set(actual_keys)\n expected_set = set(expected_keys)\n if not typ.is_anonymous():\n # Generate simpler messages for some common special cases.\n # Use list comprehension instead of set operations to preserve order.\n missing = [key for key in expected_keys if key not in actual_set]\n if missing:\n self.fail(\n \"Missing {} for TypedDict {}\".format(\n format_key_list(missing, short=True), format_type(typ, self.options)\n ),\n context,\n code=codes.TYPEDDICT_ITEM,\n )\n extra = [key for key in actual_keys if key not in expected_set]\n if extra:\n self.fail(\n \"Extra {} for TypedDict {}\".format(\n format_key_list(extra, short=True), format_type(typ, self.options)\n ),\n context,\n code=codes.TYPEDDICT_UNKNOWN_KEY,\n )\n if missing or extra:\n # No need to check for further errors\n return\n found = format_key_list(actual_keys, short=True)\n if not expected_keys:\n self.fail(f\"Unexpected TypedDict {found}\", context)\n return\n expected = format_key_list(expected_keys)\n if actual_keys and actual_set < expected_set:\n found = f\"only {found}\"\n self.fail(f\"Expected {expected} but found {found}\", context, code=codes.TYPEDDICT_ITEM)\n\n def typeddict_key_must_be_string_literal(self, typ: TypedDictType, context: Context) -> None:\n self.fail(\n \"TypedDict key must be a string literal; expected one of {}\".format(\n format_item_name_list(typ.items.keys())\n ),\n context,\n code=codes.LITERAL_REQ,\n )\n\n def typeddict_key_not_found(\n self, typ: TypedDictType, item_name: str, context: Context, setitem: bool = False\n ) -> None:\n \"\"\"Handle error messages for TypedDicts that have unknown keys.\n\n Note, that we differentiate in between reading a value and setting a\n value.\n Setting a value on a TypedDict is an 'unknown-key' error, whereas\n reading it is the more serious\/general 'item' error.\n \"\"\"\n if typ.is_anonymous():\n self.fail(\n '\"{}\" is not a valid TypedDict key; expected one of {}'.format(\n item_name, format_item_name_list(typ.items.keys())\n ),\n context,\n )\n else:\n err_code = codes.TYPEDDICT_UNKNOWN_KEY if setitem else codes.TYPEDDICT_ITEM\n self.fail(\n f'TypedDict {format_type(typ, self.options)} has no key \"{item_name}\"',\n context,\n code=err_code,\n )\n matches = best_matches(item_name, typ.items.keys(), n=3)\n if matches:\n self.note(\n \"Did you mean {}?\".format(pretty_seq(matches, \"or\")), context, code=err_code\n )\n\n def typeddict_context_ambiguous(self, types: list[TypedDictType], context: Context) -> None:\n formatted_types = \", \".join(list(format_type_distinctly(*types, options=self.options)))\n self.fail(\n f\"Type of TypedDict is ambiguous, none of ({formatted_types}) matches cleanly\", context\n )\n\n def typeddict_key_cannot_be_deleted(\n self, typ: TypedDictType, item_name: str, context: Context\n ) -> None:\n if typ.is_anonymous():\n self.fail(f'TypedDict key \"{item_name}\" cannot be deleted', context)\n else:\n self.fail(\n f'Key \"{item_name}\" of TypedDict {format_type(typ, self.options)} cannot be deleted',\n context,\n )\n\n def typeddict_setdefault_arguments_inconsistent(\n self, default: Type, expected: Type, context: Context\n ) -> None:\n msg = 'Argument 2 to \"setdefault\" of \"TypedDict\" has incompatible type {}; expected {}'\n self.fail(\n msg.format(format_type(default, self.options), format_type(expected, self.options)),\n context,\n code=codes.TYPEDDICT_ITEM,\n )\n\n def type_arguments_not_allowed(self, context: Context) -> None:\n self.fail(\"Parameterized generics cannot be used with class or instance checks\", context)\n\n def disallowed_any_type(self, typ: Type, context: Context) -> None:\n typ = get_proper_type(typ)\n if isinstance(typ, AnyType):\n message = 'Expression has type \"Any\"'\n else:\n message = f'Expression type contains \"Any\" (has type {format_type(typ, self.options)})'\n self.fail(message, context)\n\n def incorrectly_returning_any(self, typ: Type, context: Context) -> None:\n message = (\n f\"Returning Any from function declared to return {format_type(typ, self.options)}\"\n )\n self.fail(message, context, code=codes.NO_ANY_RETURN)\n\n def incorrect__exit__return(self, context: Context) -> None:\n self.fail(\n '\"bool\" is invalid as return type for \"__exit__\" that always returns False',\n context,\n code=codes.EXIT_RETURN,\n )\n self.note(\n 'Use \"typing_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(\"Function is untyped after decorator transformation\", context)\n else:\n self.fail(\n f'Type of decorated function contains type \"Any\" ({format_type(typ, self.options)})',\n context,\n )\n\n def typed_function_untyped_decorator(self, func_name: str, context: Context) -> None:\n self.fail(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'\n \" {} one is expected\".format(\n variance_string(actual), tvar_name, variance_string(expected)\n )\n )\n self.fail(msg, context)\n\n def concrete_only_assign(self, typ: Type, context: Context) -> None:\n self.fail(\n f\"Can only assign concrete classes to a variable of type {format_type(typ, self.options)}\",\n context,\n code=codes.TYPE_ABSTRACT,\n )\n\n def concrete_only_call(self, typ: Type, context: Context) -> None:\n self.fail(\n f\"Only concrete class can be given where {format_type(typ, self.options)} is expected\",\n context,\n code=codes.TYPE_ABSTRACT,\n )\n\n def cannot_use_function_with_type(\n self, method_name: str, type_name: str, context: Context\n ) -> None:\n self.fail(f\"Cannot use {method_name}() with {type_name} type\", context)\n\n def report_non_method_protocol(\n self, tp: TypeInfo, members: list[str], context: Context\n ) -> None:\n self.fail(\n \"Only protocols that don't have non-method members can be used with issubclass()\",\n context,\n )\n if len(members) < 3:\n attrs = \", \".join(members)\n self.note(f'Protocol \"{tp.name}\" has non-method member(s): {attrs}', context)\n\n def note_call(\n self, subtype: Type, call: Type, context: Context, *, code: ErrorCode | None\n ) -> None:\n self.note(\n '\"{}.__call__\" has type {}'.format(\n format_type_bare(subtype, self.options),\n format_type(call, self.options, verbosity=1),\n ),\n context,\n code=code,\n )\n\n def unreachable_statement(self, context: Context) -> None:\n self.fail(\"Statement is unreachable\", context, code=codes.UNREACHABLE)\n\n def redundant_left_operand(self, op_name: str, context: Context) -> None:\n \"\"\"Indicates that the left operand of a boolean expression is redundant:\n it does not change the truth value of the entire condition as a whole.\n 'op_name' should either be the string \"and\" or the string \"or\".\n \"\"\"\n self.redundant_expr(f'Left operand of \"{op_name}\"', op_name == \"and\", context)\n\n def unreachable_right_operand(self, op_name: str, context: Context) -> None:\n \"\"\"Indicates that the right operand of a boolean expression is redundant:\n it does not change the truth value of the entire condition as a whole.\n 'op_name' should either be the string \"and\" or the string \"or\".\n \"\"\"\n self.fail(\n f'Right operand of \"{op_name}\" is never evaluated', context, code=codes.UNREACHABLE\n )\n\n def redundant_condition_in_comprehension(self, truthiness: bool, context: Context) -> None:\n self.redundant_expr(\"If condition in comprehension\", truthiness, context)\n\n def redundant_condition_in_if(self, truthiness: bool, context: Context) -> None:\n self.redundant_expr(\"If condition\", truthiness, context)\n\n def redundant_expr(self, description: str, truthiness: bool, context: Context) -> None:\n self.fail(\n f\"{description} is always {str(truthiness).lower()}\",\n context,\n code=codes.REDUNDANT_EXPR,\n )\n\n def impossible_intersection(\n self, formatted_base_class_list: str, reason: str, context: Context\n ) -> None:\n template = \"Subclass of {} cannot exist: {}\"\n self.fail(\n template.format(formatted_base_class_list, reason), context, code=codes.UNREACHABLE\n )\n\n def tvar_without_default_type(\n self, tvar_name: str, last_tvar_name_with_default: str, context: Context\n ) -> None:\n self.fail(\n f'\"{tvar_name}\" cannot appear after \"{last_tvar_name_with_default}\" '\n \"in type parameter list because it has no default type\",\n context,\n )\n\n def report_protocol_problems(\n self,\n subtype: Instance | TupleType | TypedDictType | TypeType | CallableType,\n supertype: Instance,\n context: Context,\n *,\n 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,\"\n \" got class variable\".format(supertype.type.name, name),\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,\"\n \" got instance variable\".format(supertype.type.name, name),\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\", \"\"]\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 for arg_name, arg_type, arg_kind in zip(arg_names, arg_types, arg_kinds):\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\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) -> 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 \"\"\"\n\n def format(typ: Type) -> str:\n return format_type_inner(typ, verbosity, options, fullnames)\n\n def format_list(types: Sequence[Type]) -> str:\n return \", \".join(format(typ) for typ in types)\n\n def format_union_items(types: Sequence[Type]) -> list[str]:\n formatted = [format(typ) for typ in types if format(typ) != \"None\"]\n if len(formatted) > MAX_UNION_ITEMS and verbosity == 0:\n more = len(formatted) - MAX_UNION_ITEMS \/\/ 2\n formatted = formatted[: MAX_UNION_ITEMS \/\/ 2]\n else:\n more = 0\n if more:\n formatted.append(f\"<{more} more items>\")\n if any(format(typ) == \"None\" for typ in types):\n formatted.append(\"None\")\n return formatted\n\n def format_union(types: Sequence[Type]) -> str:\n return \" | \".join(format_union_items(types))\n\n def format_literal_value(typ: LiteralType) -> str:\n if typ.is_enum_literal():\n underlying_type = format(typ.fallback)\n return f\"{underlying_type}.{typ.value}\"\n else:\n return typ.value_repr()\n\n if isinstance(typ, TypeAliasType) and typ.is_recursive:\n if typ.alias is None:\n type_str = \"\"\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 \"\"\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 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 fullname = scoped_type_var_name(typ)\n if verbosity >= 2 or (fullnames and fullname in fullnames):\n return fullname\n return typ.name\n elif isinstance(typ, TypeVarTupleType):\n # This is similar to non-generic instance types.\n fullname = scoped_type_var_name(typ)\n if verbosity >= 2 or (fullnames and fullname in fullnames):\n return fullname\n return typ.name\n elif isinstance(typ, ParamSpecType):\n # Concatenate[..., P]\n if typ.prefix.arg_types:\n args = format_callable_args(\n typ.prefix.arg_types, typ.prefix.arg_kinds, typ.prefix.arg_names, format, verbosity\n )\n\n return f\"[{args}, **{typ.name_with_suffix()}]\"\n else:\n # TODO: better disambiguate ParamSpec name clashes.\n return typ.name_with_suffix()\n elif isinstance(typ, TupleType):\n # Prefer the name of the fallback class (if not tuple), as it's more informative.\n if typ.partial_fallback.type.fullname != \"builtins.tuple\":\n return format(typ.partial_fallback)\n type_items = format_list(typ.items) or \"()\"\n if options.use_lowercase_names():\n s = f\"tuple[{type_items}]\"\n else:\n s = f\"Tuple[{type_items}]\"\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 return f\"Literal[{format_literal_value(typ)}]\"\n elif isinstance(typ, UnionType):\n typ = get_proper_type(ignore_last_known_values(typ))\n if not isinstance(typ, UnionType):\n return format(typ)\n literal_items, union_items = separate_union_literals(typ)\n\n # Coalesce multiple Literal[] members. This also changes output order.\n # If there's just one Literal item, retain the original ordering.\n if len(literal_items) > 1:\n literal_str = \"Literal[{}]\".format(\n \", \".join(format_literal_value(t) for t in literal_items)\n )\n\n if len(union_items) == 1 and isinstance(get_proper_type(union_items[0]), NoneType):\n return (\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, NoneType):\n return \"None\"\n elif isinstance(typ, AnyType):\n return \"Any\"\n elif isinstance(typ, DeletedType):\n return \"\"\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(erase_type(func.items[0].ret_type)))\n elif isinstance(func, CallableType):\n if func.type_guard is not None:\n return_type = f\"TypeGuard[{format(func.type_guard)}]\"\n elif func.type_is is not None:\n return_type = f\"TypeIs[{format(func.type_is)}]\"\n else:\n return_type = format(func.ret_type)\n if func.is_ellipsis_args:\n return f\"Callable[..., {return_type}]\"\n param_spec = func.param_spec()\n if param_spec is not None:\n return f\"Callable[{format(param_spec)}, {return_type}]\"\n args = format_callable_args(\n func.arg_types, func.arg_kinds, func.arg_names, format, verbosity\n )\n return f\"Callable[[{args}], {return_type}]\"\n else:\n # Use a simple representation for function types; proper\n # function types may result in long and difficult-to-read\n # error messages.\n return \"overloaded function\"\n elif isinstance(typ, UnboundType):\n return typ.accept(TypeStrVisitor(options=options))\n elif isinstance(typ, Parameters):\n args = format_callable_args(typ.arg_types, typ.arg_kinds, typ.arg_names, format, verbosity)\n return f\"[{args}]\"\n elif typ is None:\n raise RuntimeError(\"Type is None\")\n else:\n # Default case; we simply have to return something meaningful here.\n return \"object\"\n\n\ndef collect_all_named_types(t: Type) -> list[Type]:\n \"\"\"Return all instances\/aliases\/type variables that `t` contains (including `t`).\n\n This is similar to collect_all_inner_types from typeanal but only\n returns instances and will recurse into fallbacks.\n \"\"\"\n visitor = CollectAllNamedTypesQuery()\n t.accept(visitor)\n return visitor.types\n\n\nclass CollectAllNamedTypesQuery(TypeTraverserVisitor):\n def __init__(self) -> None:\n self.types: list[Type] = []\n\n def visit_instance(self, t: Instance) -> None:\n self.types.append(t)\n super().visit_instance(t)\n\n def visit_type_alias_type(self, t: TypeAliasType) -> None:\n if t.alias and not t.is_recursive:\n get_proper_type(t).accept(self)\n else:\n self.types.append(t)\n super().visit_type_alias_type(t)\n\n def visit_type_var(self, t: TypeVarType) -> None:\n self.types.append(t)\n super().visit_type_var(t)\n\n def visit_type_var_tuple(self, t: TypeVarTupleType) -> None:\n self.types.append(t)\n super().visit_type_var_tuple(t)\n\n def visit_param_spec(self, t: ParamSpecType) -> None:\n self.types.append(t)\n super().visit_param_spec(t)\n\n\ndef scoped_type_var_name(t: TypeVarLikeType) -> str:\n if not t.id.namespace:\n return t.name\n # TODO: support rare cases when both TypeVar name and namespace suffix coincide.\n *_, suffix = t.id.namespace.split(\".\")\n return f\"{t.name}@{suffix}\"\n\n\ndef find_type_overlaps(*types: Type) -> set[str]:\n \"\"\"Return a set of fullnames that share a short name and appear in either type.\n\n This is used to ensure that distinct types with the same short name are printed\n with their fullname.\n \"\"\"\n d: dict[str, set[str]] = {}\n for type in types:\n for t in collect_all_named_types(type):\n if isinstance(t, ProperType) and isinstance(t, Instance):\n d.setdefault(t.type.name, set()).add(t.type.fullname)\n elif isinstance(t, TypeAliasType) and t.alias:\n d.setdefault(t.alias.name, set()).add(t.alias.fullname)\n else:\n assert isinstance(t, TypeVarLikeType)\n d.setdefault(t.name, set()).add(scoped_type_var_name(t))\n for shortname in d.keys():\n if f\"typing.{shortname}\" in TYPES_FOR_UNIMPORTED_HINTS:\n d[shortname].add(f\"typing.{shortname}\")\n\n overlaps: set[str] = set()\n for fullnames in d.values():\n if len(fullnames) > 1:\n overlaps.update(fullnames)\n return overlaps\n\n\ndef format_type(\n typ: Type, options: Options, verbosity: int = 0, module_names: bool = False\n) -> str:\n \"\"\"\n Convert a type to a relatively short string suitable for error messages.\n\n `verbosity` is a coarse-grained control on the verbosity of the type\n\n This function returns a string appropriate for unmodified use in error\n messages; this means that it will be quoted in most cases. If\n modification of the formatted string is required, callers should use\n format_type_bare.\n \"\"\"\n return quote_type_string(format_type_bare(typ, options, verbosity, module_names))\n\n\ndef format_type_bare(\n typ: Type, options: Options, verbosity: int = 0, module_names: bool = False\n) -> str:\n \"\"\"\n Convert a type to a relatively short string suitable for error messages.\n\n `verbosity` is a coarse-grained control on the verbosity of the type\n `fullnames` specifies a set of names that should be printed in full\n\n This function will return an unquoted string. If a caller doesn't need to\n perform post-processing on the string output, format_type should be used\n instead. (The caller may want to use quote_type_string after\n processing has happened, to maintain consistent quoting in messages.)\n \"\"\"\n return format_type_inner(typ, verbosity, options, find_type_overlaps(typ), module_names)\n\n\ndef format_type_distinctly(*types: Type, options: Options, bare: bool = False) -> tuple[str, ...]:\n \"\"\"Jointly format types to distinct strings.\n\n Increase the verbosity of the type strings until they become distinct\n while also requiring that distinct types with the same short name are\n formatted distinctly.\n\n By default, the returned strings are created using format_type() and will be\n quoted accordingly. If ``bare`` is True, the returned strings will not\n be quoted; callers who need to do post-processing of the strings before\n quoting them (such as prepending * or **) should use this.\n \"\"\"\n overlapping = find_type_overlaps(*types)\n 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 s += f\"TypeGuard[{format_type_bare(tp.type_guard, options)}]\"\n elif tp.type_is is not None:\n s += f\"TypeIs[{format_type_bare(tp.type_is, options)}]\"\n else:\n s += format_type_bare(tp.ret_type, options)\n\n if tp.variables:\n tvars = []\n for tvar in tp.variables:\n if isinstance(tvar, TypeVarType):\n upper_bound = get_proper_type(tvar.upper_bound)\n if not (\n isinstance(upper_bound, Instance)\n and upper_bound.type.fullname == \"builtins.object\"\n ):\n tvars.append(f\"{tvar.name}: {format_type_bare(upper_bound, options)}\")\n elif tvar.values:\n tvars.append(\n \"{}: ({})\".format(\n tvar.name,\n \", \".join([format_type_bare(tp, options) for tp in tvar.values]),\n )\n )\n else:\n tvars.append(tvar.name)\n else:\n # For other TypeVarLikeTypes, just use the repr\n tvars.append(repr(tvar))\n s = f\"[{', '.join(tvars)}] {s}\"\n return f\"def {s}\"\n\n\ndef 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, ignore_pos_arg_names=True, 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:\/\/mypy.readthedocs.io\/en\/stable\/common_issues.html#variance\"\n )\n notes.append(covariant_suggestion)\n return notes\n\n\ndef append_union_note(\n notes: list[str], arg_type: UnionType, expected_type: UnionType, options: Options\n) -> list[str]:\n \"\"\"Point to specific union item(s) that may cause failure in subtype check.\"\"\"\n non_matching = []\n items = flatten_nested_unions(arg_type.items)\n if len(items) < MAX_UNION_ITEMS:\n return notes\n for item in items:\n if not is_subtype(item, expected_type):\n non_matching.append(item)\n if non_matching:\n types = \", \".join([format_type(typ, options) for typ in non_matching])\n notes.append(f\"Item{plural_s(non_matching)} in the first union not in the second: {types}\")\n return notes\n\n\ndef append_numbers_notes(\n notes: list[str], arg_type: Instance, expected_type: Instance\n) -> list[str]:\n \"\"\"Explain if an unsupported type from \"numbers\" is used in a subtype check.\"\"\"\n if expected_type.type.fullname in UNSUPPORTED_NUMBERS_TYPES:\n notes.append('Types from \"numbers\" 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/messages.py","language":"Python","license":"NOASSERTION","size":130191} {"code":"\"\"\"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 typing import TYPE_CHECKING, Any, Iterable\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.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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/metastore.py","language":"Python","license":"NOASSERTION","size":6554} {"code":"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 TypeAliasExpr,\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 self.in_type_alias_expr = True\n o.node.target.accept(self)\n self.in_type_alias_expr = False\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_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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/mixedtraverser.py","language":"Python","license":"NOASSERTION","size":3205} {"code":"\"\"\"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 Dict, Final, List, NamedTuple, Optional, Tuple, Union\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 approved_stub_package_exists\nfrom mypy.util import os_path_join\n\n\n# Paths to be searched in find_module().\nclass SearchPaths(NamedTuple):\n python_path: tuple[str, ...] # where user code is found\n mypy_path: tuple[str, ...] # from $MYPYPATH or config variable\n package_path: tuple[str, ...] # from get_site_packages_dirs()\n typeshed_path: tuple[str, ...] # paths in typeshed\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:\/\/mypy.readthedocs.io\/en\/stable\/running_mypy.html#missing-imports\"\n if self is ModuleNotFoundReason.NOT_FOUND:\n msg = 'Cannot find implementation or library stub for module named \"{module}\"'\n notes = [doc_link]\n elif self is ModuleNotFoundReason.WRONG_WORKING_DIRECTORY:\n msg = 'Cannot find implementation or library stub for module named \"{module}\"'\n notes = [\n \"You may be running mypy in a subpackage, \"\n \"mypy should be run on the package root\"\n ]\n elif self is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS:\n msg = (\n 'Skipping analyzing \"{module}\": module is installed, but missing library stubs '\n \"or py.typed marker\"\n )\n notes = [doc_link]\n elif self is ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED:\n msg = 'Library stubs not installed for \"{module}\"'\n notes = ['Hint: \"python3 -m pip install {stub_dist}\"']\n if not daemon:\n notes.append(\n '(or run \"mypy --install-types\" to install all missing stub packages)'\n )\n notes.append(doc_link)\n else:\n assert False\n return msg, notes\n\n\n# If we found the module, returns the path to the module as a str.\n# Otherwise, returns the reason why the module wasn't found.\nModuleSearchResult = 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\n This is run for the python_path, mypy_path, and typeshed_path search paths.\n \"\"\"\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 dir = os.path.normpath(os_path_join(pathitem, dir_chain))\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, components: list[str], pkg_dir: str\n ) -> OnePackageDir | ModuleNotFoundReason:\n plausible_match = False\n dir_path = pkg_dir\n for index, component in enumerate(components):\n dir_path = os_path_join(dir_path, component)\n if self.fscache.isfile(os_path_join(dir_path, \"py.typed\")):\n return os.path.join(pkg_dir, *components[:-1]), index == 0\n elif not plausible_match and (\n self.fscache.isdir(dir_path) or self.fscache.isfile(dir_path + \".py\")\n ):\n plausible_match = True\n # If this is not a directory then we can't traverse further into it\n if not self.fscache.isdir(dir_path):\n break\n if approved_stub_package_exists(\".\".join(components)):\n return ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED\n if plausible_match:\n return ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS\n else:\n return ModuleNotFoundReason.NOT_FOUND\n\n def _update_ns_ancestors(self, components: list[str], match: tuple[str, bool]) -> None:\n path, verify = match\n for i in range(1, len(components)):\n pkg_id = \".\".join(components[:-i])\n if pkg_id not in self.ns_ancestors and self.fscache.isdir(path):\n self.ns_ancestors[pkg_id] = path\n path = os.path.dirname(path)\n\n def _can_find_module_in_parent_dir(self, id: str) -> bool:\n \"\"\"Test if a module can be found by checking the parent directories\n of the current working directory.\n \"\"\"\n working_dir = os.getcwd()\n parent_search = FindModuleCache(\n SearchPaths((), (), (), ()),\n self.fscache,\n self.options,\n stdlib_py_versions=self.stdlib_py_versions,\n )\n while any(is_init_file(file) for file in os.listdir(working_dir)):\n working_dir = os.path.dirname(working_dir)\n parent_search.search_paths = SearchPaths((working_dir,), (), (), ())\n if not isinstance(parent_search._find_module(id, False), 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 need_installed_stubs = False\n # Third-party stub\/typed packages\n for pkg_dir in self.search_paths.package_path:\n stub_name = components[0] + \"-stubs\"\n stub_dir = os_path_join(pkg_dir, stub_name)\n if fscache.isdir(stub_dir):\n stub_typed_file = os_path_join(stub_dir, \"py.typed\")\n stub_components = [stub_name] + components[1:]\n path = os.path.join(pkg_dir, *stub_components[:-1])\n if fscache.isdir(path):\n if fscache.isfile(stub_typed_file):\n # Stub packages can have a py.typed file, which must include\n # 'partial\\n' to make the package partial\n # Partial here means that mypy should look at the runtime\n # package if installed.\n if fscache.read(stub_typed_file).decode().strip() == \"partial\":\n runtime_path = os_path_join(pkg_dir, dir_chain)\n third_party_inline_dirs.append((runtime_path, True))\n # if the package is partial, we don't verify the module, as\n # the partial stub package may not have a __init__.pyi\n third_party_stubs_dirs.append((path, False))\n else:\n # handle the edge case where people put a py.typed file\n # in a stub package, but it isn't partial\n third_party_stubs_dirs.append((path, True))\n else:\n third_party_stubs_dirs.append((path, True))\n non_stub_match = self._find_module_non_stub_helper(components, pkg_dir)\n if isinstance(non_stub_match, ModuleNotFoundReason):\n if non_stub_match is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS:\n found_possible_third_party_missing_type_hints = True\n elif non_stub_match is ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED:\n need_installed_stubs = True\n else:\n third_party_inline_dirs.append(non_stub_match)\n self._update_ns_ancestors(components, non_stub_match)\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 if need_installed_stubs:\n return ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED\n elif found_possible_third_party_missing_type_hints:\n return ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS\n else:\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.lru_cache(maxsize=None)\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 reason = os.strerror(err.errno)\n raise CompileError(\n [f\"mypy: Invalid python executable '{python_executable}': {reason}\"]\n ) from err\n return sys_path, site_packages\n\n\ndef compute_search_paths(\n sources: list[BuildSource], options: Options, data_dir: str, alt_lib_path: str | None = None\n) -> SearchPaths:\n \"\"\"Compute the search paths as specified in PEP 561.\n\n There are the following 4 members created:\n - User code (from `sources`)\n - MYPYPATH (set either via config or environment variable)\n - installed package directories (which will later be split into stub-only and inline)\n - typeshed\n \"\"\"\n # Determine the default module search path.\n lib_path = collections.deque(\n default_lib_path(\n data_dir, options.python_version, custom_typeshed_dir=options.custom_typeshed_dir\n )\n )\n\n if options.use_builtins_fixtures:\n # Use stub builtins (to speed up test cases and to make them easier to\n # debug). This is a test-only feature, so assume our files are laid out\n # as in the source tree.\n # We also need to allow overriding where to look for it. Argh.\n root_dir = os.getenv(\"MYPY_TEST_PREFIX\", None)\n if not root_dir:\n root_dir = os.path.dirname(os.path.dirname(__file__))\n root_dir = os.path.abspath(root_dir)\n lib_path.appendleft(os.path.join(root_dir, \"test-data\", \"unit\", \"lib-stub\"))\n # alt_lib_path is used by some tests to bypass the normal lib_path mechanics.\n # If we don't have one, grab directories of source files.\n python_path: list[str] = []\n if not alt_lib_path:\n for source in sources:\n # Include directory of the program file in the module search path.\n if source.base_dir:\n dir = source.base_dir\n if dir not in python_path:\n python_path.append(dir)\n\n # Do this even if running as a file, for sanity (mainly because with\n # multiple builds, there could be a mix of files\/modules, so its easier\n # to just define the semantics that we always add the current director\n # to the lib_path\n # TODO: Don't do this in some cases; for motivation see see\n # https:\/\/github.com\/python\/mypy\/issues\/4195#issuecomment-341915031\n if options.bazel:\n dir = \".\"\n else:\n dir = os.getcwd()\n if dir not in lib_path:\n python_path.insert(0, dir)\n\n # Start with a MYPYPATH environment variable at the front of the mypy_path, if defined.\n mypypath = mypy_path()\n\n # Add a config-defined mypy path.\n mypypath.extend(options.mypy_path)\n\n # If provided, insert the caller-supplied extra module path to the\n # beginning (highest priority) of the search path.\n if alt_lib_path:\n mypypath.insert(0, alt_lib_path)\n\n sys_path, site_packages = get_search_dirs(options.python_executable)\n # We only use site packages for this check\n for site in site_packages:\n assert site not in lib_path\n if (\n site in mypypath\n or any(p.startswith(site + os.path.sep) for p in mypypath)\n or (os.path.altsep and any(p.startswith(site + os.path.altsep) for p in mypypath))\n ):\n print(f\"{site} is in the MYPYPATH. Please remove it.\", file=sys.stderr)\n print(\n \"See https:\/\/mypy.readthedocs.io\/en\/stable\/running_mypy.html\"\n \"#how-mypy-handles-imports for more info\",\n file=sys.stderr,\n )\n sys.exit(1)\n\n return SearchPaths(\n python_path=tuple(reversed(python_path)),\n mypy_path=tuple(mypypath),\n # package_path and typeshed_path must be normalised and absolute via os.path.abspath\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/modulefinder.py","language":"Python","license":"NOASSERTION","size":38192} {"code":"\"\"\"Basic introspection of modules.\"\"\"\n\nfrom __future__ import annotations\n\nimport importlib\nimport inspect\nimport os\nimport pkgutil\nimport queue\nimport sys\nfrom multiprocessing import Queue, get_context\nfrom types import ModuleType\n\n\nclass ModuleProperties:\n # Note that all __init__ args must have default values\n def __init__(\n self,\n name: str = \"\",\n file: str | None = None,\n path: list[str] | None = None,\n all: list[str] | None = None,\n is_c_module: bool = False,\n subpackages: list[str] | None = None,\n ) -> None:\n self.name = name # __name__ attribute\n self.file = file # __file__ attribute\n self.path = path # __path__ attribute\n self.all = all # __all__ attribute\n self.is_c_module = is_c_module\n self.subpackages = subpackages or []\n\n\ndef is_c_module(module: ModuleType) -> bool:\n if module.__dict__.get(\"__file__\") is None:\n # Could be a namespace package. These must be handled through\n # introspection, since there is no source file.\n return True\n return os.path.splitext(module.__dict__[\"__file__\"])[-1] in [\".so\", \".pyd\", \".dll\"]\n\n\ndef is_pyc_only(file: str | None) -> bool:\n return bool(file and file.endswith(\".pyc\") and not os.path.exists(file[:-1]))\n\n\nclass InspectError(Exception):\n pass\n\n\ndef get_package_properties(package_id: str) -> ModuleProperties:\n \"\"\"Use runtime introspection to get information about a module\/package.\"\"\"\n try:\n package = importlib.import_module(package_id)\n except BaseException as e:\n raise InspectError(str(e)) from e\n name = getattr(package, \"__name__\", package_id)\n file = getattr(package, \"__file__\", None)\n path: list[str] | None = getattr(package, \"__path__\", None)\n if not isinstance(path, list):\n path = None\n pkg_all = getattr(package, \"__all__\", None)\n if pkg_all is not None:\n try:\n pkg_all = list(pkg_all)\n except Exception:\n pkg_all = None\n is_c = is_c_module(package)\n\n if path is None:\n # Object has no path; this means it's either a module inside a package\n # (and thus no sub-packages), or it could be a C extension package.\n if is_c:\n # This is a C extension module, now get the list of all sub-packages\n # using the inspect module\n subpackages = [\n package.__name__ + \".\" + name\n for name, val in inspect.getmembers(package)\n if inspect.ismodule(val) and val.__name__ == package.__name__ + \".\" + name\n ]\n else:\n # It's a module inside a package. There's nothing else to walk\/yield.\n subpackages = []\n else:\n all_packages = pkgutil.walk_packages(\n path, prefix=package.__name__ + \".\", onerror=lambda r: None\n )\n subpackages = [qualified_name for importer, qualified_name, ispkg in all_packages]\n return ModuleProperties(\n name=name, file=file, path=path, all=pkg_all, is_c_module=is_c, subpackages=subpackages\n )\n\n\ndef worker(tasks: Queue[str], results: Queue[str | ModuleProperties], sys_path: list[str]) -> None:\n \"\"\"The main loop of a worker introspection process.\"\"\"\n sys.path = sys_path\n while True:\n mod = tasks.get()\n try:\n prop = get_package_properties(mod)\n except InspectError as e:\n results.put(str(e))\n continue\n results.put(prop)\n\n\nclass ModuleInspect:\n \"\"\"Perform runtime introspection of modules in a separate process.\n\n Reuse the process for multiple modules for efficiency. However, if there is an\n error, retry using a fresh process to avoid cross-contamination of state between\n modules.\n\n We use a separate process to isolate us from many side effects. For example, the\n import of a module may kill the current process, and we want to recover from that.\n\n Always use in a with statement for proper clean-up:\n\n with ModuleInspect() as m:\n p = m.get_package_properties('urllib.parse')\n \"\"\"\n\n def __init__(self) -> None:\n self._start()\n\n def _start(self) -> None:\n if sys.platform == \"linux\":\n ctx = get_context(\"forkserver\")\n else:\n ctx = get_context(\"spawn\")\n self.tasks: Queue[str] = ctx.Queue()\n self.results: Queue[ModuleProperties | str] = ctx.Queue()\n self.proc = ctx.Process(target=worker, args=(self.tasks, self.results, sys.path))\n self.proc.start()\n self.counter = 0 # Number of successful roundtrips\n\n def close(self) -> None:\n \"\"\"Free any resources used.\"\"\"\n self.proc.terminate()\n\n def get_package_properties(self, package_id: str) -> ModuleProperties:\n \"\"\"Return some properties of a module\/package using runtime introspection.\n\n Raise InspectError if the target couldn't be imported.\n \"\"\"\n self.tasks.put(package_id)\n res = self._get_from_queue()\n if res is None:\n # The process died; recover and report error.\n self._start()\n raise InspectError(f\"Process died when importing {package_id!r}\")\n if isinstance(res, str):\n # Error importing module\n if self.counter > 0:\n # Also try with a fresh process. Maybe one of the previous imports has\n # corrupted some global state.\n self.close()\n self._start()\n return self.get_package_properties(package_id)\n raise InspectError(res)\n self.counter += 1\n return res\n\n def _get_from_queue(self) -> ModuleProperties | str | None:\n \"\"\"Get value from the queue.\n\n Return the value read from the queue, or None if the process unexpectedly died.\n \"\"\"\n max_iter = 600\n n = 0\n while True:\n if n == max_iter:\n raise RuntimeError(\"Timeout waiting for subprocess\")\n try:\n return self.results.get(timeout=0.05)\n except queue.Empty:\n if not self.proc.is_alive():\n return None\n n += 1\n\n def __enter__(self) -> ModuleInspect:\n return self\n\n def __exit__(self, *args: object) -> None:\n self.close()\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/moduleinspect.py","language":"Python","license":"NOASSERTION","size":6326} {"code":"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/mro.py","language":"Python","license":"NOASSERTION","size":1993} {"code":"\"\"\"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 enum import Enum, unique\nfrom typing import (\n TYPE_CHECKING,\n Any,\n Callable,\n Dict,\n Final,\n Iterator,\n List,\n Optional,\n Sequence,\n Tuple,\n TypeVar,\n Union,\n cast,\n)\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 # 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# 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 return _nongen_builtins if python_version < (3, 9) else {}\n\n\nRUNTIME_PROTOCOL_DECOS: Final = (\n \"typing.runtime_checkable\",\n \"typing_extensions.runtime\",\n \"typing_extensions.runtime_checkable\",\n)\n\nLAMBDA_NAME: Final = \"\"\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\"]\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\")\n\n items: list[OverloadPart]\n unanalyzed_items: list[OverloadPart]\n impl: OverloadPart | 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 if items:\n # TODO: figure out how to reliably set end position (we don't know the impl here).\n self.set_line(items[0].line, items[0].column)\n\n @property\n def name(self) -> str:\n if self.items:\n return self.items[0].name\n else:\n # This may happen for malformed overload\n assert self.impl is not None\n return self.impl.name\n\n 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 }\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 # 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\")\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 ) -> None:\n self.name = name\n self.kind = kind\n self.upper_bound = upper_bound\n self.values = values\n\n\nFUNCITEM_FLAGS: Final = FUNCBASE_FLAGS + [\n \"is_overload\",\n \"is_generator\",\n \"is_coroutine\",\n \"is_async_generator\",\n \"is_awaitable_coroutine\",\n]\n\n\nclass FuncItem(FuncBase):\n \"\"\"Base class for nodes usable as overloaded function items.\"\"\"\n\n __slots__ = (\n \"arguments\", # Note that can be unset if deserialized (type is a lie!)\n \"arg_names\", # Names of arguments\n \"arg_kinds\", # Kinds of arguments\n \"min_args\", # Minimum number of arguments\n \"max_pos\", # Maximum number of positional arguments, -1 if no explicit\n # limit (*args not included)\n \"type_args\", # New-style type parameters (PEP 695)\n \"body\", # Body of the function\n \"is_overload\", # Is this an overload variant of function with more than\n # one overload variant?\n \"is_generator\", # Contains a yield statement?\n \"is_coroutine\", # Defined using 'async def' syntax?\n \"is_async_generator\", # Is an async def generator?\n \"is_awaitable_coroutine\", # Decorated with '@{typing,asyncio}.coroutine'?\n \"expanded\", # Variants of function with type variables with values expanded\n )\n\n __deletable__ = (\"arguments\", \"max_pos\", \"min_args\")\n\n def __init__(\n self,\n arguments: list[Argument] | None = None,\n body: Block | None = None,\n typ: mypy.types.FunctionLike | None = None,\n type_args: list[TypeParam] | None = None,\n ) -> None:\n super().__init__()\n self.arguments = arguments or []\n self.arg_names = [None if arg.pos_only else arg.variable.name for arg in self.arguments]\n self.arg_kinds: list[ArgKind] = [arg.kind for arg in self.arguments]\n self.max_pos: int = self.arg_kinds.count(ARG_POS) + self.arg_kinds.count(ARG_OPT)\n self.type_args: list[TypeParam] | None = type_args\n self.body: Block = body or Block([])\n self.type = typ\n self.unanalyzed_type = typ\n self.is_overload: bool = False\n self.is_generator: bool = False\n self.is_coroutine: bool = False\n self.is_async_generator: bool = False\n self.is_awaitable_coroutine: bool = False\n self.expanded: list[FuncItem] = []\n\n self.min_args = 0\n for i in range(len(self.arguments)):\n if self.arguments[i] is None and i < self.max_fixed_argc():\n self.min_args = i + 1\n\n def max_fixed_argc(self) -> int:\n return self.max_pos\n\n def is_dynamic(self) -> bool:\n return self.type is None\n\n\nFUNCDEF_FLAGS: Final = FUNCITEM_FLAGS + [\n \"is_decorated\",\n \"is_conditional\",\n \"is_trivial_body\",\n \"is_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 \"deco_line\",\n \"is_trivial_body\",\n \"is_mypy_only\",\n # Present only when a function is decorated with @typing.datasclass_transform or similar\n \"dataclass_transform_spec\",\n \"docstring\",\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 # Used for error reporting (to keep backward compatibility with pre-3.8)\n self.deco_line: int | None = 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\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 }\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 # 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 \"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 \"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 # 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 \"deco_line\",\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 # Used for error reporting (to keep backwad compatibility with pre-3.8)\n self.deco_line: int | None = None\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]) -> 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 = False\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\")\n\n __match_args__ = (\"expr\", \"body\", \"else_body\")\n\n expr: list[Expression]\n body: list[Block]\n else_body: Block | None\n\n def __init__(self, expr: list[Expression], body: list[Block], else_body: Block | None) -> None:\n super().__init__()\n self.expr = expr\n self.body = body\n self.else_body = else_body\n\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\")\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\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\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]]:\n return all(isinstance(item, StrExpr) for item in seq)\n\n\nclass BytesExpr(Expression):\n \"\"\"Bytes literal\"\"\"\n\n __slots__ = (\"value\",)\n\n __match_args__ = (\"value\",)\n\n # Note: we deliberately do NOT use bytes here because it ends up\n # unnecessarily complicating a lot of the result logic. For example,\n # we'd have to worry about converting the bytes into a format we can\n # easily serialize\/deserialize to and from JSON, would have to worry\n # about turning the bytes into a human-readable representation in\n # error messages...\n #\n # It's more convenient to just store the human-readable representation\n # from the very start.\n value: str\n\n def __init__(self, value: str) -> None:\n super().__init__()\n self.value = value\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_bytes_expr(self)\n\n\nclass FloatExpr(Expression):\n \"\"\"Float literal\"\"\"\n\n __slots__ = (\"value\",)\n\n __match_args__ = (\"value\",)\n\n value: float # 0.0 by default\n\n def __init__(self, value: float) -> None:\n super().__init__()\n self.value = value\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_float_expr(self)\n\n\nclass ComplexExpr(Expression):\n \"\"\"Complex literal\"\"\"\n\n __slots__ = (\"value\",)\n\n __match_args__ = (\"value\",)\n\n value: complex\n\n def __init__(self, value: complex) -> None:\n super().__init__()\n self.value = value\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_complex_expr(self)\n\n\nclass EllipsisExpr(Expression):\n \"\"\"Ellipsis (...)\"\"\"\n\n __slots__ = ()\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_ellipsis(self)\n\n\nclass StarExpr(Expression):\n \"\"\"Star expression\"\"\"\n\n __slots__ = (\"expr\", \"valid\")\n\n __match_args__ = (\"expr\", \"valid\")\n\n expr: Expression\n valid: bool\n\n def __init__(self, expr: Expression) -> None:\n super().__init__()\n self.expr = expr\n\n # Whether this starred expression is used in a tuple\/list and as lvalue\n self.valid = False\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_star_expr(self)\n\n\nclass RefExpr(Expression):\n \"\"\"Abstract base class for name-like constructs\"\"\"\n\n __slots__ = (\n \"kind\",\n \"node\",\n \"_fullname\",\n \"is_new_def\",\n \"is_inferred_def\",\n \"is_alias_rvalue\",\n \"type_guard\",\n \"type_is\",\n )\n\n def __init__(self) -> None:\n super().__init__()\n # LDEF\/GDEF\/MDEF\/... (None if not available)\n self.kind: int | None = None\n # Var, FuncDef or TypeInfo that describes this\n self.node: SymbolNode | None = None\n # Fully qualified name (or name if not global)\n self._fullname = \"\"\n # Does this define a new name?\n self.is_new_def = False\n # Does this define a new name with inferred type?\n #\n # For members, after semantic analysis, this does not take base\n # classes into consideration at all; the type checker deals with these.\n self.is_inferred_def = False\n # Is this expression appears as an rvalue of a valid type alias definition?\n self.is_alias_rvalue = False\n # Cache type guard from callable_type.type_guard\n self.type_guard: mypy.types.Type | None = None\n # And same for TypeIs\n self.type_is: mypy.types.Type | None = None\n\n @property\n def fullname(self) -> str:\n return self._fullname\n\n @fullname.setter\n def fullname(self, v: str) -> None:\n self._fullname = v\n\n\nclass NameExpr(RefExpr):\n \"\"\"Name expression\n\n This refers to a local name, global name or a module.\n \"\"\"\n\n __slots__ = (\"name\", \"is_special_form\")\n\n __match_args__ = (\"name\", \"node\")\n\n def __init__(self, name: str) -> None:\n super().__init__()\n self.name = name # Name referred to\n # Is this a l.h.s. of a special form assignment like typed dict or type variable?\n self.is_special_form = False\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_name_expr(self)\n\n def serialize(self) -> JsonDict:\n assert False, f\"Serializing NameExpr: {self}\"\n\n\nclass MemberExpr(RefExpr):\n \"\"\"Member access expression x.y\"\"\"\n\n __slots__ = (\"expr\", \"name\", \"def_var\")\n\n __match_args__ = (\"expr\", \"name\", \"node\")\n\n def __init__(self, expr: Expression, name: str) -> None:\n super().__init__()\n self.expr = expr\n self.name = name\n # The variable node related to a definition through 'self.x = '.\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\")\n\n __match_args__ = (\"callee\", \"args\", \"arg_kinds\", \"arg_names\")\n\n def __init__(\n self,\n callee: Expression,\n args: list[Expression],\n arg_kinds: list[ArgKind],\n arg_names: list[str | None],\n analyzed: Expression | None = None,\n ) -> None:\n super().__init__()\n if not arg_names:\n arg_names = [None] * len(args)\n\n self.callee = callee\n self.args = args\n self.arg_kinds = arg_kinds # ARG_ constants\n # Each name can be None if not a keyword argument.\n self.arg_names: list[str | None] = arg_names\n # If not None, the node that represents the meaning of the CallExpr. For\n # cast(...) this is a CastExpr.\n self.analyzed = analyzed\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_call_expr(self)\n\n\nclass YieldFromExpr(Expression):\n __slots__ = (\"expr\",)\n\n __match_args__ = (\"expr\",)\n\n expr: Expression\n\n def __init__(self, expr: Expression) -> None:\n super().__init__()\n self.expr = expr\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_yield_from_expr(self)\n\n\nclass YieldExpr(Expression):\n __slots__ = (\"expr\",)\n\n __match_args__ = (\"expr\",)\n\n expr: Expression | None\n\n def __init__(self, expr: Expression | None) -> None:\n super().__init__()\n self.expr = expr\n\n def accept(self, visitor: ExpressionVisitor[T]) -> T:\n return visitor.visit_yield_expr(self)\n\n\nclass IndexExpr(Expression):\n \"\"\"Index expression x[y].\n\n Also wraps type application such as List[int] as a special form.\n \"\"\"\n\n __slots__ = (\"base\", \"index\", \"method_type\", \"analyzed\")\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\")\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\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 )\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 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 ]\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\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 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\"\"\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 }\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 return ti\n\n\nclass FakeInfo(TypeInfo):\n __slots__ = (\"msg\",)\n\n # types.py defines a single instance of this class, called types.NOT_READY.\n # This instance is used as a temporary placeholder in the process of de-serialization\n # of 'Instance' types. The de-serialization happens in two steps: In the first step,\n # Instance.type is set to NOT_READY. In the second step (in fixup.py) it is replaced by\n # an actual TypeInfo. If you see the assertion error below, then most probably something\n # went wrong during the second step and an 'Instance' that raised this error was not fixed.\n # Note:\n # 'None' is not used as a dummy value for two reasons:\n # 1. This will require around 80-100 asserts to make 'mypy --strict-optional mypy'\n # pass cleanly.\n # 2. If NOT_READY value is accidentally used somewhere, it will be obvious where the value\n # is from, whereas a 'None' value could come from anywhere.\n #\n # Additionally, this serves as a more general-purpose placeholder\n # for missing TypeInfos in a number of places where the excuses\n # for not being Optional are a little weaker.\n #\n # TypeInfo defines a __bool__ method that returns False for FakeInfo\n # so that it can be conveniently tested against in the same way that it\n # would be if things were properly optional.\n def __init__(self, msg: str) -> None:\n self.msg = msg\n\n def __getattribute__(self, attr: str) -> type:\n # Handle __class__ so that isinstance still works...\n if attr == \"__class__\":\n return object.__getattribute__(self, attr) # type: ignore[no-any-return]\n raise AssertionError(object.__getattribute__(self, \"msg\"))\n\n\nVAR_NO_INFO: Final[TypeInfo] = FakeInfo(\"Var is lacking info\")\nCLASSDEF_NO_INFO: Final[TypeInfo] = FakeInfo(\"ClassDef is lacking info\")\nFUNC_NO_INFO: Final[TypeInfo] = FakeInfo(\"FuncBase for non-methods lack info\")\nMISSING_FALLBACK: Final = FakeInfo(\"fallback can't be filled out until semanal\")\n\n\nclass TypeAlias(SymbolNode):\n \"\"\"\n A symbol node representing a type alias.\n\n Type alias is a static concept, in contrast to variables with types\n like Type[...]. Namely:\n * type aliases\n - can be used in type context (annotations)\n - cannot be re-assigned\n * variables with type Type[...]\n - cannot be used in type context\n - but can be re-assigned\n\n An alias can be defined only by an assignment to a name (not any other lvalues).\n\n Such assignment defines an alias by default. To define a variable,\n an explicit Type[...] annotation is required. As an exception,\n at non-global scope non-subscripted rvalue creates a variable even without\n an annotation. This exception exists to accommodate the common use case of\n class-valued attributes. See SemanticAnalyzerPass2.check_and_set_up_type_alias\n for details.\n\n Aliases can be generic. We use bound type variables for generic aliases, similar\n to classes. Essentially, type aliases work as macros that expand textually.\n The definition and expansion rules are following:\n\n 1. An alias targeting a generic class without explicit variables act as\n the given class (this doesn't apply to TypedDict, Tuple and Callable, which\n are not proper classes but special type constructors):\n\n A = List\n AA = List[Any]\n\n x: A # same as List[Any]\n x: A[int] # same as List[int]\n\n x: AA # same as List[Any]\n x: AA[int] # Error!\n\n C = Callable # Same as Callable[..., Any]\n T = Tuple # Same as Tuple[Any, ...]\n\n 2. An alias using explicit type variables in its rvalue expects\n replacements (type arguments) for these variables. If missing, they\n are treated as Any, like for other generics:\n\n B = List[Tuple[T, T]]\n\n x: B # same as List[Tuple[Any, Any]]\n x: B[int] # same as List[Tuple[int, int]]\n\n def f(x: B[T]) -> T: ... # without T, Any would be used here\n\n 3. An alias can be defined using another aliases. In the definition\n rvalue the Any substitution doesn't happen for top level unsubscripted\n generic classes:\n\n A = List\n B = A # here A is expanded to List, _not_ List[Any],\n # to match the Python runtime behaviour\n x: B[int] # same as List[int]\n C = List[A] # this expands to List[List[Any]]\n\n AA = List[T]\n D = AA # here AA expands to List[Any]\n x: D[int] # Error!\n\n Note: the fact that we support aliases like `A = List` means that the target\n type will be initially an instance type with wrong number of type arguments.\n Such instances are all fixed either during or after main semantic analysis passes.\n We therefore store the difference between `List` and `List[Any]` rvalues (targets)\n using the `no_args` flag. See also TypeAliasExpr.no_args.\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 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(\" \")\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(node: SymbolNode | None) -> bool:\n \"\"\"Check whether `node` corresponds to a final attribute.\"\"\"\n return isinstance(node, (Var, FuncDef, OverloadedFuncDef, Decorator)) and node.is_final\n\n\ndef 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/nodes.py","language":"Python","license":"NOASSERTION","size":137130} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/operators.py","language":"Python","license":"NOASSERTION","size":2866} {"code":"from __future__ import annotations\n\nimport pprint\nimport re\nimport sys\nimport sysconfig\nfrom typing import Any, Callable, Final, Mapping, Pattern\n\nfrom mypy import defaults\nfrom mypy.errorcodes import ErrorCode, error_codes\nfrom mypy.util import get_class_descriptors, replace_object_state\n\n\nclass BuildType:\n STANDARD: Final = 0\n MODULE: Final = 1\n PROGRAM_TEXT: Final = 2\n\n\nPER_MODULE_OPTIONS: Final = {\n # Please keep this list sorted\n \"allow_redefinition\",\n \"allow_untyped_globals\",\n \"always_false\",\n \"always_true\",\n \"check_untyped_defs\",\n \"debug_cache\",\n \"disable_error_code\",\n \"disabled_error_codes\",\n \"disallow_any_decorated\",\n \"disallow_any_explicit\",\n \"disallow_any_expr\",\n \"disallow_any_generics\",\n \"disallow_any_unimported\",\n \"disallow_incomplete_defs\",\n \"disallow_subclassing_any\",\n \"disallow_untyped_calls\",\n \"disallow_untyped_decorators\",\n \"disallow_untyped_defs\",\n \"enable_error_code\",\n \"enabled_error_codes\",\n \"extra_checks\",\n \"follow_imports_for_stubs\",\n \"follow_imports\",\n \"ignore_errors\",\n \"ignore_missing_imports\",\n \"implicit_optional\",\n \"implicit_reexport\",\n \"local_partial_types\",\n \"mypyc\",\n \"strict_concatenate\",\n \"strict_equality\",\n \"strict_optional\",\n \"warn_no_return\",\n \"warn_return_any\",\n \"warn_unreachable\",\n \"warn_unused_ignores\",\n}\n\nOPTIONS_AFFECTING_CACHE: Final = (\n PER_MODULE_OPTIONS\n | {\n \"platform\",\n \"bazel\",\n \"old_type_inference\",\n \"plugins\",\n \"disable_bytearray_promotion\",\n \"disable_memoryview_promotion\",\n }\n) - {\"debug_cache\"}\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 # Cache for clone_for_module()\n self._per_module_cache: dict[str, Options] | None = None\n\n # -- build options --\n self.build_type = BuildType.STANDARD\n self.python_version: tuple[int, int] = sys.version_info[:2]\n # The executable used to search for PEP 561 packages. If this is None,\n # then mypy does not search for PEP 561 packages.\n self.python_executable: str | None = sys.executable\n\n # When cross compiling to emscripten, we need to rely on MACHDEP because\n # sys.platform is the host build platform, not emscripten.\n MACHDEP = sysconfig.get_config_var(\"MACHDEP\")\n if MACHDEP == \"emscripten\":\n self.platform = MACHDEP\n else:\n self.platform = sys.platform\n\n self.custom_typing_module: str | None = None\n self.custom_typeshed_dir: str | None = None\n # The abspath() version of the above, we compute it once as an optimization.\n self.abs_custom_typeshed_dir: str | None = None\n self.mypy_path: list[str] = []\n self.report_dirs: dict[str, str] = {}\n # Show errors in PEP 561 packages\/site-packages modules\n self.no_silence_site_packages = False\n self.no_site_packages = False\n self.ignore_missing_imports = False\n # Is ignore_missing_imports set in a per-module section\n self.ignore_missing_imports_per_module = False\n 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 # disallow_any options\n self.disallow_any_generics = False\n self.disallow_any_unimported = False\n self.disallow_any_expr = False\n self.disallow_any_decorated = False\n self.disallow_any_explicit = False\n\n # Disallow calling untyped functions from typed ones\n self.disallow_untyped_calls = False\n\n # Always allow untyped calls for function coming from modules\/packages\n # in this list (each item effectively acts as a prefix match)\n self.untyped_calls_exclude: list[str] = []\n\n # Disallow defining untyped (or incompletely typed) functions\n self.disallow_untyped_defs = False\n\n # Disallow defining incompletely typed functions\n self.disallow_incomplete_defs = False\n\n # Type check unannotated functions\n self.check_untyped_defs = False\n\n # Disallow decorating typed functions with untyped decorators\n self.disallow_untyped_decorators = False\n\n # Disallow subclassing values of type 'Any'\n self.disallow_subclassing_any = False\n\n # Also check typeshed for missing annotations\n self.warn_incomplete_stub = False\n\n # Warn about casting an expression to its inferred type\n self.warn_redundant_casts = False\n\n # Warn about falling off the end of a function returning non-None\n self.warn_no_return = True\n\n # Warn about returning objects of type Any when the function is\n # declared with a precise type\n self.warn_return_any = False\n\n # Warn about unused '# type: ignore' comments\n self.warn_unused_ignores = False\n\n # Warn about unused '[mypy-]' or '[[tool.mypy.overrides]]' config sections\n self.warn_unused_configs = False\n\n # Files in which to ignore all non-fatal errors\n self.ignore_errors = False\n\n # Apply strict None checking\n self.strict_optional = True\n\n # Show \"note: In function \"foo\":\" messages.\n self.show_error_context = False\n\n # Use nicer output (when possible).\n self.color_output = True\n self.error_summary = True\n\n # Assume arguments with default values of None are Optional\n self.implicit_optional = False\n\n # Don't re-export names unless they are imported with `from ... as ...`\n self.implicit_reexport = True\n\n # Suppress toplevel errors caused by missing annotations\n self.allow_untyped_globals = False\n\n # Allow variable to be redefined with an arbitrary type in the same block\n # and the same nesting level as the initialization\n self.allow_redefinition = False\n\n # Prohibit equality, identity, and container checks for non-overlapping types.\n # This makes 1 == '1', 1 in ['1'], and 1 is '1' errors.\n self.strict_equality = False\n\n # Deprecated, use extra_checks instead.\n self.strict_concatenate = False\n\n # Enable additional checks that are technically correct but impractical.\n self.extra_checks = False\n\n # Report an error for any branches inferred to be unreachable as a result of\n # type analysis.\n self.warn_unreachable = False\n\n # Variable names considered True\n self.always_true: list[str] = []\n\n # Variable names considered False\n self.always_false: list[str] = []\n\n # Error codes to disable\n self.disable_error_code: list[str] = []\n self.disabled_error_codes: set[ErrorCode] = set()\n\n # Error codes to enable\n self.enable_error_code: list[str] = []\n self.enabled_error_codes: set[ErrorCode] = set()\n\n # Use script name instead of __main__\n self.scripts_are_modules = False\n\n # Config file name\n self.config_file: str | None = None\n\n # A filename containing a JSON mapping from filenames to\n # mtime\/size\/hash arrays, used to avoid having to recalculate\n # source hashes as often.\n self.quickstart_file: str | None = None\n\n # A comma-separated list of files\/directories for mypy to type check;\n # supports globbing\n self.files: list[str] | None = None\n\n # A list of packages for mypy to type check\n self.packages: list[str] | None = None\n\n # A list of modules for mypy to type check\n self.modules: list[str] | None = None\n\n # Write junit.xml to given file\n self.junit_xml: str | None = None\n\n self.junit_format: str = \"global\" # global|per_file\n\n # Caching and incremental checking options\n self.incremental = True\n self.cache_dir = defaults.CACHE_DIR\n self.sqlite_cache = 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 = False\n self.show_error_end: bool = False\n self.hide_error_codes = False\n self.show_error_code_links = False\n # Use soft word wrap and show trimmed source snippets with error location markers.\n self.pretty = False\n self.dump_graph = False\n self.dump_deps = False\n self.logical_deps = False\n # If True, partial types can't span a module top level and a function\n self.local_partial_types = False\n # 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 = False\n self.disable_memoryview_promotion = False\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):\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 new_semantic_analyzer\n @property\n def new_semantic_analyzer(self) -> bool:\n return True\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) and k != \"new_semantic_analyzer\":\n d[k] = getattr(self, k)\n # Remove private attributes from snapshot\n d = {k: v for k, v in d.items() if not k.startswith(\"_\")}\n return d\n\n def __repr__(self) -> str:\n return f\"Options({pprint.pformat(self.snapshot())})\"\n\n def process_error_codes(self, *, error_callback: Callable[[str], Any]) -> None:\n # Process `--enable-error-code` and `--disable-error-code` flags\n disabled_codes = set(self.disable_error_code)\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 return self._per_module_cache[module]\n\n # If not, search for glob paths at all the parents. So if we are looking for\n # options for foo.bar.baz, we search foo.bar.baz.*, foo.bar.*, foo.*,\n # in that order, looking for an entry.\n # This is technically quadratic in the length of the path, but module paths\n # don't actually get all that long.\n options = self\n path = module.split(\".\")\n for i in range(len(path), 0, -1):\n key = \".\".join(path[:i] + [\"*\"])\n if key in self._per_module_cache:\n self.unused_configs.discard(key)\n options = self._per_module_cache[key]\n break\n\n # OK and *now* we need to look for unstructured glob matches.\n # We only do this for concrete modules, not structured wildcards.\n if not module.endswith(\".*\"):\n for key, pattern in self._glob_options:\n if pattern.match(module):\n self.unused_configs.discard(key)\n options = options.apply_changes(self.per_module_options[key])\n\n # We could update the cache to directly point to modules once\n # they have been looked up, but in testing this made things\n # slower and not faster, so we don't bother.\n\n return options\n\n def compile_glob(self, s: str) -> Pattern[str]:\n # Compile one of the glob patterns to a regex so that '.*' can\n # match *zero or more* module sections. This means we compile\n # '.*' into '(\\..*)?'.\n parts = s.split(\".\")\n expr = re.escape(parts[0]) if parts[0] != \"*\" else \".*\"\n for part in parts[1:]:\n expr += re.escape(\".\" + part) if part != \"*\" else r\"(\\..*)?\"\n return re.compile(expr + \"\\\\Z\")\n\n def select_options_affecting_cache(self) -> 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/options.py","language":"Python","license":"NOASSERTION","size":24365} {"code":"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/parse.py","language":"Python","license":"NOASSERTION","size":913} {"code":"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/partially_defined.py","language":"Python","license":"NOASSERTION","size":25562} {"code":"\"\"\"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 as \"\"\"\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 | | ...\"\"\"\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 [, ...]\"\"\"\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/patterns.py","language":"Python","license":"NOASSERTION","size":4048} {"code":"\"\"\"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\nYou can use `api.options.new_semantic_analyzer` to check whether the new\nsemantic analyzer is enabled (it's always true in mypy 0.730 and later).\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, name: 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 t: Type,\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, name: 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, name: 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, stnode: 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, n: 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 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/plugin.py","language":"Python","license":"NOASSERTION","size":35404} {"code":"","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/plugins\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"\"\"\"Plugin for supporting the attrs library (http:\/\/www.attrs.org)\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections import defaultdict\nfrom functools import reduce\nfrom typing import Final, Iterable, List, Mapping, cast\nfrom typing_extensions import Literal\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: Type | None = None\n if isinstance(converter_expr, RefExpr) and converter_expr.node:\n if isinstance(converter_expr.node, FuncDef):\n if converter_expr.node.type and isinstance(converter_expr.node.type, FunctionLike):\n converter_type = converter_expr.node.type\n else: # The converter is an unannotated function.\n converter_info.init_type = AnyType(TypeOfAny.unannotated)\n return converter_info\n elif isinstance(converter_expr.node, OverloadedFuncDef) and is_valid_overloaded_converter(\n converter_expr.node\n ):\n converter_type = converter_expr.node.type\n elif isinstance(converter_expr.node, TypeInfo):\n 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 (self, ) -> ): ... to info.\n\n self_type: The type to use for the self argument or None to use the inferred self type.\n tvd: If the method is generic these should be the type variables.\n \"\"\"\n self_type = self_type if self_type is not None else self.self_type\n add_method_to_class(\n self.ctx.api, self.ctx.cls, method_name, args, ret_type, self_type, tvd\n )\n\n\ndef _get_attrs_init_type(typ: Instance) -> CallableType | None:\n \"\"\"\n If `typ` refers to an attrs class, get the type of its initializer method.\n \"\"\"\n magic_attr = typ.type.get(MAGIC_ATTR_NAME)\n if magic_attr is None or not magic_attr.plugin_generated:\n return None\n init_method = typ.type.get_method(\"__init__\") or typ.type.get_method(ATTRS_INIT_NAME)\n if not isinstance(init_method, FuncDef) or not isinstance(init_method.type, CallableType):\n return None\n return init_method.type\n\n\ndef _fail_not_attrs_class(ctx: mypy.plugin.FunctionSigContext, t: Type, parent_t: Type) -> None:\n t_name = format_type_bare(t, ctx.api.options)\n if parent_t is t:\n msg = (\n f'Argument 1 to \"evolve\" has a variable type \"{t_name}\" not bound to an attrs class'\n if isinstance(t, TypeVarType)\n else f'Argument 1 to \"evolve\" has incompatible type \"{t_name}\"; expected an attrs class'\n )\n else:\n pt_name = format_type_bare(parent_t, ctx.api.options)\n msg = (\n f'Argument 1 to \"evolve\" has type \"{pt_name}\" whose item \"{t_name}\" is not bound to an attrs class'\n if isinstance(t, TypeVarType)\n else f'Argument 1 to \"evolve\" has incompatible type \"{pt_name}\" whose item \"{t_name}\" is not an attrs class'\n )\n\n ctx.api.fail(msg, ctx.context)\n\n\ndef _get_expanded_attr_types(\n ctx: mypy.plugin.FunctionSigContext,\n typ: ProperType,\n display_typ: ProperType,\n parent_typ: ProperType,\n) -> list[Mapping[str, Type]] | None:\n \"\"\"\n For a given type, determine what attrs classes it can be: for each class, return the field types.\n For generic classes, the field types are expanded.\n If the type contains Any or a non-attrs type, returns None; in the latter case, also reports an error.\n \"\"\"\n if isinstance(typ, AnyType):\n return None\n elif isinstance(typ, UnionType):\n ret: list[Mapping[str, Type]] | None = []\n for item in typ.relevant_items():\n item = get_proper_type(item)\n item_types = _get_expanded_attr_types(ctx, item, item, parent_typ)\n if ret is not None and item_types is not None:\n ret += item_types\n else:\n ret = None # but keep iterating to emit all errors\n return ret\n elif isinstance(typ, TypeVarType):\n return _get_expanded_attr_types(\n ctx, get_proper_type(typ.upper_bound), display_typ, parent_typ\n )\n elif isinstance(typ, Instance):\n init_func = _get_attrs_init_type(typ)\n if init_func is None:\n _fail_not_attrs_class(ctx, display_typ, parent_typ)\n return None\n init_func = expand_type_by_instance(init_func, typ)\n # [1:] to skip the self argument of AttrClass.__init__\n field_names = cast(List[str], init_func.arg_names[1:])\n field_types = init_func.arg_types[1:]\n return [dict(zip(field_names, field_types))]\n else:\n _fail_not_attrs_class(ctx, display_typ, parent_typ)\n return None\n\n\ndef _meet_fields(types: list[Mapping[str, Type]]) -> Mapping[str, Type]:\n \"\"\"\n \"Meet\" the fields of a list of attrs classes, i.e. for each field, its new type will be the lower bound.\n \"\"\"\n field_to_types = defaultdict(list)\n for fields in types:\n for name, typ in fields.items():\n field_to_types[name].append(typ)\n\n return {\n name: (\n get_proper_type(reduce(meet_types, f_types))\n if len(f_types) == len(types)\n else UninhabitedType()\n )\n for name, f_types in field_to_types.items()\n }\n\n\ndef evolve_function_sig_callback(ctx: mypy.plugin.FunctionSigContext) -> CallableType:\n \"\"\"\n Generate a signature for the 'attr.evolve' function that's specific to the call site\n and dependent on the type of the first argument.\n \"\"\"\n if len(ctx.args) != 2:\n # Ideally the name and context should be callee's, but we don't have it in FunctionSigContext.\n ctx.api.fail(f'\"{ctx.default_signature.name}\" has unexpected type annotation', ctx.context)\n return ctx.default_signature\n\n if len(ctx.args[0]) != 1:\n return ctx.default_signature # leave it to the type checker to complain\n\n inst_arg = ctx.args[0][0]\n inst_type = get_proper_type(ctx.api.get_expression_type(inst_arg))\n inst_type_str = format_type_bare(inst_type, ctx.api.options)\n\n attr_types = _get_expanded_attr_types(ctx, inst_type, inst_type, inst_type)\n if attr_types is None:\n return ctx.default_signature\n fields = _meet_fields(attr_types)\n\n return CallableType(\n arg_names=[\"inst\", *fields.keys()],\n arg_kinds=[ARG_POS] + [ARG_NAMED_OPT] * len(fields),\n arg_types=[inst_type, *fields.values()],\n ret_type=inst_type,\n fallback=ctx.default_signature.fallback,\n name=f\"{ctx.default_signature.name} of {inst_type_str}\",\n )\n\n\ndef fields_function_sig_callback(ctx: mypy.plugin.FunctionSigContext) -> CallableType:\n \"\"\"Provide the signature for `attrs.fields`.\"\"\"\n if len(ctx.args) != 1 or len(ctx.args[0]) != 1:\n return ctx.default_signature\n\n proper_type = get_proper_type(ctx.api.get_expression_type(ctx.args[0][0]))\n\n # fields(Any) -> Any, fields(type[Any]) -> Any\n if (\n isinstance(proper_type, AnyType)\n or isinstance(proper_type, TypeType)\n and isinstance(proper_type.item, AnyType)\n ):\n return ctx.default_signature\n\n cls = None\n arg_types = ctx.default_signature.arg_types\n\n if isinstance(proper_type, TypeVarType):\n inner = get_proper_type(proper_type.upper_bound)\n if isinstance(inner, Instance):\n # We need to work arg_types to compensate for the attrs stubs.\n arg_types = [proper_type]\n cls = inner.type\n elif isinstance(proper_type, CallableType):\n cls = proper_type.type_object()\n\n if cls is not None and MAGIC_ATTR_NAME in cls.names:\n # This is a proper attrs class.\n ret_type = cls.names[MAGIC_ATTR_NAME].type\n assert ret_type is not None\n return ctx.default_signature.copy_modified(arg_types=arg_types, ret_type=ret_type)\n\n return ctx.default_signature\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/plugins\/attrs.py","language":"Python","license":"NOASSERTION","size":46535} {"code":"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 syntatic 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 func.deco_line = func.line\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/plugins\/common.py","language":"Python","license":"NOASSERTION","size":14148} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/plugins\/ctypes.py","language":"Python","license":"NOASSERTION","size":10675} {"code":"\"\"\"Plugin that provides support for dataclasses.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Final, Iterator, Literal\n\nfrom mypy import errorcodes, message_registry\nfrom mypy.expandtype import expand_type, expand_type_by_instance\nfrom mypy.meet import meet_types\nfrom mypy.messages import format_type_bare\nfrom mypy.nodes import (\n ARG_NAMED,\n ARG_NAMED_OPT,\n ARG_OPT,\n ARG_POS,\n ARG_STAR,\n ARG_STAR2,\n MDEF,\n Argument,\n AssignmentStmt,\n Block,\n CallExpr,\n ClassDef,\n Context,\n DataclassTransformSpec,\n Decorator,\n EllipsisExpr,\n Expression,\n FuncDef,\n FuncItem,\n IfStmt,\n JsonDict,\n NameExpr,\n Node,\n PlaceholderNode,\n RefExpr,\n Statement,\n SymbolTableNode,\n TempNode,\n TypeAlias,\n TypeInfo,\n TypeVarExpr,\n Var,\n)\nfrom mypy.plugin import ClassDefContext, FunctionSigContext, SemanticAnalyzerPluginInterface\nfrom mypy.plugins.common import (\n _get_callee_type,\n _get_decorator_bool_argument,\n add_attribute_to_class,\n add_method_to_class,\n deserialize_and_fixup_type,\n)\nfrom mypy.semanal_shared import find_dataclass_transform_spec, require_bool_literal_argument\nfrom mypy.server.trigger import make_wildcard_trigger\nfrom mypy.state import state\nfrom mypy.typeops import map_type_from_supertype, try_getting_literals_from_type\nfrom mypy.types import (\n AnyType,\n CallableType,\n FunctionLike,\n Instance,\n LiteralType,\n NoneType,\n ProperType,\n TupleType,\n Type,\n TypeOfAny,\n TypeVarId,\n TypeVarType,\n UninhabitedType,\n UnionType,\n get_proper_type,\n)\nfrom mypy.typevars import fill_typevars\n\nif TYPE_CHECKING:\n from mypy.checker import TypeChecker\n\n# The set of decorators that generate dataclasses.\ndataclass_makers: Final = {\"dataclass\", \"dataclasses.dataclass\"}\n\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=(\"dataclasses.Field\", \"dataclasses.field\"),\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 = [attr.to_argument(self._cls.info, of=\"replace\") for attr in attributes]\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\" '\n \"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: list[CallableType] | None = []\n for item in typ.relevant_items():\n item = get_proper_type(item)\n item_types = _get_expanded_dataclasses_fields(ctx, item, item, parent_typ)\n if ret is not None and item_types is not None:\n ret += item_types\n else:\n ret = None # but keep iterating to emit all errors\n return ret\n elif isinstance(typ, TypeVarType):\n return _get_expanded_dataclasses_fields(\n ctx, get_proper_type(typ.upper_bound), display_typ, parent_typ\n )\n elif isinstance(typ, Instance):\n replace_sym = typ.type.get_method(_INTERNAL_REPLACE_SYM_NAME)\n if replace_sym is None:\n return None\n replace_sig = replace_sym.type\n assert isinstance(replace_sig, ProperType)\n assert isinstance(replace_sig, CallableType)\n return [expand_type_by_instance(replace_sig, typ)]\n else:\n return None\n\n\n# TODO: we can potentially get the function signature hook to allow returning a union\n# and leave this to the regular machinery of resolving a union of callables\n# (https:\/\/github.com\/python\/mypy\/issues\/15457)\ndef _meet_replace_sigs(sigs: list[CallableType]) -> CallableType:\n \"\"\"\n Produces the lowest bound of the 'replace' signatures of multiple dataclasses.\n \"\"\"\n args = {\n name: (typ, kind)\n for name, typ, kind in zip(sigs[0].arg_names, sigs[0].arg_types, sigs[0].arg_kinds)\n }\n\n for sig in sigs[1:]:\n sig_args = {\n name: (typ, kind)\n for name, typ, kind in zip(sig.arg_names, sig.arg_types, sig.arg_kinds)\n }\n for name in (*args.keys(), *sig_args.keys()):\n sig_typ, sig_kind = args.get(name, (UninhabitedType(), ARG_NAMED_OPT))\n sig2_typ, sig2_kind = sig_args.get(name, (UninhabitedType(), ARG_NAMED_OPT))\n args[name] = (\n meet_types(sig_typ, sig2_typ),\n ARG_NAMED_OPT if sig_kind == sig2_kind == ARG_NAMED_OPT else ARG_NAMED,\n )\n\n return sigs[0].copy_modified(\n arg_names=list(args.keys()),\n arg_types=[typ for typ, _ in args.values()],\n arg_kinds=[kind for _, kind in args.values()],\n )\n\n\ndef replace_function_sig_callback(ctx: FunctionSigContext) -> CallableType:\n \"\"\"\n Returns a signature for the 'dataclasses.replace' function that's dependent on the type\n of the first positional argument.\n \"\"\"\n if len(ctx.args) != 2:\n # Ideally the name and context should be callee's, but we don't have it in FunctionSigContext.\n ctx.api.fail(f'\"{ctx.default_signature.name}\" has unexpected type annotation', ctx.context)\n return ctx.default_signature\n\n if len(ctx.args[0]) != 1:\n return ctx.default_signature # leave it to the type checker to complain\n\n obj_arg = ctx.args[0][0]\n obj_type = get_proper_type(ctx.api.get_expression_type(obj_arg))\n inst_type_str = format_type_bare(obj_type, ctx.api.options)\n\n replace_sigs = _get_expanded_dataclasses_fields(ctx, obj_type, obj_type, obj_type)\n if replace_sigs is None:\n return ctx.default_signature\n replace_sig = _meet_replace_sigs(replace_sigs)\n\n return replace_sig.copy_modified(\n arg_names=[None, *replace_sig.arg_names],\n arg_kinds=[ARG_POS, *replace_sig.arg_kinds],\n arg_types=[obj_type, *replace_sig.arg_types],\n ret_type=obj_type,\n fallback=ctx.default_signature.fallback,\n name=f\"{ctx.default_signature.name} of {inst_type_str}\",\n )\n\n\ndef is_processed_dataclass(info: TypeInfo) -> bool:\n return bool(info) and \"dataclass\" in info.metadata\n\n\ndef check_post_init(api: TypeChecker, defn: FuncItem, info: TypeInfo) -> None:\n if defn.type is None:\n return\n assert isinstance(defn.type, FunctionLike)\n\n ideal_sig_method = info.get_method(_INTERNAL_POST_INIT_SYM_NAME)\n assert ideal_sig_method is not None and ideal_sig_method.type is not None\n ideal_sig = ideal_sig_method.type\n assert isinstance(ideal_sig, ProperType) # we set it ourselves\n assert isinstance(ideal_sig, CallableType)\n ideal_sig = ideal_sig.copy_modified(name=\"__post_init__\")\n\n api.check_override(\n override=defn.type,\n original=ideal_sig,\n name=\"__post_init__\",\n name_in_super=\"__post_init__\",\n supertype=\"dataclass\",\n original_class_or_static=False,\n override_class_or_static=False,\n node=defn,\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/plugins\/dataclasses.py","language":"Python","license":"NOASSERTION","size":46716} {"code":"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, 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 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\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 return None\n\n def get_method_signature_hook(\n self, fullname: str\n ) -> Callable[[MethodSigContext], FunctionLike] | None:\n from mypy.plugins import ctypes, 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\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, 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 == \"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 keys = try_getting_str_literals(ctx.args[0][0], ctx.arg_types[0][0])\n if keys is None:\n ctx.api.fail(\n message_registry.TYPEDDICT_KEY_MUST_BE_STRING_LITERAL,\n ctx.context,\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, ctx.context)\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, ctx.context)\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 keys = try_getting_str_literals(ctx.args[0][0], ctx.arg_types[0][0])\n if keys is None:\n ctx.api.fail(\n message_registry.TYPEDDICT_KEY_MUST_BE_STRING_LITERAL,\n ctx.context,\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=ctx.context)\n\n default_type = ctx.arg_types[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, ctx.context)\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, ctx.context\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 keys = try_getting_str_literals(ctx.args[0][0], ctx.arg_types[0][0])\n if keys is None:\n ctx.api.fail(\n message_registry.TYPEDDICT_KEY_MUST_BE_STRING_LITERAL,\n ctx.context,\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, ctx.context)\n elif key not in ctx.type.items:\n ctx.api.msg.typeddict_key_not_found(ctx.type, key, ctx.context)\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/plugins\/default.py","language":"Python","license":"NOASSERTION","size":22464} {"code":"\"\"\"\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 typing import Final, Iterable, Sequence, 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 infered 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/plugins\/enums.py","language":"Python","license":"NOASSERTION","size":11338} {"code":"\"\"\"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, 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 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 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 )\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 )\n\n ret = ctx.api.named_generic_type(PARTIAL, [ret_type])\n ret = ret.copy_with_extra_attr(\"__mypy_partial\", partially_applied)\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 partial_type = ctx.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 return result[0]\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/plugins\/functools.py","language":"Python","license":"NOASSERTION","size":13074} {"code":"\"\"\"\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/plugins\/proper_plugin.py","language":"Python","license":"NOASSERTION","size":6481} {"code":"from __future__ import annotations\n\nfrom typing import Final, NamedTuple, Sequence, 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/plugins\/singledispatch.py","language":"Python","license":"NOASSERTION","size":8446} {"code":"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.8+ 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.8. This file is run each mypy run, so it should be kept\nas fast as possible.\n\"\"\"\nimport sys\n\nif __name__ == \"__main__\":\n # HACK: We don't want to pick up mypy.types as the top-level types\n # module. This could happen if this file is run as a script.\n # This workaround fixes this for Python versions before 3.11.\n if sys.version_info < (3, 11):\n old_sys_path = sys.path\n sys.path = sys.path[1:]\n import types # noqa: F401\n\n sys.path = old_sys_path\n\nimport os\nimport site\nimport sysconfig\n\n\ndef getsitepackages() -> list[str]:\n res = []\n if hasattr(site, \"getsitepackages\"):\n res.extend(site.getsitepackages())\n\n if hasattr(site, \"getusersitepackages\") and site.ENABLE_USER_SITE:\n res.insert(0, site.getusersitepackages())\n else:\n res = [sysconfig.get_paths()[\"purelib\"]]\n return res\n\n\ndef getsyspath() -> list[str]:\n # Do not include things from the standard library\n # because those should come from typeshed.\n stdlib_zip = os.path.join(\n sys.base_exec_prefix,\n getattr(sys, \"platlibdir\", \"lib\"),\n f\"python{sys.version_info.major}{sys.version_info.minor}.zip\",\n )\n stdlib = sysconfig.get_path(\"stdlib\")\n stdlib_ext = os.path.join(stdlib, \"lib-dynload\")\n excludes = {stdlib_zip, stdlib, stdlib_ext}\n\n # Drop the first entry of sys.path\n # - If pyinfo.py is executed as a script (in a subprocess), this is the directory\n # containing pyinfo.py\n # - Otherwise, if mypy launched via console script, this is the directory of the script\n # - Otherwise, if mypy launched via python -m mypy, this is the current directory\n # In all these cases, it is desirable to drop the first entry\n # Note that mypy adds the cwd to SearchPaths.python_path, so we still find things on the\n # cwd consistently (the return value here sets SearchPaths.package_path)\n\n # Python 3.11 adds a \"safe_path\" flag wherein Python won't automatically prepend\n # anything to sys.path. In this case, the first entry of sys.path is no longer special.\n offset = 0 if sys.version_info >= (3, 11) and sys.flags.safe_path else 1\n\n abs_sys_path = (os.path.abspath(p) for p in sys.path[offset:])\n return [p for p in abs_sys_path if p not in excludes]\n\n\ndef getsearchdirs() -> tuple[list[str], list[str]]:\n return (getsyspath(), getsitepackages())\n\n\nif __name__ == \"__main__\":\n sys.stdout.reconfigure(encoding=\"utf-8\") # type: ignore[union-attr]\n if sys.argv[-1] == \"getsearchdirs\":\n print(repr(getsearchdirs()))\n else:\n print(\"ERROR: incorrect argument to pyinfo.py.\", file=sys.stderr)\n sys.exit(1)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/pyinfo.py","language":"Python","license":"NOASSERTION","size":3014} {"code":"\"\"\"Utilities related to determining the reachability of code (in semantic analysis).\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Final, Tuple, TypeVar\n\nfrom mypy.literals import literal\nfrom mypy.nodes import (\n LITERAL_YES,\n AssertStmt,\n Block,\n CallExpr,\n ComparisonExpr,\n Expression,\n FuncDef,\n IfStmt,\n Import,\n ImportAll,\n ImportFrom,\n IndexExpr,\n IntExpr,\n MatchStmt,\n MemberExpr,\n NameExpr,\n OpExpr,\n SliceExpr,\n StrExpr,\n TupleExpr,\n UnaryExpr,\n)\nfrom mypy.options import Options\nfrom mypy.patterns import AsPattern, OrPattern, Pattern\nfrom mypy.traverser import TraverserVisitor\n\n# Inferred truth value of an expression.\nALWAYS_TRUE: Final = 1\nMYPY_TRUE: Final = 2 # True in mypy, False at runtime\nALWAYS_FALSE: Final = 3\nMYPY_FALSE: Final = 4 # False in mypy, True at runtime\nTRUTH_VALUE_UNKNOWN: Final = 5\n\ninverted_truth_mapping: Final = {\n ALWAYS_TRUE: ALWAYS_FALSE,\n ALWAYS_FALSE: ALWAYS_TRUE,\n TRUTH_VALUE_UNKNOWN: TRUTH_VALUE_UNKNOWN,\n MYPY_TRUE: MYPY_FALSE,\n MYPY_FALSE: MYPY_TRUE,\n}\n\nreverse_op: Final = {\"==\": \"==\", \"!=\": \"!=\", \"<\": \">\", \">\": \"<\", \"<=\": \">=\", \">=\": \"<=\"}\n\n\ndef infer_reachability_of_if_statement(s: IfStmt, options: Options) -> None:\n for i in range(len(s.expr)):\n result = infer_condition_value(s.expr[i], options)\n if result in (ALWAYS_FALSE, MYPY_FALSE):\n # The condition is considered always false, so we skip the if\/elif body.\n mark_block_unreachable(s.body[i])\n elif result in (ALWAYS_TRUE, MYPY_TRUE):\n # This condition is considered always true, so all of the remaining\n # elif\/else bodies should not be checked.\n if result == MYPY_TRUE:\n # This condition is false at runtime; this will affect\n # import priorities.\n mark_block_mypy_only(s.body[i])\n for body in s.body[i + 1 :]:\n mark_block_unreachable(body)\n\n # Make sure else body always exists and is marked as\n # unreachable so the type checker always knows that\n # all control flow paths will flow through the if\n # statement body.\n if not s.else_body:\n s.else_body = Block([])\n mark_block_unreachable(s.else_body)\n break\n\n\ndef infer_reachability_of_match_statement(s: MatchStmt, options: Options) -> None:\n for i, guard in enumerate(s.guards):\n pattern_value = infer_pattern_value(s.patterns[i])\n\n if guard is not None:\n guard_value = infer_condition_value(guard, options)\n else:\n guard_value = ALWAYS_TRUE\n\n if pattern_value in (ALWAYS_FALSE, MYPY_FALSE) or guard_value in (\n ALWAYS_FALSE,\n MYPY_FALSE,\n ):\n # The case is considered always false, so we skip the case body.\n mark_block_unreachable(s.bodies[i])\n elif pattern_value in (ALWAYS_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 ` or `False or `: 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 == \"MYPY\" or name == \"TYPE_CHECKING\":\n result = MYPY_TRUE\n elif name in options.always_true:\n result = ALWAYS_TRUE\n elif name in options.always_false:\n result = ALWAYS_FALSE\n 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[] \n # - sys.version_info[:] \n # - sys.version_info \n # (in this case 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] 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/reachability.py","language":"Python","license":"NOASSERTION","size":12690} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/refinfo.py","language":"Python","license":"NOASSERTION","size":2784} {"code":"from __future__ import annotations\n\nfrom contextlib import contextmanager\nfrom typing import Final, Iterator\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/renaming.py","language":"Python","license":"NOASSERTION","size":19910} {"code":"\"\"\"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 operator import attrgetter\nfrom typing import Any, Callable, Dict, Final, Iterator, Tuple\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.version import __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 != \"\":\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(\"coverage\", timestamp=str(int(time.time())), version=__version__)\n self.doc = etree.ElementTree(self.root)\n self.root_package = CoberturaPackage(\".\")\n\n def on_file(\n self,\n tree: MypyFile,\n modules: dict[str, MypyFile],\n type_map: dict[Expression, Type],\n options: Options,\n ) -> None:\n path = os.path.relpath(tree.path)\n visitor = stats.StatisticsVisitor(\n inferred=True,\n filename=tree.fullname,\n modules=modules,\n typemap=type_map,\n all_nodes=True,\n )\n tree.accept(visitor)\n\n class_name = os.path.basename(path)\n file_info = FileInfo(path, tree._fullname)\n class_element = etree.Element(\"class\", complexity=\"1.0\", filename=path, name=class_name)\n etree.SubElement(class_element, \"methods\")\n lines_element = etree.SubElement(class_element, \"lines\")\n\n class_lines_covered = 0\n class_total_lines = 0\n for lineno, _ in iterate_python_lines(path):\n status = visitor.line_map.get(lineno, stats.TYPE_EMPTY)\n hits = 0\n branch = False\n if status == stats.TYPE_EMPTY:\n continue\n class_total_lines += 1\n if status != stats.TYPE_ANY:\n class_lines_covered += 1\n hits = 1\n if status == stats.TYPE_IMPRECISE:\n branch = True\n file_info.counts[status] += 1\n line_element = etree.SubElement(\n lines_element,\n \"line\",\n branch=str(branch).lower(),\n hits=str(hits),\n number=str(lineno),\n precision=stats.precision_names[status],\n )\n if branch:\n line_element.attrib[\"condition-coverage\"] = \"50% (1\/2)\"\n class_element.attrib[\"branch-rate\"] = \"0\"\n class_element.attrib[\"line-rate\"] = get_line_rate(class_lines_covered, class_total_lines)\n # parent_module is set to whichever module contains this file. For most files, we want\n # to simply strip the last element off of the module. But for __init__.py files,\n # the module == the parent module.\n parent_module = file_info.module.rsplit(\".\", 1)[0]\n if file_info.name.endswith(\"__init__.py\"):\n parent_module = file_info.module\n\n if parent_module not in self.root_package.packages:\n self.root_package.packages[parent_module] = CoberturaPackage(parent_module)\n current_package = self.root_package.packages[parent_module]\n packages_to_update = [self.root_package, current_package]\n for package in packages_to_update:\n package.total_lines += class_total_lines\n package.covered_lines += class_lines_covered\n current_package.classes[class_name] = class_element\n\n def on_finish(self) -> None:\n self.root.attrib[\"line-rate\"] = get_line_rate(\n self.root_package.covered_lines, self.root_package.total_lines\n )\n self.root.attrib[\"branch-rate\"] = \"0\"\n self.root.attrib[\"lines-covered\"] = str(self.root_package.covered_lines)\n self.root.attrib[\"lines-valid\"] = str(self.root_package.total_lines)\n sources = etree.SubElement(self.root, \"sources\")\n source_element = etree.SubElement(sources, \"source\")\n source_element.text = os.getcwd()\n self.root_package.add_packages(self.root)\n out_path = os.path.join(self.output_dir, \"cobertura.xml\")\n self.doc.write(out_path, encoding=\"utf-8\", pretty_print=True)\n print(\"Generated Cobertura report:\", os.path.abspath(out_path))\n\n\nregister_reporter(\"cobertura-xml\", CoberturaXmlReporter, needs_lxml=True)\n\n\nclass AbstractXmlReporter(AbstractReporter):\n \"\"\"Internal abstract class for reporters that work via XML.\"\"\"\n\n def __init__(self, reports: Reports, output_dir: str) -> None:\n super().__init__(reports, output_dir)\n\n memory_reporter = reports.add_report(\"memory-xml\", \"\")\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/report.py","language":"Python","license":"NOASSERTION","size":34446} {"code":"\"\"\"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 contextlib import contextmanager, nullcontext\nfrom typing import Iterator, Optional, Tuple\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/scope.py","language":"Python","license":"NOASSERTION","size":4258} {"code":"\"\"\"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 contextlib import contextmanager\nfrom typing import Any, Callable, Collection, Final, Iterable, Iterator, List, TypeVar, cast\nfrom typing_extensions import TypeAlias as _TypeAlias, TypeGuard\n\nfrom mypy import errorcodes as codes, message_registry\nfrom mypy.constant_fold import constant_fold_expr\nfrom mypy.errorcodes import PROPERTY_DECORATOR, ErrorCode\nfrom mypy.errors import Errors, report_internal_error\nfrom mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type\nfrom mypy.message_registry import ErrorMessage\nfrom mypy.messages import (\n SUGGESTED_TEST_FIXTURES,\n TYPES_FOR_UNIMPORTED_HINTS,\n MessageBuilder,\n best_matches,\n pretty_seq,\n)\nfrom mypy.mro import MroError, calculate_mro\nfrom mypy.nodes import (\n ARG_NAMED,\n ARG_POS,\n ARG_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.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 function_type, get_type_vars, try_getting_str_literals_from_type\nfrom mypy.types import (\n ASSERT_TYPE_NAMES,\n DATACLASS_TRANSFORM_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 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 get_proper_type,\n get_proper_types,\n is_named_instance,\n remove_dups,\n type_vars_as_args,\n)\nfrom mypy.types_utils import is_invalid_recursive_alias, store_argument_type\nfrom mypy.typevars import fill_typevars\nfrom mypy.util import correct_relative_import, is_dunder, module_prefix, unmangle, unnamed_function\nfrom mypy.visitor import NodeVisitor\n\nT = TypeVar(\"T\")\n\n\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 # 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 #\n # Preparing module (performed before semantic analysis)\n #\n\n def prepare_file(self, file_node: MypyFile) -> None:\n \"\"\"Prepare a freshly parsed file for semantic analysis.\"\"\"\n if \"builtins\" in self.modules:\n file_node.names[\"__builtins__\"] = SymbolTableNode(GDEF, self.modules[\"builtins\"])\n if file_node.fullname == \"builtins\":\n self.prepare_builtins_namespace(file_node)\n if file_node.fullname == \"typing\":\n self.prepare_typing_namespace(file_node, type_aliases)\n if file_node.fullname == \"typing_extensions\":\n self.prepare_typing_namespace(file_node, typing_extensions_aliases)\n\n def prepare_typing_namespace(self, file_node: MypyFile, aliases: dict[str, str]) -> None:\n \"\"\"Remove dummy alias definitions such as List = TypeAlias(object) from typing.\n\n They will be replaced with real aliases when corresponding targets are ready.\n \"\"\"\n\n # This is all pretty unfortunate. typeshed now has a\n # sys.version_info check for OrderedDict, and we shouldn't\n # take it out, because it is correct and a typechecker should\n # use that as a source of truth. But instead we rummage\n # through IfStmts to remove the info first. (I tried to\n # remove this whole machinery and ran into issues with the\n # builtins\/typing import cycle.)\n def helper(defs: list[Statement]) -> None:\n for stmt in defs.copy():\n if isinstance(stmt, IfStmt):\n for body in stmt.body:\n helper(body.body)\n if stmt.else_body:\n helper(stmt.else_body.body)\n if (\n isinstance(stmt, AssignmentStmt)\n and len(stmt.lvalues) == 1\n and isinstance(stmt.lvalues[0], NameExpr)\n ):\n # Assignment to a simple name, remove it if it is a dummy alias.\n if f\"{file_node.fullname}.{stmt.lvalues[0].name}\" in aliases:\n defs.remove(stmt)\n\n helper(file_node.defs)\n\n def prepare_builtins_namespace(self, file_node: MypyFile) -> None:\n \"\"\"Add certain special-cased definitions to the builtins module.\n\n Some definitions are too special or fundamental to be processed\n normally from the AST.\n \"\"\"\n names = file_node.names\n\n # Add empty definition for core built-in classes, since they are required for basic\n # operation. These will be completed later on.\n for name in CORE_BUILTIN_CLASSES:\n cdef = ClassDef(name, Block([])) # Dummy ClassDef, will be replaced later\n info = TypeInfo(SymbolTable(), cdef, \"builtins\")\n info._fullname = f\"builtins.{name}\"\n names[name] = SymbolTableNode(GDEF, info)\n\n bool_info = names[\"bool\"].node\n assert isinstance(bool_info, TypeInfo)\n bool_type = Instance(bool_info, [])\n\n special_var_types: list[tuple[str, Type]] = [\n (\"None\", NoneType()),\n # reveal_type is a mypy-only function that gives an error with\n # the type of its arg.\n (\"reveal_type\", AnyType(TypeOfAny.special_form)),\n # reveal_locals is a mypy-only function that gives an error with the types of\n # locals\n (\"reveal_locals\", AnyType(TypeOfAny.special_form)),\n (\"True\", bool_type),\n (\"False\", bool_type),\n (\"__debug__\", bool_type),\n ]\n\n for name, typ in special_var_types:\n v = Var(name, typ)\n v._fullname = f\"builtins.{name}\"\n file_node.names[name] = SymbolTableNode(GDEF, v)\n\n #\n # Analyzing a target\n #\n\n def refresh_partial(\n self,\n node: MypyFile | FuncDef | OverloadedFuncDef,\n patches: list[tuple[int, Callable[[], None]]],\n final_iteration: bool,\n file_node: MypyFile,\n options: Options,\n active_type: TypeInfo | None = None,\n ) -> None:\n \"\"\"Refresh a stale target in fine-grained incremental mode.\"\"\"\n self.patches = patches\n self.deferred = False\n self.incomplete = False\n self._final_iteration = final_iteration\n self.missing_names[-1] = set()\n\n with self.file_context(file_node, options, active_type):\n if isinstance(node, MypyFile):\n self.refresh_top_level(node)\n else:\n self.recurse_into_functions = True\n self.accept(node)\n del self.patches\n\n def refresh_top_level(self, file_node: MypyFile) -> None:\n \"\"\"Reanalyze a stale module top-level in fine-grained incremental mode.\"\"\"\n 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 # Visit default values because they may contain assignment expressions.\n for arg in defn.arguments:\n if arg.initializer:\n arg.initializer.accept(self)\n\n defn.is_conditional = self.block_depth[-1] > 0\n\n # Set full names even for those definitions that aren't added\n # to a symbol table. For example, for overload items.\n defn._fullname = self.qualified_name(defn.name)\n\n # We don't add module top-level functions to symbol tables\n # when we analyze their bodies in the second phase on analysis,\n # since they were added in the first phase. Nested functions\n # get always added, since they aren't separate targets.\n if not self.recurse_into_functions or len(self.function_stack) > 0:\n if not defn.is_decorated and not defn.is_overload:\n self.add_function_to_symbol_table(defn)\n\n if not self.recurse_into_functions:\n return\n\n with self.scope.function_scope(defn):\n self.analyze_func_def(defn)\n\n def function_fullname(self, fullname: str) -> str:\n if self.current_overload_item is None:\n return fullname\n return f\"{fullname}#{self.current_overload_item}\"\n\n def analyze_func_def(self, defn: FuncDef) -> None:\n if self.push_type_args(defn.type_args, defn) is None:\n self.defer(defn)\n return\n\n self.function_stack.append(defn)\n\n if defn.type:\n assert isinstance(defn.type, CallableType)\n has_self_type = self.update_function_type_variables(defn.type, defn)\n else:\n has_self_type = False\n\n self.function_stack.pop()\n\n if self.is_class_scope():\n # Method definition\n assert self.type is not None\n defn.info = self.type\n if defn.type is not None and defn.name in (\"__init__\", \"__init_subclass__\"):\n assert isinstance(defn.type, CallableType)\n if isinstance(get_proper_type(defn.type.ret_type), AnyType):\n defn.type = defn.type.copy_modified(ret_type=NoneType())\n self.prepare_method_signature(defn, self.type, has_self_type)\n\n # Analyze function signature\n fullname = self.function_fullname(defn.fullname)\n with self.tvar_scope_frame(self.tvar_scope.method_frame(fullname)):\n if defn.type:\n self.check_classvar_in_signature(defn.type)\n assert isinstance(defn.type, CallableType)\n # Signature must be analyzed in the surrounding scope so that\n # class-level imported names and type variables are in scope.\n analyzer = self.type_analyzer()\n tag = self.track_incomplete_refs()\n result = analyzer.visit_callable_type(defn.type, nested=False, namespace=fullname)\n # Don't store not ready types (including placeholders).\n if self.found_incomplete_ref(tag) or has_placeholder(result):\n self.defer(defn)\n self.pop_type_args(defn.type_args)\n return\n assert isinstance(result, ProperType)\n if isinstance(result, CallableType):\n # type guards need to have a positional argument, to spec\n skip_self = self.is_class_scope() and not defn.is_static\n if result.type_guard and ARG_POS not in result.arg_kinds[skip_self:]:\n self.fail(\n \"TypeGuard functions must have a positional argument\",\n result,\n code=codes.VALID_TYPE,\n )\n # in this case, we just kind of just ... remove the type guard.\n result = result.copy_modified(type_guard=None)\n if result.type_is and ARG_POS not in result.arg_kinds[skip_self:]:\n self.fail(\n '\"TypeIs\" functions must have a positional argument',\n result,\n code=codes.VALID_TYPE,\n )\n result = result.copy_modified(type_is=None)\n\n result = self.remove_unpack_kwargs(defn, result)\n if has_self_type and self.type is not None:\n info = self.type\n if info.self_type is not None:\n result.variables = [info.self_type] + list(result.variables)\n defn.type = result\n self.add_type_alias_deps(analyzer.aliases_used)\n self.check_function_signature(defn)\n self.check_paramspec_definition(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\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_final_in_overload(defn)\n self.process_static_or_class_method_in_overload(defn)\n self.process_overload_impl(defn)\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 if not any(refers_to_fullname(dec, OVERLOAD_NAMES) for dec in item.decorators):\n if i == len(defn.items) - 1 and not self.is_stub_file:\n # Last item outside a stub is impl\n impl = item\n else:\n # Oops it wasn't an overload after all. A clear error\n # will vary based on where in the list it is, record\n # that.\n non_overload_indexes.append(i)\n else:\n item.func.is_overload = True\n types.append(callable)\n if item.var.is_property:\n self.fail(\"An overload can not be a property\", item)\n # If any item was decorated with `@override`, the whole overload\n # becomes an explicit override.\n defn.is_explicit_override |= item.func.is_explicit_override\n elif isinstance(item, FuncDef):\n if i == len(defn.items) - 1 and not self.is_stub_file:\n impl = item\n else:\n non_overload_indexes.append(i)\n return types, impl, non_overload_indexes\n\n def handle_missing_overload_decorators(\n self,\n defn: OverloadedFuncDef,\n non_overload_indexes: list[int],\n some_overload_decorators: bool,\n ) -> None:\n \"\"\"Generate errors for overload items without @overload.\n\n Side effect: remote non-overload items.\n \"\"\"\n if some_overload_decorators:\n # Some of them were overloads, but not all.\n for idx in non_overload_indexes:\n if self.is_stub_file:\n self.fail(\n \"An implementation for an overloaded function \"\n \"is not allowed in a stub file\",\n defn.items[idx],\n )\n else:\n self.fail(\n \"The implementation for an overloaded function must come last\",\n defn.items[idx],\n )\n else:\n for idx in non_overload_indexes[1:]:\n self.name_already_defined(defn.name, defn.items[idx], defn.items[0])\n if defn.impl:\n self.name_already_defined(defn.name, defn.impl, defn.items[0])\n # Remove the non-overloads\n for idx in reversed(non_overload_indexes):\n del defn.items[idx]\n\n def handle_missing_overload_implementation(self, defn: OverloadedFuncDef) -> None:\n \"\"\"Generate error about missing overload implementation (only if needed).\"\"\"\n if not self.is_stub_file:\n if self.type and self.type.is_protocol and not self.is_func_scope():\n # An overloaded protocol method doesn't need an implementation,\n # but if it doesn't have one, then it is considered abstract.\n for item in defn.items:\n if isinstance(item, Decorator):\n item.func.abstract_status = IS_ABSTRACT\n else:\n item.abstract_status = IS_ABSTRACT\n else:\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 node = item.decorators[0]\n if isinstance(node, MemberExpr):\n if 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 if node.name == \"deleter\":\n item.func.abstract_status = first_item.func.abstract_status\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 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 check_paramspec_definition(self, defn: FuncDef) -> None:\n func = defn.type\n assert isinstance(func, CallableType)\n\n if not any(isinstance(var, ParamSpecType) for var in func.variables):\n return # Function does not have param spec variables\n\n args = func.var_arg()\n kwargs = func.kw_arg()\n if args is None and kwargs is None:\n return # Looks like this function does not have starred args\n\n args_defn_type = None\n kwargs_defn_type = None\n for arg_def, arg_kind in zip(defn.arguments, defn.arg_kinds):\n if arg_kind == ARG_STAR:\n args_defn_type = arg_def.type_annotation\n elif arg_kind == ARG_STAR2:\n kwargs_defn_type = arg_def.type_annotation\n\n # This may happen on invalid `ParamSpec` args \/ kwargs definition,\n # type analyzer sets types of arguments to `Any`, but keeps\n # definition types as `UnboundType` for now.\n if not (\n (isinstance(args_defn_type, UnboundType) and args_defn_type.name.endswith(\".args\"))\n or (\n isinstance(kwargs_defn_type, UnboundType)\n and kwargs_defn_type.name.endswith(\".kwargs\")\n )\n ):\n # Looks like both `*args` and `**kwargs` are not `ParamSpec`\n # It might be something else, skipping.\n return\n\n args_type = args.typ if args is not None else None\n kwargs_type = kwargs.typ if kwargs is not None else None\n\n if (\n not isinstance(args_type, ParamSpecType)\n or not isinstance(kwargs_type, ParamSpecType)\n or args_type.name != kwargs_type.name\n ):\n if isinstance(args_defn_type, UnboundType) and args_defn_type.name.endswith(\".args\"):\n param_name = args_defn_type.name.split(\".\")[0]\n elif isinstance(kwargs_defn_type, UnboundType) and kwargs_defn_type.name.endswith(\n \".kwargs\"\n ):\n param_name = kwargs_defn_type.name.split(\".\")[0]\n else:\n # Fallback for cases that probably should not ever happen:\n param_name = \"P\"\n\n self.fail(\n f'ParamSpec must have \"*args\" typed as \"{param_name}.args\" and \"**kwargs\" typed as \"{param_name}.kwargs\"',\n func,\n code=codes.VALID_TYPE,\n )\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 ),\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 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 default = AnyType(TypeOfAny.from_omitted_generics)\n if type_param.kind == TYPE_VAR_KIND:\n values = []\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 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\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: list[TypeVarLikeType] = []\n last_tvar_name_with_default: str | None = None\n for name, tvar_expr in declared_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)\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 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 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)\n info.fallback_to_any = True\n elif isinstance(base, TypedDictType):\n base_types.append(base.fallback)\n else:\n msg = \"Invalid base class\"\n name = self.get_name_repr_of_expr(base_expr)\n if name:\n msg += f' \"{name}\"'\n self.fail(msg, base_expr)\n info.fallback_to_any = True\n if self.options.disallow_any_unimported and has_any_from_unimported_type(base):\n if isinstance(base_expr, (NameExpr, MemberExpr)):\n prefix = f\"Base type {base_expr.name}\"\n else:\n prefix = \"Base type\"\n self.msg.unimported_type_becomes_any(prefix, base, base_expr)\n check_for_explicit_any(\n base, self.options, self.is_typeshed_stub_file, self.msg, context=base_expr\n )\n\n # Add 'object' as implicit base if there is no other base class.\n if not base_types and defn.fullname != \"builtins.object\":\n base_types.append(self.object_type())\n\n info.bases = base_types\n\n # Calculate the MRO.\n if not self.verify_base_classes(defn):\n self.set_dummy_mro(defn.info)\n return\n if not self.verify_duplicate_base_classes(defn):\n # We don't want to block the typechecking process,\n # so, we just insert `Any` as the base class and show an error.\n self.set_any_mro(defn.info)\n self.calculate_class_mro(defn, self.object_type)\n\n def configure_tuple_base_class(self, defn: ClassDef, base: TupleType) -> Instance:\n info = defn.info\n\n # There may be an existing valid tuple type from previous semanal iterations.\n # Use equality to check if it is the case.\n if info.tuple_type and info.tuple_type != base and not has_placeholder(info.tuple_type):\n self.fail(\"Class has two incompatible bases derived from tuple\", defn)\n defn.has_incompatible_baseclass = True\n if 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 \"Cannot determine consistent method resolution \"\n 'order (MRO) for \"%s\"' % 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 if (\n isinstance(sym.node, TypeAlias)\n and sym.node.no_args\n and isinstance(sym.node.target, ProperType)\n and isinstance(sym.node.target, Instance)\n ):\n metaclass_info: Node | None = sym.node.target.type\n else:\n metaclass_info = sym.node\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 use_implicit_reexport = not self.is_stub_file and self.options.implicit_reexport\n module_public = use_implicit_reexport or (as_id is not None and id == as_id)\n\n # If the module does not contain a symbol with the name 'id',\n # try checking if it's a module instead.\n if not node:\n mod = self.modules.get(fullname)\n if mod is not None:\n kind = self.current_symbol_kind()\n node = SymbolTableNode(kind, mod)\n elif fullname in self.missing_modules:\n missing_submodule = True\n # If it is still not resolved, check for a module level __getattr__\n if module and not node and \"__getattr__\" in module.names:\n # We store the fullname of the original definition so that we can\n # detect whether two imported names refer to the same thing.\n fullname = module_id + \".\" + id\n gvar = self.create_getattr_var(module.names[\"__getattr__\"], imported_id, fullname)\n if gvar:\n self.add_symbol(\n imported_id,\n gvar,\n imp,\n module_public=module_public,\n module_hidden=not module_public,\n )\n continue\n\n if node:\n self.process_imported_symbol(\n node, module_id, id, imported_id, fullname, module_public, context=imp\n )\n if node.module_hidden:\n self.report_missing_module_attribute(\n module_id,\n id,\n imported_id,\n module_public=module_public,\n module_hidden=not module_public,\n context=imp,\n add_unknown_imported_symbol=False,\n )\n elif module and not missing_submodule:\n # Target module exists but the imported name is missing or hidden.\n self.report_missing_module_attribute(\n module_id,\n id,\n imported_id,\n module_public=module_public,\n module_hidden=not module_public,\n context=imp,\n )\n else:\n # Import of a missing (sub)module.\n self.add_unknown_imported_symbol(\n imported_id,\n imp,\n target_name=fullname,\n module_public=module_public,\n module_hidden=not module_public,\n )\n\n def process_imported_symbol(\n self,\n node: SymbolTableNode,\n module_id: str,\n id: str,\n imported_id: str,\n fullname: str,\n module_public: bool,\n context: ImportBase,\n ) -> None:\n module_hidden = not module_public and (\n # `from package import submodule` should work regardless of whether package\n # re-exports submodule, so we shouldn't hide it\n not isinstance(node.node, MypyFile)\n or fullname not in self.modules\n # but given `from somewhere import random_unrelated_module` we should hide\n # random_unrelated_module\n or not fullname.startswith(self.cur_mod_id + \".\")\n )\n\n if isinstance(node.node, PlaceholderNode):\n if self.final_iteration:\n self.report_missing_module_attribute(\n module_id,\n id,\n imported_id,\n module_public=module_public,\n module_hidden=module_hidden,\n context=context,\n )\n return\n else:\n # This might become a type.\n self.mark_incomplete(\n imported_id,\n node.node,\n module_public=module_public,\n module_hidden=module_hidden,\n becomes_typeinfo=True,\n )\n # NOTE: we take the original node even for final `Var`s. This is to support\n # a common pattern when constants are re-exported (same applies to import *).\n self.add_imported_symbol(\n imported_id, node, context, module_public=module_public, module_hidden=module_hidden\n )\n\n def report_missing_module_attribute(\n self,\n import_id: str,\n source_id: str,\n imported_id: str,\n module_public: bool,\n module_hidden: bool,\n context: Node,\n add_unknown_imported_symbol: bool = True,\n ) -> None:\n # Missing attribute.\n if self.is_incomplete_namespace(import_id):\n # We don't know whether the name will be there, since the namespace\n # is incomplete. Defer the current target.\n self.mark_incomplete(\n imported_id, context, module_public=module_public, module_hidden=module_hidden\n )\n return\n message = f'Module \"{import_id}\" has no attribute \"{source_id}\"'\n # Suggest alternatives, if any match is found.\n module = self.modules.get(import_id)\n if module:\n if source_id in module.names.keys() and not module.names[source_id].module_public:\n message = (\n f'Module \"{import_id}\" does not explicitly export attribute \"{source_id}\"'\n )\n 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:\/\/mypy.readthedocs.io\/en\/stable\/runtime_troubles.html#using-new-additions-to-the-typing-module\",\n context,\n code=codes.ATTR_DEFINED,\n )\n\n def process_import_over_existing_name(\n self,\n imported_id: str,\n existing_symbol: SymbolTableNode,\n module_symbol: SymbolTableNode,\n import_node: ImportBase,\n ) -> bool:\n if existing_symbol.node is module_symbol.node:\n # We added this symbol on previous iteration.\n return False\n if existing_symbol.kind in (LDEF, GDEF, MDEF) and isinstance(\n existing_symbol.node, (Var, FuncDef, TypeInfo, Decorator, TypeAlias)\n ):\n # This is a valid import over an existing definition in the file. Construct a dummy\n # assignment that we'll use to type check the import.\n lvalue = NameExpr(imported_id)\n lvalue.kind = existing_symbol.kind\n lvalue.node = existing_symbol.node\n rvalue = NameExpr(imported_id)\n rvalue.kind = module_symbol.kind\n rvalue.node = module_symbol.node\n if isinstance(rvalue.node, TypeAlias):\n # Suppress bogus errors from the dummy assignment if rvalue is an alias.\n # Otherwise mypy may complain that alias is invalid in runtime context.\n rvalue.is_alias_rvalue = True\n assignment = AssignmentStmt([lvalue], rvalue)\n for node in assignment, lvalue, rvalue:\n node.set_line(import_node)\n import_node.assignments.append(assignment)\n return True\n return False\n\n def correct_relative_import(self, node: ImportFrom | ImportAll) -> str:\n import_id, ok = correct_relative_import(\n self.cur_mod_id, node.relative, node.id, self.cur_mod_node.is_package_init_file()\n )\n if not ok:\n self.fail(\"Relative import climbs too many namespaces\", node)\n return import_id\n\n def visit_import_all(self, i: ImportAll) -> None:\n i_id = self.correct_relative_import(i)\n if i_id in self.modules:\n m = self.modules[i_id]\n if self.is_incomplete_namespace(i_id):\n # Any names could be missing from the current namespace if the target module\n # namespace is incomplete.\n self.mark_incomplete(\"*\", i)\n for name, node in m.names.items():\n 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 isinstance(s.rvalue, TempNode) and s.rvalue.no_rhs:\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 s.type is not None and self.is_classvar(s.type):\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(s.type, allow_tuple_literal=allow_tuple_literal)\n # Don't store not ready types (including placeholders).\n if analyzed is None or has_placeholder(analyzed):\n self.defer(s)\n return\n s.type = analyzed\n if (\n self.type\n and self.type.is_protocol\n and isinstance(lvalue, NameExpr)\n and isinstance(s.rvalue, TempNode)\n and s.rvalue.no_rhs\n ):\n if isinstance(lvalue.node, Var):\n lvalue.node.is_abstract_var = True\n else:\n if (\n self.type\n and self.type.is_protocol\n and self.is_annotated_protocol_member(s)\n and not self.is_func_scope()\n ):\n self.fail(\"All protocol members must have explicitly declared types\", s)\n # Set the type if the rvalue is a simple literal (even if the above error occurred).\n if len(s.lvalues) == 1 and isinstance(s.lvalues[0], RefExpr):\n ref_expr = s.lvalues[0]\n safe_literal_inference = True\n if self.type and isinstance(ref_expr, NameExpr) and len(self.type.mro) > 1:\n # Check if there is a definition in supertype. If yes, we can't safely\n # decide here what to infer: int or Literal[42].\n safe_literal_inference = self.type.mro[1].get(ref_expr.name) is None\n if safe_literal_inference and ref_expr.is_inferred_def:\n s.type = self.analyze_simple_literal_type(s.rvalue, s.is_final_def)\n if s.type:\n # Store type into nodes.\n for lvalue in s.lvalues:\n self.store_declared_types(lvalue, s.type)\n\n def is_annotated_protocol_member(self, s: AssignmentStmt) -> bool:\n \"\"\"Check whether a protocol member is annotated.\n\n There are some exceptions that can be left unannotated, like ``__slots__``.\"\"\"\n return any(\n (isinstance(lv, NameExpr) and lv.name != \"__slots__\" and lv.is_inferred_def)\n for lv in s.lvalues\n )\n\n def analyze_simple_literal_type(self, rvalue: Expression, is_final: bool) -> Type | None:\n \"\"\"Return builtins.int if rvalue is an int literal, etc.\n\n If this is a 'Final' context, we return \"Literal[...]\" instead.\n \"\"\"\n if self.function_stack:\n # Skip inside a function; this is to avoid confusing\n # the code that handles dead code due to isinstance()\n # inside type variables with value restrictions (like\n # AnyStr).\n return None\n\n value = constant_fold_expr(rvalue, self.cur_mod_id)\n if value is None or isinstance(value, complex):\n return None\n\n if isinstance(value, bool):\n type_name = \"builtins.bool\"\n elif isinstance(value, int):\n type_name = \"builtins.int\"\n elif isinstance(value, str):\n type_name = \"builtins.str\"\n elif isinstance(value, float):\n type_name = \"builtins.float\"\n\n typ = self.named_type_or_none(type_name)\n if typ and is_final:\n return typ.copy_modified(last_known_value=LiteralType(value=value, fallback=typ))\n return typ\n\n def analyze_alias(\n self,\n name: str,\n rvalue: Expression,\n allow_placeholder: bool = False,\n declared_type_vars: TypeVarLikeList | None = None,\n all_declared_type_params_names: list[str] | None = None,\n python_3_12_type_alias: bool = False,\n ) -> tuple[Type | None, list[TypeVarLikeType], set[str], 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, self.options, self.is_stub_file, lookup_qualified=self.lookup_qualified\n )\n except TypeTranslationError:\n self.fail(\n \"Invalid type alias: expression is not a valid type\", rvalue, code=codes.VALID_TYPE\n )\n return None, [], set(), [], False\n\n found_type_vars = self.find_type_var_likes(typ)\n 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 last_tvar_name_with_default: str | None = None\n with self.tvar_scope_frame(self.tvar_scope.class_frame(namespace)):\n for name, tvar_expr in alias_type_vars:\n tvar_expr.default = tvar_expr.default.accept(\n TypeVarDefaultTranslator(self, tvar_expr.name, typ)\n )\n tvar_def = self.tvar_scope.bind_new(name, tvar_expr)\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, typ\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\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.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 )\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\n return self.check_typevarlike_name(rvalue, name, rvalue)\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 decalred 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 ) -> 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 \"\"\"\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 )\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 ) -> 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 (not existing or isinstance(existing.node, PlaceholderNode)) and not outer:\n # Define new variable.\n var = self.make_name_lvalue_var(lvalue, kind, not explicit_type, has_explicit_value)\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, lvalue: NameExpr, kind: int, inferred: bool, has_explicit_value: 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 # fullanme 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 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 values\", s, force_progress=updated)\n elif has_placeholder(upper_bound):\n self.process_placeholder(None, \"TypeVar upper bound\", s, force_progress=updated)\n elif has_placeholder(default):\n self.process_placeholder(None, \"TypeVar default\", s, force_progress=updated)\n\n self.add_symbol(name, call.analyzed, s)\n return True\n\n def check_typevarlike_name(self, call: CallExpr, name: str, context: Context) -> bool:\n \"\"\"Checks that the name of a TypeVar or ParamSpec matches its variable.\"\"\"\n name = unmangle(name)\n assert isinstance(call.callee, RefExpr)\n typevarlike_type = (\n call.callee.name if isinstance(call.callee, NameExpr) else call.callee.fullname\n )\n if len(call.args) < 1:\n self.fail(f\"Too few arguments for {typevarlike_type}()\", context)\n return False\n if not isinstance(call.args[0], StrExpr) or call.arg_kinds[0] != ARG_POS:\n self.fail(f\"{typevarlike_type}() expects a string literal as first argument\", context)\n return False\n elif call.args[0].value != name:\n msg = 'String argument 1 \"{}\" to {}(...) does not match variable name \"{}\"'\n self.fail(msg.format(call.args[0].value, typevarlike_type, name), context)\n return False\n return True\n\n def get_typevarlike_declaration(\n self, s: AssignmentStmt, typevarlike_types: tuple[str, ...]\n ) -> CallExpr | None:\n \"\"\"Returns the call expression if `s` is a declaration of `typevarlike_type`\n (TypeVar or ParamSpec), or None otherwise.\n \"\"\"\n if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], NameExpr):\n return None\n if not isinstance(s.rvalue, CallExpr):\n return None\n call = s.rvalue\n callee = call.callee\n if not isinstance(callee, RefExpr):\n return None\n if callee.fullname not in typevarlike_types:\n return None\n return call\n\n def process_typevar_parameters(\n self,\n args: list[Expression],\n names: list[str | None],\n kinds: list[ArgKind],\n num_values: int,\n context: Context,\n ) -> tuple[int, Type, Type] | None:\n has_values = num_values > 0\n covariant = False\n contravariant = False\n upper_bound: Type = self.object_type()\n default: Type = AnyType(TypeOfAny.from_omitted_generics)\n for param_value, param_name, param_kind in zip(args, names, kinds):\n if not param_kind.is_named():\n self.fail(message_registry.TYPEVAR_UNEXPECTED_ARGUMENT, context)\n return None\n if param_name == \"covariant\":\n if isinstance(param_value, NameExpr) and param_value.name in (\"True\", \"False\"):\n covariant = param_value.name == \"True\"\n else:\n self.fail(message_registry.TYPEVAR_VARIANCE_DEF.format(\"covariant\"), context)\n return None\n elif param_name == \"contravariant\":\n if isinstance(param_value, NameExpr) and param_value.name in (\"True\", \"False\"):\n contravariant = param_value.name == \"True\"\n else:\n self.fail(\n message_registry.TYPEVAR_VARIANCE_DEF.format(\"contravariant\"), context\n )\n return None\n elif param_name == \"bound\":\n if has_values:\n self.fail(\"TypeVar cannot have both values and an upper bound\", context)\n return None\n tv_arg = self.get_typevarlike_argument(\"TypeVar\", param_name, param_value, context)\n if tv_arg is None:\n return None\n upper_bound = tv_arg\n elif param_name == \"default\":\n tv_arg = self.get_typevarlike_argument(\n \"TypeVar\", param_name, param_value, context, allow_unbound_tvars=True\n )\n default = tv_arg or AnyType(TypeOfAny.from_error)\n elif param_name == \"values\":\n # Probably using obsolete syntax with values=(...). Explain the current syntax.\n self.fail('TypeVar \"values\" argument not supported', context)\n self.fail(\n \"Use TypeVar('T', t, ...) instead of TypeVar('T', values=(t, ...))\", context\n )\n return None\n else:\n self.fail(\n f'{message_registry.TYPEVAR_UNEXPECTED_ARGUMENT}: \"{param_name}\"', context\n )\n return None\n\n if covariant and contravariant:\n self.fail(\"TypeVar cannot be both covariant and contravariant\", context)\n return None\n elif num_values == 1:\n self.fail(message_registry.TYPE_VAR_TOO_FEW_CONSTRAINED_TYPES, context)\n return None\n elif covariant:\n variance = COVARIANT\n elif contravariant:\n variance = CONTRAVARIANT\n else:\n variance = INVARIANT\n return variance, upper_bound, default\n\n def get_typevarlike_argument(\n self,\n typevarlike_name: str,\n param_name: str,\n param_value: Expression,\n context: Context,\n *,\n allow_unbound_tvars: bool = False,\n allow_param_spec_literals: bool = False,\n allow_unpack: bool = False,\n report_invalid_typevar_arg: bool = True,\n ) -> ProperType | None:\n try:\n # We want to use our custom error message below, so we suppress\n # the default error message for invalid types here.\n analyzed = self.expr_to_analyzed_type(\n param_value,\n allow_placeholder=True,\n report_invalid_types=False,\n allow_unbound_tvars=allow_unbound_tvars,\n allow_param_spec_literals=allow_param_spec_literals,\n allow_unpack=allow_unpack,\n )\n if analyzed is None:\n # Type variables are special: we need to place them in the symbol table\n # soon, even if upper bound is not ready yet. Otherwise avoiding\n # a \"deadlock\" in this common pattern would be tricky:\n # T = TypeVar('T', bound=Custom[Any])\n # class Custom(Generic[T]):\n # ...\n analyzed = PlaceholderType(None, [], context.line)\n typ = get_proper_type(analyzed)\n if report_invalid_typevar_arg and isinstance(typ, AnyType) and typ.is_from_error:\n self.fail(\n message_registry.TYPEVAR_ARG_MUST_BE_TYPE.format(typevarlike_name, param_name),\n param_value,\n )\n # Note: we do not return 'None' here -- we want to continue\n # using the AnyType.\n return typ\n except TypeTranslationError:\n if report_invalid_typevar_arg:\n self.fail(\n message_registry.TYPEVAR_ARG_MUST_BE_TYPE.format(typevarlike_name, param_name),\n param_value,\n )\n return None\n\n def extract_typevarlike_name(self, s: AssignmentStmt, call: CallExpr) -> str | None:\n if not call:\n return None\n\n lvalue = s.lvalues[0]\n assert isinstance(lvalue, NameExpr)\n if s.type:\n self.fail(\"Cannot declare the type of a TypeVar or similar construct\", s)\n return None\n\n if not self.check_typevarlike_name(call, lvalue.name, s):\n return None\n return lvalue.name\n\n def process_paramspec_declaration(self, s: AssignmentStmt) -> bool:\n \"\"\"Checks if s declares a ParamSpec; if yes, store it in symbol table.\n\n Return True if this looks like a ParamSpec (maybe with errors), otherwise return False.\n\n In the future, ParamSpec may accept bounds and variance arguments, in which\n case more aggressive sharing of code with process_typevar_declaration should be pursued.\n \"\"\"\n call = self.get_typevarlike_declaration(\n s, (\"typing_extensions.ParamSpec\", \"typing.ParamSpec\")\n )\n if not call:\n return False\n\n name = self.extract_typevarlike_name(s, call)\n if name is None:\n return False\n\n n_values = call.arg_kinds[1:].count(ARG_POS)\n if n_values != 0:\n self.fail('Too many positional arguments for \"ParamSpec\"', s)\n\n default: Type = AnyType(TypeOfAny.from_omitted_generics)\n for param_value, param_name in zip(\n call.args[1 + n_values :], call.arg_names[1 + n_values :]\n ):\n if param_name == \"default\":\n tv_arg = self.get_typevarlike_argument(\n \"ParamSpec\",\n param_name,\n param_value,\n s,\n allow_unbound_tvars=True,\n allow_param_spec_literals=True,\n report_invalid_typevar_arg=False,\n )\n default = tv_arg or AnyType(TypeOfAny.from_error)\n if isinstance(tv_arg, Parameters):\n for i, arg_type in enumerate(tv_arg.arg_types):\n typ = get_proper_type(arg_type)\n if isinstance(typ, AnyType) and typ.is_from_error:\n self.fail(\n f\"Argument {i} of ParamSpec default must be a type\", param_value\n )\n elif (\n isinstance(default, AnyType)\n and default.is_from_error\n or not isinstance(default, (AnyType, UnboundType))\n ):\n self.fail(\n \"The default argument to ParamSpec must be a list expression, ellipsis, or a ParamSpec\",\n param_value,\n )\n default = AnyType(TypeOfAny.from_error)\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 if not isinstance(default, UnpackType):\n self.fail(\n \"The default argument to TypeVarTuple must be an Unpacked tuple\",\n param_value,\n )\n default = AnyType(TypeOfAny.from_error)\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 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 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 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)\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 self.visit_block(s.body)\n self.loop_depth[-1] -= 1\n\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\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\n def visit_if_stmt(self, s: IfStmt) -> None:\n self.statement = s\n infer_reachability_of_if_statement(s, self.options)\n for i in range(len(s.expr)):\n s.expr[i].accept(self)\n self.visit_block(s.body[i])\n self.visit_block_maybe(s.else_body)\n\n def visit_try_stmt(self, s: TryStmt) -> None:\n self.statement = s\n self.analyze_try_stmt(s, self)\n\n def analyze_try_stmt(self, s: TryStmt, visitor: NodeVisitor[None]) -> None:\n s.body.accept(visitor)\n for type, var, handler in zip(s.types, s.vars, s.handlers):\n if type:\n type.accept(visitor)\n if var:\n self.analyze_lvalue(var)\n 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\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(\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 has_param_spec = base.node.has_param_spec_type\n num_args = len(base.node.type_vars)\n else:\n allow_unpack = False\n has_param_spec = False\n num_args = -1\n\n for item in items:\n try:\n typearg = self.expr_to_unanalyzed_type(item, allow_unpack=True)\n except TypeTranslationError:\n self.fail(\"Type expected within [...]\", expr)\n return None\n analyzed = self.anal_type(\n typearg,\n # The type application may appear in base class expression,\n # where type variables are not bound yet. Or when accepting\n # r.h.s. of type alias before we figured out it is a type alias.\n allow_unbound_tvars=self.allow_unbound_tvars,\n allow_placeholder=True,\n allow_param_spec_literals=has_param_spec,\n allow_unpack=allow_unpack,\n )\n if analyzed is None:\n return None\n types.append(analyzed)\n\n if has_param_spec and num_args == 1 and types:\n first_arg = get_proper_type(types[0])\n single_any = len(types) == 1 and isinstance(first_arg, AnyType)\n if not (single_any or any(isinstance(t, (Parameters, ParamSpecType)) for t in types)):\n types = [Parameters(types, [ARG_POS] * len(types), [None] * len(types))]\n\n return types\n\n def visit_slice_expr(self, expr: SliceExpr) -> None:\n if expr.begin_index:\n expr.begin_index.accept(self)\n if expr.end_index:\n expr.end_index.accept(self)\n if expr.stride:\n expr.stride.accept(self)\n\n def visit_cast_expr(self, expr: CastExpr) -> None:\n expr.expr.accept(self)\n analyzed = self.anal_type(expr.type)\n if analyzed is not None:\n expr.type = analyzed\n\n def visit_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 enviroments (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 # TODO: support nested classes (but consider performance impact,\n # we might keep the module level only lookup for thing like 'builtins.int').\n assert \".\" in fullname\n module, name = fullname.rsplit(\".\", maxsplit=1)\n if module not in self.modules:\n return None\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\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, [AnyType(TypeOfAny.unannotated)] * len(node.defn.type_vars))\n\n def builtin_type(self, fully_qualified_name: str) -> Instance:\n \"\"\"Legacy function -- use named_type() instead.\"\"\"\n return self.named_type(fully_qualified_name)\n\n def lookup_current_scope(self, name: str) -> SymbolTableNode | None:\n if self.locals[-1] is not None:\n return self.locals[-1].get(name)\n elif self.type is not None:\n return self.type.names.get(name)\n else:\n return self.globals.get(name)\n\n #\n # Adding symbols\n #\n\n def add_symbol(\n self,\n name: str,\n node: SymbolNode,\n context: Context,\n module_public: bool = True,\n module_hidden: bool = False,\n can_defer: bool = True,\n escape_comprehensions: bool = False,\n no_progress: bool = False,\n type_param: bool = False,\n ) -> bool:\n \"\"\"Add symbol to the currently active symbol table.\n\n Generally additions to symbol table should go through this method or\n one of the methods below so that kinds, redefinitions, conditional\n definitions, and skipped names are handled consistently.\n\n Return True if we actually added the symbol, or False if we refused to do so\n (because something is not ready).\n\n If can_defer is True, defer current target if adding a placeholder.\n \"\"\"\n if self.is_func_scope():\n kind = LDEF\n elif self.type is not None:\n kind = MDEF\n else:\n kind = GDEF\n symbol = SymbolTableNode(\n kind, node, module_public=module_public, module_hidden=module_hidden\n )\n return self.add_symbol_table_node(\n name, symbol, context, can_defer, escape_comprehensions, no_progress, type_param\n )\n\n def add_symbol_skip_local(self, name: str, node: SymbolNode) -> None:\n \"\"\"Same as above, but skipping the local namespace.\n\n This doesn't check for previous definition and is only used\n for serialization of method-level classes.\n\n Classes defined within methods can be exposed through an\n attribute type, but method-level symbol tables aren't serialized.\n This method can be used to add such classes to an enclosing,\n serialized symbol table.\n \"\"\"\n # TODO: currently this is only used by named tuples and typed dicts.\n # Use this method also by normal classes, see issue #6422.\n if self.type is not None:\n names = self.type.names\n kind = MDEF\n else:\n names = self.globals\n kind = GDEF\n symbol = SymbolTableNode(kind, node)\n names[name] = symbol\n\n def add_symbol_table_node(\n self,\n name: str,\n symbol: SymbolTableNode,\n context: Context | None = None,\n can_defer: bool = True,\n escape_comprehensions: bool = False,\n no_progress: bool = False,\n type_param: bool = False,\n ) -> bool:\n \"\"\"Add symbol table node to the currently active symbol table.\n\n Return True if we actually added the symbol, or False if we refused\n to do so (because something is not ready or it was a no-op).\n\n Generate an error if there is an invalid redefinition.\n\n If context is None, unconditionally add node, since we can't report\n an error. Note that this is used by plugins to forcibly replace nodes!\n\n TODO: Prevent plugins from replacing nodes, as it could cause problems?\n\n Args:\n name: short name of symbol\n symbol: Node to add\n can_defer: if True, defer current target if adding a placeholder\n context: error context (see above about None value)\n \"\"\"\n names = self.current_symbol_table(\n escape_comprehensions=escape_comprehensions, type_param=type_param\n )\n existing = names.get(name)\n if isinstance(symbol.node, PlaceholderNode) and can_defer:\n if context is not None:\n self.process_placeholder(name, \"name\", context)\n else:\n # see note in docstring describing None contexts\n self.defer()\n 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: 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_param_spec_literals: bool = False,\n allow_unpack: bool = False,\n report_invalid_types: bool = True,\n prohibit_self_type: 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.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_param_spec_literals=allow_param_spec_literals,\n allow_unpack=allow_unpack,\n prohibit_self_type=prohibit_self_type,\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_param_spec_literals: bool = False,\n allow_unpack: bool = False,\n report_invalid_types: bool = True,\n prohibit_self_type: str | None = None,\n allow_type_any: bool = False,\n ) -> Type | None:\n \"\"\"Semantically analyze a type.\n\n Args:\n typ: Type to analyze (if already analyzed, this is a no-op)\n allow_placeholder: If True, may return PlaceholderType if\n encountering an incomplete definition\n\n Return None only if some part of the type couldn't be bound *and* it\n referred to an incomplete namespace or definition. In this case also\n defer as needed. During a final iteration this won't return None;\n instead report an error if the type can't be analyzed and return\n AnyType.\n\n In case of other errors, report an error message and return AnyType.\n\n NOTE: The caller shouldn't defer even if this returns None or a\n placeholder type.\n \"\"\"\n has_self_type = find_self_type(\n typ, lambda name: self.lookup_qualified(name, typ, suppress_errors=True)\n )\n if has_self_type and self.type and prohibit_self_type is None:\n self.setup_self_type()\n a = self.type_analyzer(\n tvar_scope=tvar_scope,\n allow_unbound_tvars=allow_unbound_tvars,\n allow_tuple_literal=allow_tuple_literal,\n allow_placeholder=allow_placeholder,\n allow_typed_dict_special_forms=allow_typed_dict_special_forms,\n allow_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 allow_type_any=allow_type_any,\n )\n tag = self.track_incomplete_refs()\n typ = typ.accept(a)\n if self.found_incomplete_ref(tag):\n # Something could not be bound yet.\n return None\n self.add_type_alias_deps(a.aliases_used)\n return typ\n\n def class_type(self, self_type: Type) -> Type:\n return TypeType.make_normalized(self_type)\n\n def schedule_patch(self, priority: int, patch: Callable[[], None]) -> None:\n self.patches.append((priority, patch))\n\n def report_hang(self) -> None:\n print(\"Deferral trace:\")\n for mod, line in self.deferral_debug_context:\n print(f\" {mod}:{line}\")\n self.errors.report(\n -1,\n -1,\n \"INTERNAL ERROR: maximum semantic analysis iteration count reached\",\n blocker=True,\n )\n\n def add_plugin_dependency(self, trigger: str, target: str | None = None) -> None:\n \"\"\"Add dependency from trigger to a target.\n\n If the target is not given explicitly, use the current target.\n \"\"\"\n if target is None:\n target = self.scope.current_target()\n self.cur_mod_node.plugin_deps.setdefault(trigger, set()).add(target)\n\n def add_type_alias_deps(\n self, aliases_used: Collection[str], target: str | None = None\n ) -> None:\n \"\"\"Add full names of type aliases on which the current node depends.\n\n This is used by fine-grained incremental mode to re-check the corresponding nodes.\n If `target` is None, then the target node used will be the current scope.\n \"\"\"\n if not aliases_used:\n # 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\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 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/semanal.py","language":"Python","license":"NOASSERTION","size":326393} {"code":"\"\"\"Calculate some properties of classes.\n\nThese happen after semantic analysis and before type checking.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Final\n\nfrom mypy.errors import Errors\nfrom mypy.nodes import (\n IMPLICITLY_ABSTRACT,\n IS_ABSTRACT,\n CallExpr,\n Decorator,\n FuncDef,\n Node,\n OverloadedFuncDef,\n PromoteExpr,\n SymbolTable,\n TypeInfo,\n Var,\n)\nfrom mypy.options import Options\nfrom mypy.types import MYPYC_NATIVE_INT_NAMES, Instance, ProperType\n\n# Hard coded type promotions (shared between all Python versions).\n# These add extra ad-hoc edges to the subtyping relation. For example,\n# int is considered a subtype of float, even though there is no\n# subclass relationship.\n# Note that the bytearray -> bytes promotion is a little unsafe\n# as some functions only accept bytes objects. Here convenience\n# trumps safety.\nTYPE_PROMOTIONS: Final = {\n \"builtins.int\": \"float\",\n \"builtins.float\": \"complex\",\n \"builtins.bytearray\": \"bytes\",\n \"builtins.memoryview\": \"bytes\",\n}\n\n\ndef calculate_class_abstract_status(typ: TypeInfo, is_stub_file: bool, errors: Errors) -> None:\n \"\"\"Calculate abstract status of a class.\n\n Set is_abstract of the type to True if the type has an unimplemented\n abstract attribute. Also compute a list of abstract attributes.\n Report error is required ABCMeta metaclass is missing.\n \"\"\"\n typ.is_abstract = False\n typ.abstract_attributes = []\n if typ.typeddict_type:\n return # TypedDict can't be abstract\n concrete: set[str] = set()\n # List of abstract attributes together with their abstract status\n abstract: list[tuple[str, int]] = []\n abstract_in_this_class: list[str] = []\n if typ.is_newtype:\n # Special case: NewTypes are considered as always non-abstract, so they can be used as:\n # Config = NewType('Config', Mapping[str, str])\n # default = Config({'cannot': 'modify'}) # OK\n return\n for base in typ.mro:\n for name, symnode in base.names.items():\n node = symnode.node\n if isinstance(node, OverloadedFuncDef):\n # Unwrap an overloaded function definition. We can just\n # check arbitrarily the first overload item. If the\n # different items have a different abstract status, there\n # should be an error reported elsewhere.\n if node.items: # can be empty for invalid overloads\n func: Node | None = node.items[0]\n else:\n func = None\n else:\n func = node\n if isinstance(func, Decorator):\n func = func.func\n if isinstance(func, FuncDef):\n if (\n func.abstract_status in (IS_ABSTRACT, IMPLICITLY_ABSTRACT)\n and name not in concrete\n ):\n typ.is_abstract = True\n abstract.append((name, func.abstract_status))\n if base is typ:\n abstract_in_this_class.append(name)\n elif isinstance(node, Var):\n if node.is_abstract_var and name not in concrete:\n typ.is_abstract = True\n abstract.append((name, IS_ABSTRACT))\n if base is typ:\n abstract_in_this_class.append(name)\n concrete.add(name)\n # In stubs, abstract classes need to be explicitly marked because it is too\n # easy to accidentally leave a concrete class abstract by forgetting to\n # implement some methods.\n typ.abstract_attributes = sorted(abstract)\n if is_stub_file:\n if typ.declared_metaclass and typ.declared_metaclass.type.has_base(\"abc.ABCMeta\"):\n return\n if typ.is_protocol:\n return\n if abstract and not abstract_in_this_class:\n\n def report(message: str, severity: str) -> None:\n errors.report(typ.line, typ.column, message, severity=severity)\n\n attrs = \", \".join(f'\"{attr}\"' for attr, _ in sorted(abstract))\n report(f\"Class {typ.fullname} has abstract attributes {attrs}\", \"error\")\n report(\n \"If it is meant to be abstract, add 'abc.ABCMeta' as an explicit metaclass\", \"note\"\n )\n if typ.is_final and abstract:\n attrs = \", \".join(f'\"{attr}\"' for attr, _ in sorted(abstract))\n errors.report(\n typ.line, typ.column, f\"Final class {typ.fullname} has abstract attributes {attrs}\"\n )\n\n\ndef check_protocol_status(info: TypeInfo, errors: Errors) -> None:\n \"\"\"Check that all classes in MRO of a protocol are protocols\"\"\"\n if info.is_protocol:\n for type in info.bases:\n if not type.type.is_protocol and type.type.fullname != \"builtins.object\":\n errors.report(\n info.line,\n info.column,\n \"All bases of a protocol must be protocols\",\n severity=\"error\",\n )\n\n\ndef calculate_class_vars(info: TypeInfo) -> None:\n \"\"\"Try to infer additional class variables.\n\n Subclass attribute assignments with no type annotation are assumed\n to be classvar if overriding a declared classvar from the base\n class.\n\n This must happen after the main semantic analysis pass, since\n this depends on base class bodies having been fully analyzed.\n \"\"\"\n for name, sym in info.names.items():\n node = sym.node\n if isinstance(node, Var) and node.info and node.is_inferred and not node.is_classvar:\n for base in info.mro[1:]:\n member = base.names.get(name)\n if member is not None and isinstance(member.node, Var) and member.node.is_classvar:\n node.is_classvar = True\n\n\ndef add_type_promotion(\n info: TypeInfo, module_names: SymbolTable, options: Options, builtin_names: SymbolTable\n) -> None:\n \"\"\"Setup extra, ad-hoc subtyping relationships between classes (promotion).\n\n This includes things like 'int' being compatible with 'float'.\n \"\"\"\n defn = info.defn\n promote_targets: list[ProperType] = []\n for decorator in defn.decorators:\n if isinstance(decorator, CallExpr):\n analyzed = decorator.analyzed\n if isinstance(analyzed, PromoteExpr):\n # _promote class decorator (undocumented feature).\n promote_targets.append(analyzed.type)\n if not promote_targets:\n if defn.fullname in TYPE_PROMOTIONS:\n target_sym = module_names.get(TYPE_PROMOTIONS[defn.fullname])\n if defn.fullname == \"builtins.bytearray\" and options.disable_bytearray_promotion:\n target_sym = None\n elif defn.fullname == \"builtins.memoryview\" and options.disable_memoryview_promotion:\n target_sym = None\n # With test stubs, the target may not exist.\n if target_sym:\n target_info = target_sym.node\n assert isinstance(target_info, TypeInfo)\n promote_targets.append(Instance(target_info, []))\n # Special case the promotions between 'int' and native integer types.\n # These have promotions going both ways, such as from 'int' to 'i64'\n # and 'i64' to 'int', for convenience.\n if defn.fullname in MYPYC_NATIVE_INT_NAMES:\n int_sym = builtin_names[\"int\"]\n assert isinstance(int_sym.node, TypeInfo)\n int_sym.node._promote.append(Instance(defn.info, []))\n defn.info.alt_promote = Instance(int_sym.node, [])\n if promote_targets:\n defn.info._promote.extend(promote_targets)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/semanal_classprop.py","language":"Python","license":"NOASSERTION","size":7673} {"code":"\"\"\"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 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 ENUM_REMOVED_PROPS, 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 *ENUM_REMOVED_PROPS,\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 var._fullname = f\"{info.fullname}.{item}\"\n info.names[item] = SymbolTableNode(MDEF, var)\n return info\n\n def parse_enum_call_args(\n self, call: CallExpr, class_name: str\n ) -> tuple[str, list[str], list[Expression | None], bool]:\n \"\"\"Parse arguments of an Enum call.\n\n Return a tuple of fields, values, was there an error.\n \"\"\"\n args = call.args\n if not all(arg_kind in [ARG_POS, ARG_NAMED] for arg_kind in call.arg_kinds):\n return self.fail_enum_call_arg(f\"Unexpected arguments to {class_name}()\", call)\n if len(args) < 2:\n return self.fail_enum_call_arg(f\"Too few arguments for {class_name}()\", call)\n if len(args) > 6:\n return self.fail_enum_call_arg(f\"Too many arguments for {class_name}()\", call)\n valid_name = [None, \"value\", \"names\", \"module\", \"qualname\", \"type\", \"start\"]\n for arg_name in call.arg_names:\n if arg_name not in valid_name:\n self.fail_enum_call_arg(f'Unexpected keyword argument \"{arg_name}\"', call)\n value, names = None, None\n for arg_name, arg in zip(call.arg_names, args):\n if arg_name == \"value\":\n value = arg\n if arg_name == \"names\":\n names = arg\n if value is None:\n value = args[0]\n if names is None:\n names = args[1]\n if not isinstance(value, StrExpr):\n return self.fail_enum_call_arg(\n f\"{class_name}() expects a string literal as the first argument\", call\n )\n new_class_name = value.value\n\n items = []\n values: list[Expression | None] = []\n if isinstance(names, StrExpr):\n fields = names.value\n for field in fields.replace(\",\", \" \").split():\n items.append(field)\n elif isinstance(names, (TupleExpr, ListExpr)):\n seq_items = names.items\n if is_StrExpr_list(seq_items):\n items = [seq_item.value for seq_item in seq_items]\n elif all(\n isinstance(seq_item, (TupleExpr, ListExpr))\n and len(seq_item.items) == 2\n and isinstance(seq_item.items[0], StrExpr)\n for seq_item in seq_items\n ):\n for seq_item in seq_items:\n assert isinstance(seq_item, (TupleExpr, ListExpr))\n name, value = seq_item.items\n assert isinstance(name, StrExpr)\n items.append(name.value)\n values.append(value)\n else:\n return self.fail_enum_call_arg(\n \"%s() with tuple or list expects strings or (name, value) pairs\" % class_name,\n call,\n )\n elif isinstance(names, DictExpr):\n for key, value in names.items:\n if not isinstance(key, StrExpr):\n return self.fail_enum_call_arg(\n f\"{class_name}() with dict literal requires string literals\", call\n )\n items.append(key.value)\n values.append(value)\n elif isinstance(args[1], RefExpr) and isinstance(args[1].node, Var):\n proper_type = get_proper_type(args[1].node.type)\n if (\n proper_type is not None\n and isinstance(proper_type, LiteralType)\n and isinstance(proper_type.value, str)\n ):\n fields = proper_type.value\n for field in fields.replace(\",\", \" \").split():\n items.append(field)\n elif args[1].node.is_final and isinstance(args[1].node.final_value, str):\n fields = args[1].node.final_value\n for field in fields.replace(\",\", \" \").split():\n items.append(field)\n else:\n return self.fail_enum_call_arg(\n \"Second argument of %s() must be string, tuple, list or dict literal for mypy to determine Enum members\"\n % class_name,\n call,\n )\n else:\n # TODO: Allow dict(x=1, y=2) as a substitute for {'x': 1, 'y': 2}?\n return self.fail_enum_call_arg(\n \"Second argument of %s() must be string, tuple, list or dict literal for mypy to determine Enum members\"\n % class_name,\n call,\n )\n if not items:\n return self.fail_enum_call_arg(f\"{class_name}() needs at least one item\", call)\n if not values:\n values = [None] * len(items)\n assert len(items) == len(values)\n return new_class_name, items, values, True\n\n def fail_enum_call_arg(\n self, message: str, context: Context\n ) -> tuple[str, list[str], list[Expression | None], bool]:\n self.fail(message, context)\n return \"\", [], [], False\n\n # Helpers\n\n def fail(self, msg: str, ctx: Context) -> None:\n self.api.fail(msg, ctx)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/semanal_enum.py","language":"Python","license":"NOASSERTION","size":9706} {"code":"\"\"\"Simple type inference for decorated functions during semantic analysis.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy.nodes import ARG_POS, CallExpr, Decorator, Expression, FuncDef, RefExpr, Var\nfrom mypy.semanal_shared import SemanticAnalyzerInterface\nfrom mypy.typeops import function_type\nfrom mypy.types import (\n AnyType,\n CallableType,\n ProperType,\n Type,\n TypeOfAny,\n TypeVarType,\n get_proper_type,\n)\nfrom mypy.typevars import has_no_typevars\n\n\ndef infer_decorator_signature_if_simple(\n dec: Decorator, analyzer: SemanticAnalyzerInterface\n) -> None:\n \"\"\"Try to infer the type of the decorated function.\n\n This lets us resolve additional references to decorated functions\n during type checking. Otherwise the type might not be available\n when we need it, since module top levels can't be deferred.\n\n This basically uses a simple special-purpose type inference\n engine just for decorators.\n \"\"\"\n if dec.var.is_property:\n # Decorators are expected to have a callable type (it's a little odd).\n 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(\"builtins.function\"))\n if dec.decorators:\n return_type = calculate_return_type(dec.decorators[0])\n if return_type and isinstance(return_type, AnyType):\n # The outermost decorator will return Any so we know the type of the\n # decorated function.\n dec.var.type = AnyType(TypeOfAny.from_another_any, source_any=return_type)\n sig = find_fixed_callable_return(dec.decorators[0])\n if sig:\n # The outermost decorator always returns the same kind of function,\n # so we know that this is the type of the decorated function.\n orig_sig = function_type(dec.func, analyzer.named_type(\"builtins.function\"))\n sig.name = orig_sig.items[0].name\n dec.var.type = sig\n\n\ndef is_identity_signature(sig: Type) -> bool:\n \"\"\"Is type a callable of form T -> T (where T is a type variable)?\"\"\"\n sig = get_proper_type(sig)\n if isinstance(sig, CallableType) and sig.arg_kinds == [ARG_POS]:\n if isinstance(sig.arg_types[0], TypeVarType) and isinstance(sig.ret_type, TypeVarType):\n return sig.arg_types[0].id == sig.ret_type.id\n return False\n\n\ndef calculate_return_type(expr: Expression) -> ProperType | None:\n \"\"\"Return the return type if we can calculate it.\n\n This only uses information available during semantic analysis so this\n will sometimes return None because of insufficient information (as\n type inference hasn't run yet).\n \"\"\"\n if isinstance(expr, RefExpr):\n if isinstance(expr.node, FuncDef):\n typ = expr.node.type\n if typ is None:\n # No signature -> default to Any.\n return AnyType(TypeOfAny.unannotated)\n # Explicit Any return?\n if isinstance(typ, CallableType):\n return get_proper_type(typ.ret_type)\n return None\n elif isinstance(expr.node, Var):\n return get_proper_type(expr.node.type)\n elif isinstance(expr, CallExpr):\n return calculate_return_type(expr.callee)\n return None\n\n\ndef find_fixed_callable_return(expr: Expression) -> CallableType | None:\n \"\"\"Return the return type, if expression refers to a callable that returns a callable.\n\n But only do this if the return type has no type variables. Return None otherwise.\n This approximates things a lot as this is supposed to be called before type checking\n when full type information is not available yet.\n \"\"\"\n if isinstance(expr, RefExpr):\n if isinstance(expr.node, FuncDef):\n typ = expr.node.type\n if typ:\n if isinstance(typ, CallableType) and has_no_typevars(typ.ret_type):\n ret_type = get_proper_type(typ.ret_type)\n if isinstance(ret_type, CallableType):\n return ret_type\n elif isinstance(expr, CallExpr):\n t = find_fixed_callable_return(expr.callee)\n if t:\n ret_type = get_proper_type(t.ret_type)\n if isinstance(ret_type, CallableType):\n return ret_type\n return None\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/semanal_infer.py","language":"Python","license":"NOASSERTION","size":5180} {"code":"\"\"\"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, List, Optional, Tuple, 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/semanal_main.py","language":"Python","license":"NOASSERTION","size":20521} {"code":"\"\"\"Semantic analysis of named tuple definitions.\n\nThis is conceptually part of mypy.semanal.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport keyword\nfrom contextlib import contextmanager\nfrom typing import Container, Final, Iterator, List, Mapping, 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 has_type_vars,\n)\nfrom mypy.util import get_unique_redefinition_name\n\n# Matches \"_prohibited\" in typing.py, but adds __annotations__, which works at runtime but can't\n# easily be supported in a static checker.\nNAMEDTUPLE_PROHIBITED_NAMES: Final = (\n \"__new__\",\n \"__init__\",\n \"__slots__\",\n \"__getnewargs__\",\n \"_fields\",\n \"_field_defaults\",\n \"_field_types\",\n \"_make\",\n \"_replace\",\n \"_asdict\",\n \"_source\",\n \"__annotations__\",\n)\n\nNAMEDTUP_CLASS_ERROR: Final = (\n 'Invalid statement in NamedTuple definition; expected \"field_name: field_type [= default]\"'\n)\n\nSELF_TVAR_NAME: Final = \"_NT\"\n\n\nclass NamedTupleAnalyzer:\n def __init__(\n self, options: Options, api: SemanticAnalyzerInterface, msg: MessageBuilder\n ) -> None:\n self.options = options\n self.api = api\n self.msg = msg\n\n def analyze_namedtuple_classdef(\n self, defn: ClassDef, is_stub_file: bool, is_func_scope: bool\n ) -> tuple[bool, TypeInfo | None]:\n \"\"\"Analyze if given class definition can be a named tuple definition.\n\n Return a tuple where first item indicates whether this can possibly be a named tuple,\n and the second item is the corresponding TypeInfo (may be None if not ready and should be\n deferred).\n \"\"\"\n for base_expr in defn.base_type_exprs:\n if isinstance(base_expr, RefExpr):\n self.api.accept(base_expr)\n if base_expr.fullname in TYPED_NAMEDTUPLE_NAMES:\n result = self.check_namedtuple_classdef(defn, is_stub_file)\n if result is None:\n # This is a valid named tuple, but some types are incomplete.\n return True, None\n items, types, default_items, statements = result\n if is_func_scope and \"@\" not in defn.name:\n defn.name += \"@\" + str(defn.line)\n existing_info = None\n if isinstance(defn.analyzed, NamedTupleExpr):\n existing_info = defn.analyzed.info\n info = self.build_namedtuple_typeinfo(\n defn.name, items, types, default_items, defn.line, existing_info\n )\n defn.analyzed = NamedTupleExpr(info, is_typed=True)\n defn.analyzed.line = defn.line\n defn.analyzed.column = defn.column\n defn.defs.body = statements\n # All done: this is a valid named tuple with all types known.\n return True, info\n # This can't be a valid named tuple.\n return False, None\n\n def check_namedtuple_classdef(\n self, defn: ClassDef, is_stub_file: bool\n ) -> tuple[list[str], list[Type], dict[str, Expression], list[Statement]] | None:\n \"\"\"Parse and validate fields in named tuple class definition.\n\n Return a four tuple:\n * field names\n * field types\n * field default values\n * valid statements\n or None, if any of the types are not ready.\n \"\"\"\n if len(defn.base_type_exprs) > 1:\n self.fail(\"NamedTuple should be a single base\", defn)\n items: list[str] = []\n types: list[Type] = []\n default_items: dict[str, Expression] = {}\n statements: list[Statement] = []\n for stmt in defn.defs.body:\n statements.append(stmt)\n if not isinstance(stmt, AssignmentStmt):\n # Still allow pass or ... (for empty namedtuples).\n if isinstance(stmt, PassStmt) or (\n isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, EllipsisExpr)\n ):\n continue\n # Also allow methods, including decorated ones.\n if isinstance(stmt, (Decorator, FuncBase)):\n continue\n # And docstrings.\n if isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, StrExpr):\n continue\n statements.pop()\n defn.removed_statements.append(stmt)\n self.fail(NAMEDTUP_CLASS_ERROR, stmt)\n elif len(stmt.lvalues) > 1 or not isinstance(stmt.lvalues[0], NameExpr):\n # An assignment, but an invalid one.\n statements.pop()\n defn.removed_statements.append(stmt)\n self.fail(NAMEDTUP_CLASS_ERROR, stmt)\n else:\n # Append name and type in this case...\n name = stmt.lvalues[0].name\n items.append(name)\n if stmt.type is None:\n types.append(AnyType(TypeOfAny.unannotated))\n else:\n # We never allow recursive types at function scope. Although it is\n # possible to support this for named tuples, it is still tricky, and\n # it would be inconsistent with type aliases.\n analyzed = self.api.anal_type(\n stmt.type,\n allow_placeholder=not self.api.is_func_scope(),\n prohibit_self_type=\"NamedTuple item type\",\n )\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 'Boolean literal expected as the \"rename\" argument to '\n f\"{type_name}()\",\n arg,\n code=ARG_TYPE,\n )\n if call.arg_kinds[:2] != [ARG_POS, ARG_POS]:\n self.fail(f'Unexpected arguments to \"{type_name}()\"', call)\n return None\n if not isinstance(args[0], StrExpr):\n self.fail(f'\"{type_name}()\" expects a string literal as the first argument', call)\n return None\n typename = args[0].value\n types: list[Type] = []\n tvar_defs = []\n if not isinstance(args[1], (ListExpr, TupleExpr)):\n if fullname == \"collections.namedtuple\" and isinstance(args[1], StrExpr):\n str_expr = args[1]\n items = str_expr.value.replace(\",\", \" \").split()\n else:\n self.fail(\n 'List or tuple literal expected as the second argument to \"{}()\"'.format(\n type_name\n ),\n call,\n )\n return None\n else:\n listexpr = args[1]\n if fullname == \"collections.namedtuple\":\n # The fields argument contains just names, with implicit Any types.\n if not is_StrExpr_list(listexpr.items):\n self.fail('String literal expected as \"namedtuple()\" item', call)\n return None\n items = [item.value for item in listexpr.items]\n else:\n type_exprs = [\n t.items[1]\n for t in listexpr.items\n if isinstance(t, TupleExpr) and len(t.items) == 2\n ]\n tvar_defs = self.api.get_and_bind_all_tvars(type_exprs)\n # The fields argument contains (name, type) tuples.\n result = self.parse_namedtuple_fields_with_types(listexpr.items, call)\n if result is None:\n # One of the types is not ready, defer.\n return None\n items, types, _, ok = result\n if not ok:\n return [], [], [], typename, [], False\n if not types:\n types = [AnyType(TypeOfAny.unannotated) for _ in items]\n processed_items = []\n seen_names: set[str] = set()\n for i, item in enumerate(items):\n problem = self.check_namedtuple_field_name(item, seen_names)\n if problem is None:\n processed_items.append(item)\n seen_names.add(item)\n else:\n if not rename:\n self.fail(f'\"{type_name}()\" {problem}', call)\n # Even if rename=False, we pretend that it is True.\n # At runtime namedtuple creation would throw an error;\n # applying the rename logic means we create a more sensible\n # namedtuple.\n new_name = f\"_{i}\"\n processed_items.append(new_name)\n seen_names.add(new_name)\n\n if len(defaults) > len(items):\n self.fail(f'Too many defaults given in call to \"{type_name}()\"', call)\n defaults = defaults[: len(items)]\n return processed_items, types, defaults, typename, tvar_defs, True\n\n def parse_namedtuple_fields_with_types(\n self, nodes: list[Expression], context: Context\n ) -> tuple[list[str], list[Type], list[Expression], bool] | None:\n \"\"\"Parse typed named tuple fields.\n\n Return (names, types, defaults, whether types are all ready), or None if error occurred.\n \"\"\"\n items: list[str] = []\n types: list[Type] = []\n for item in nodes:\n if isinstance(item, TupleExpr):\n if len(item.items) != 2:\n self.fail('Invalid \"NamedTuple()\" field definition', item)\n return None\n name, type_node = item.items\n if isinstance(name, StrExpr):\n items.append(name.value)\n else:\n self.fail('Invalid \"NamedTuple()\" field name', item)\n return None\n try:\n type = expr_to_unanalyzed_type(type_node, self.options, self.api.is_stub_file)\n except TypeTranslationError:\n self.fail(\"Invalid field type\", type_node)\n return None\n # We never allow recursive types at function scope.\n analyzed = self.api.anal_type(\n type,\n allow_placeholder=not self.api.is_func_scope(),\n prohibit_self_type=\"NamedTuple item type\",\n )\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/semanal_namedtuple.py","language":"Python","license":"NOASSERTION","size":30934} {"code":"\"\"\"Semantic analysis of NewType definitions.\n\nThis is conceptually part of mypy.semanal (semantic analyzer pass 2).\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy import errorcodes as codes\nfrom mypy.errorcodes import ErrorCode\nfrom mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type\nfrom mypy.messages import MessageBuilder, format_type\nfrom mypy.nodes import (\n ARG_POS,\n MDEF,\n Argument,\n AssignmentStmt,\n Block,\n CallExpr,\n Context,\n FuncDef,\n NameExpr,\n NewTypeExpr,\n PlaceholderNode,\n RefExpr,\n StrExpr,\n SymbolTableNode,\n TypeInfo,\n Var,\n)\nfrom mypy.options import Options\nfrom mypy.semanal_shared import SemanticAnalyzerInterface, has_placeholder\nfrom mypy.typeanal import check_for_explicit_any, has_any_from_unimported_type\nfrom mypy.types import (\n AnyType,\n CallableType,\n Instance,\n NoneType,\n PlaceholderType,\n TupleType,\n Type,\n TypeOfAny,\n get_proper_type,\n)\n\n\nclass NewTypeAnalyzer:\n def __init__(\n self, options: Options, api: SemanticAnalyzerInterface, msg: MessageBuilder\n ) -> None:\n self.options = options\n self.api = api\n self.msg = msg\n\n def process_newtype_declaration(self, s: AssignmentStmt) -> bool:\n \"\"\"Check if s declares a NewType; if yes, store it in symbol table.\n\n Return True if it's a NewType declaration. The current target may be\n deferred as a side effect if the base type is not ready, even if\n the return value is True.\n\n The logic in this function mostly copies the logic for visit_class_def()\n with a single (non-Generic) base.\n \"\"\"\n var_name, call = self.analyze_newtype_declaration(s)\n if var_name is None or call is None:\n return False\n name = var_name\n # OK, now we know this is a NewType. But the base type may be not ready yet,\n # add placeholder as we do for ClassDef.\n\n if self.api.is_func_scope():\n name += \"@\" + str(s.line)\n fullname = self.api.qualified_name(name)\n\n if not call.analyzed or isinstance(call.analyzed, NewTypeExpr) and not call.analyzed.info:\n # Start from labeling this as a future class, as we do for normal ClassDefs.\n placeholder = PlaceholderNode(fullname, s, s.line, becomes_typeinfo=True)\n self.api.add_symbol(var_name, placeholder, s, can_defer=False)\n\n old_type, should_defer = self.check_newtype_args(var_name, call, s)\n old_type = get_proper_type(old_type)\n if not isinstance(call.analyzed, NewTypeExpr):\n call.analyzed = NewTypeExpr(var_name, old_type, line=call.line, column=call.column)\n else:\n call.analyzed.old_type = old_type\n if old_type is None:\n if should_defer:\n # Base type is not ready.\n self.api.defer()\n return True\n\n # Create the corresponding class definition if the aliased type is subtypeable\n assert isinstance(call.analyzed, NewTypeExpr)\n if isinstance(old_type, TupleType):\n newtype_class_info = self.build_newtype_typeinfo(\n name, old_type, old_type.partial_fallback, s.line, call.analyzed.info\n )\n newtype_class_info.update_tuple_type(old_type)\n elif isinstance(old_type, Instance):\n if old_type.type.is_protocol:\n self.fail(\"NewType cannot be used with protocol classes\", s)\n newtype_class_info = self.build_newtype_typeinfo(\n name, old_type, old_type, s.line, call.analyzed.info\n )\n else:\n if old_type is not None:\n message = \"Argument 2 to NewType(...) must be subclassable (got {})\"\n self.fail(\n message.format(format_type(old_type, self.options)),\n s,\n code=codes.VALID_NEWTYPE,\n )\n # Otherwise the error was already reported.\n old_type = AnyType(TypeOfAny.from_error)\n object_type = self.api.named_type(\"builtins.object\")\n newtype_class_info = self.build_newtype_typeinfo(\n name, old_type, object_type, s.line, call.analyzed.info\n )\n newtype_class_info.fallback_to_any = True\n\n check_for_explicit_any(\n old_type, self.options, self.api.is_typeshed_stub_file, self.msg, context=s\n )\n\n if self.options.disallow_any_unimported and has_any_from_unimported_type(old_type):\n self.msg.unimported_type_becomes_any(\"Argument 2 to NewType(...)\", old_type, s)\n\n # If so, add it to the symbol table.\n assert isinstance(call.analyzed, NewTypeExpr)\n # As we do for normal classes, create the TypeInfo only once, then just\n # update base classes on next iterations (to get rid of placeholders there).\n if not call.analyzed.info:\n call.analyzed.info = newtype_class_info\n else:\n call.analyzed.info.bases = newtype_class_info.bases\n self.api.add_symbol(var_name, call.analyzed.info, s)\n if self.api.is_func_scope():\n self.api.add_symbol_skip_local(name, call.analyzed.info)\n newtype_class_info.line = s.line\n return True\n\n def analyze_newtype_declaration(self, s: AssignmentStmt) -> tuple[str | None, CallExpr | None]:\n \"\"\"Return the NewType call expression if `s` is a newtype declaration or None otherwise.\"\"\"\n name, call = None, None\n if (\n len(s.lvalues) == 1\n and isinstance(s.lvalues[0], NameExpr)\n and isinstance(s.rvalue, CallExpr)\n and isinstance(s.rvalue.callee, RefExpr)\n and (s.rvalue.callee.fullname in (\"typing.NewType\", \"typing_extensions.NewType\"))\n ):\n name = s.lvalues[0].name\n\n if s.type:\n self.fail(\"Cannot declare the type of a NewType declaration\", s)\n\n names = self.api.current_symbol_table()\n existing = names.get(name)\n # Give a better error message than generic \"Name already defined\".\n if (\n existing\n and not isinstance(existing.node, PlaceholderNode)\n and not s.rvalue.analyzed\n ):\n self.fail(f'Cannot redefine \"{name}\" as a NewType', s)\n\n # This dummy NewTypeExpr marks the call as sufficiently analyzed; it will be\n # overwritten later with a fully complete NewTypeExpr if there are no other\n # errors with the NewType() call.\n call = s.rvalue\n\n return name, call\n\n def check_newtype_args(\n self, name: str, call: CallExpr, context: Context\n ) -> tuple[Type | None, bool]:\n \"\"\"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 into None.\n if isinstance(old_type, AnyType) and old_type.is_from_error:\n self.fail(msg, context)\n return None, False\n\n return None if has_failed else old_type, should_defer\n\n def build_newtype_typeinfo(\n self,\n name: str,\n old_type: Type,\n base_type: Instance,\n line: int,\n existing_info: TypeInfo | None,\n ) -> TypeInfo:\n info = existing_info or self.api.basic_new_typeinfo(name, base_type, line)\n info.bases = [base_type] # Update in case there were nested placeholders.\n info.is_newtype = True\n\n # Add __init__ method\n args = [\n Argument(Var(\"self\"), NoneType(), None, ARG_POS),\n self.make_argument(\"item\", old_type),\n ]\n signature = CallableType(\n arg_types=[Instance(info, []), old_type],\n arg_kinds=[arg.kind for arg in args],\n arg_names=[\"self\", \"item\"],\n ret_type=NoneType(),\n fallback=self.api.named_type(\"builtins.function\"),\n name=name,\n )\n init_func = FuncDef(\"__init__\", args, Block([]), typ=signature)\n init_func.info = info\n init_func._fullname = info.fullname + \".__init__\"\n if not existing_info:\n updated = True\n else:\n previous_sym = info.names[\"__init__\"].node\n assert isinstance(previous_sym, FuncDef)\n updated = old_type != previous_sym.arguments[1].variable.type\n info.names[\"__init__\"] = SymbolTableNode(MDEF, init_func)\n\n if has_placeholder(old_type):\n self.api.process_placeholder(None, \"NewType base\", info, force_progress=updated)\n return info\n\n # Helpers\n\n def make_argument(self, name: str, type: Type) -> Argument:\n return Argument(Var(name), type, None, ARG_POS)\n\n def fail(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None:\n self.api.fail(msg, ctx, code=code)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/semanal_newtype.py","language":"Python","license":"NOASSERTION","size":10577} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/semanal_pass1.py","language":"Python","license":"NOASSERTION","size":5439} {"code":"\"\"\"Shared definitions used by different parts of semantic analysis.\"\"\"\n\nfrom __future__ import annotations\n\nfrom abc import abstractmethod\nfrom typing import Callable, Final, overload\nfrom typing_extensions import Literal, Protocol\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, name: str) -> SymbolTableNode:\n raise NotImplementedError\n\n @abstractmethod\n def lookup_fully_qualified_or_none(self, name: 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 t: Type,\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 ) -> 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, fn: Callable[[], None]) -> None:\n raise NotImplementedError\n\n @abstractmethod\n def add_symbol_table_node(self, name: str, stnode: 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, n: 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, fully_qualified_name: 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] | Literal[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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/semanal_shared.py","language":"Python","license":"NOASSERTION","size":15513} {"code":"\"\"\"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 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 ctx,\n code=codes.VALID_TYPE,\n )\n self.note(\n INVALID_PARAM_SPEC_LOCATION_NOTE.format(arg.name),\n ctx,\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 ctx,\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 ctx,\n code=codes.TYPE_VAR,\n )\n continue\n else:\n arg_values = [arg]\n if self.check_type_var_values(name, arg_values, tvar.name, tvar.values, ctx):\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 ctx,\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 ctx,\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 self.fail(\n message_registry.INVALID_TYPEVAR_ARG_VALUE.format(name),\n context,\n code=codes.TYPE_VAR,\n )\n else:\n class_name = f'\"{name}\"'\n actual_type_name = f'\"{actual.type.name}\"'\n self.fail(\n message_registry.INCOMPATIBLE_TYPEVAR_VALUE.format(\n arg_name, class_name, actual_type_name\n ),\n context,\n code=codes.TYPE_VAR,\n )\n return is_error\n\n def fail(self, msg: str, context: Context, *, code: ErrorCode | None = None) -> None:\n self.errors.report(context.line, context.column, msg, code=code)\n\n def note(self, msg: str, context: Context, *, code: ErrorCode | None = None) -> None:\n self.errors.report(context.line, context.column, msg, severity=\"note\", code=code)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/semanal_typeargs.py","language":"Python","license":"NOASSERTION","size":12646} {"code":"\"\"\"Semantic analysis of TypedDict definitions.\"\"\"\n\nfrom __future__ import annotations\n\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)\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 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 fields, types, statements, required_keys, readonly_keys = (\n self.analyze_typeddict_classdef_fields(defn)\n )\n if fields 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, fields, 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 keys: list[str] = []\n 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, keys, types, required_keys, readonly_keys, defn\n )\n (new_keys, new_types, new_statements, new_required_keys, new_readonly_keys) = (\n self.analyze_typeddict_classdef_fields(defn, keys)\n )\n if new_keys is None:\n return True, None # Defer\n keys.extend(new_keys)\n types.extend(new_types)\n required_keys.update(new_required_keys)\n readonly_keys.update(new_readonly_keys)\n info = self.build_typeddict_typeinfo(\n defn.name, keys, 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 keys: list[str],\n types: list[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 keys:\n self.fail(TYPEDDICT_OVERRIDE_MERGE.format(key), ctx)\n keys.extend(valid_items.keys())\n types.extend(valid_items.values())\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: list[str] | None = None\n ) -> tuple[list[str] | None, list[Type], 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 * List of keys (or None if found an incomplete reference --> deferral)\n * List of types for each key\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: list[str] = []\n types: list[Type] = []\n statements: list[Statement] = []\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 fields.append(name)\n statements.append(stmt)\n if stmt.unanalyzed_type is None:\n types.append(AnyType(TypeOfAny.unannotated))\n else:\n analyzed = self.api.anal_type(\n stmt.unanalyzed_type,\n allow_typed_dict_special_forms=True,\n allow_placeholder=not self.api.is_func_scope(),\n prohibit_self_type=\"TypedDict item type\",\n )\n if analyzed is None:\n return None, [], [], set(), set() # Need to defer\n types.append(analyzed)\n if not has_placeholder(analyzed):\n stmt.type = self.extract_meta_info(analyzed, stmt)[0]\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 total: bool | None = True\n if \"total\" in defn.keywords:\n total = require_bool_literal_argument(self.api, defn.keywords[\"total\"], \"total\", True)\n if defn.keywords and defn.keywords.keys() != {\"total\"}:\n for_function = ' for \"__init_subclass__\" of \"TypedDict\"'\n for key in defn.keywords:\n if key == \"total\":\n continue\n self.msg.unexpected_keyword_argument_for_function(for_function, key, defn)\n\n res_types = []\n readonly_keys = set()\n required_keys = set()\n for field, t in zip(fields, types):\n typ, required, readonly = self.extract_meta_info(t)\n res_types.append(typ)\n if (total or required is True) and required is not False:\n required_keys.add(field)\n if readonly:\n readonly_keys.add(field)\n\n return fields, res_types, 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, items, types, required_keys, readonly_keys, call.line, 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 )\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 items: list[str],\n types: list[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(\n dict(zip(items, types)), required_keys, readonly_keys, fallback\n )\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/semanal_typeddict.py","language":"Python","license":"NOASSERTION","size":25817} {"code":"","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/server\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"\"\"\"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 typing import Sequence, Tuple, 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 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 )\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 <...> -> ,\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 )\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 (\"\",)\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 \"\"\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_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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/server\/astdiff.py","language":"Python","license":"NOASSERTION","size":20528} {"code":"\"\"\"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 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) # noqa: E721\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_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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/server\/astmerge.py","language":"Python","license":"NOASSERTION","size":20636} {"code":"\"\"\"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 contextlib import contextmanager, nullcontext\nfrom typing import Dict, Iterator, Tuple\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/server\/aststrip.py","language":"Python","license":"NOASSERTION","size":11293} {"code":"\"\"\"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\" -> locations\"):\n\n -> m.f\n -> , 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 '' (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* '' 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* '' 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* '' 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 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\nfrom typing import List\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 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 -> , 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 -> , 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 -> , 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 (\" 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\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/server\/deps.py","language":"Python","license":"NOASSERTION","size":49736} {"code":"\"\"\"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 = \"\"\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/server\/mergecheck.py","language":"Python","license":"NOASSERTION","size":2760} {"code":"\"\"\"Find all objects reachable from a root object.\"\"\"\n\nfrom __future__ import annotations\n\nimport types\nimport weakref\nfrom collections.abc import Iterable\nfrom typing import Final, Iterator, Mapping\n\nmethod_descriptor_type: Final = type(object.__dir__)\nmethod_wrapper_type: Final = type(object().__ne__)\nwrapper_descriptor_type: Final = type(object.__ne__)\n\nFUNCTION_TYPES: Final = (\n types.BuiltinFunctionType,\n types.FunctionType,\n types.MethodType,\n method_descriptor_type,\n wrapper_descriptor_type,\n method_wrapper_type,\n)\n\nATTR_BLACKLIST: Final = {\"__doc__\", \"__name__\", \"__class__\", \"__dict__\"}\n\n# Instances of these types can't have references to other objects\nATOMIC_TYPE_BLACKLIST: Final = {bool, int, float, str, type(None), object}\n\n# Don't look at most attributes of these types\nCOLLECTION_TYPE_BLACKLIST: Final = {list, set, dict, tuple}\n\n# Don't return these objects\nTYPE_BLACKLIST: Final = {weakref.ReferenceType}\n\n\ndef isproperty(o: object, attr: str) -> bool:\n return isinstance(getattr(type(o), attr, None), property)\n\n\ndef get_edge_candidates(o: object) -> Iterator[tuple[object, object]]:\n # use getattr because mypyc expects dict, not mappingproxy\n if \"__getattribute__\" in getattr(type(o), \"__dict__\"): # noqa: B009\n return\n if type(o) not in COLLECTION_TYPE_BLACKLIST:\n for attr in dir(o):\n try:\n if attr not in ATTR_BLACKLIST and hasattr(o, attr) and not isproperty(o, attr):\n e = getattr(o, attr)\n if type(e) not in ATOMIC_TYPE_BLACKLIST:\n yield attr, e\n except AssertionError:\n pass\n if isinstance(o, Mapping):\n yield from o.items()\n elif isinstance(o, Iterable) and not isinstance(o, str):\n for i, e in enumerate(o):\n yield i, e\n\n\ndef get_edges(o: object) -> Iterator[tuple[object, object]]:\n for s, e in get_edge_candidates(o):\n if isinstance(e, FUNCTION_TYPES):\n # We don't want to collect methods, but do want to collect values\n # in closures and self pointers to other objects\n\n if hasattr(e, \"__closure__\"):\n yield (s, \"__closure__\"), e.__closure__\n if hasattr(e, \"__self__\"):\n se = e.__self__\n if se is not o and se is not type(o) and hasattr(s, \"__self__\"):\n yield s.__self__, se\n else:\n if type(e) not in TYPE_BLACKLIST:\n yield s, e\n\n\ndef get_reachable_graph(root: object) -> tuple[dict[int, object], dict[int, tuple[int, object]]]:\n parents = {}\n seen = {id(root): root}\n worklist = [root]\n while worklist:\n o = worklist.pop()\n for s, e in get_edges(o):\n if id(e) in seen:\n continue\n parents[id(e)] = (id(o), s)\n seen[id(e)] = e\n worklist.append(e)\n\n return seen, parents\n\n\ndef get_path(\n o: object, seen: dict[int, object], parents: dict[int, tuple[int, object]]\n) -> list[tuple[object, object]]:\n path = []\n while id(o) in parents:\n pid, attr = parents[id(o)]\n o = seen[pid]\n path.append((attr, o))\n path.reverse()\n return path\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/server\/objgraph.py","language":"Python","license":"NOASSERTION","size":3230} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/server\/subexpr.py","language":"Python","license":"NOASSERTION","size":5202} {"code":"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/server\/target.py","language":"Python","license":"NOASSERTION","size":273} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/server\/trigger.py","language":"Python","license":"NOASSERTION","size":793} {"code":"\"\"\"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 '' 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 typing import Callable, Final, NamedTuple, Sequence, Union\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 (\n core_modules,\n semantic_analysis_for_scc,\n semantic_analysis_for_targets,\n)\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 module_prefix, split_target\n\nMAX_ITER: Final = 1000\n\nSENSITIVE_INTERNAL_MODULES = tuple(core_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 module in SENSITIVE_INTERNAL_MODULES:\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 {''}.\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 = {}\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: SymbolNode | None = modules[module]\n file: MypyFile | None = None\n active_class = None\n for c in components:\n if isinstance(node, TypeInfo):\n active_class = node\n if isinstance(node, MypyFile):\n file = node\n if not isinstance(node, (MypyFile, TypeInfo)) or c not in node.names:\n not_found() # Stale dependency\n return [], None\n # Don't reprocess plugin generated targets. They should get\n # stripped and regenerated when the containing target is\n # reprocessed.\n if node.names[c].plugin_generated:\n return [], None\n node = node.names[c].node\n if isinstance(node, TypeInfo):\n # A ClassDef target covers the body of the class and everything defined\n # within it. To get the body we include the entire surrounding target,\n # typically a module top-level, since we don't support processing class\n # bodies as separate entities for simplicity.\n assert file is not None\n if node.fullname != target:\n # This is a reference to a different TypeInfo, likely due to a stale dependency.\n # Processing them would spell trouble -- for example, we could be refreshing\n # a deserialized TypeInfo with missing attributes.\n not_found()\n return [], None\n result = [FineGrainedDeferredNode(file, None)]\n stale_info: TypeInfo | None = None\n if node.is_protocol:\n stale_info = node\n for name, symnode in node.names.items():\n node = symnode.node\n if isinstance(node, FuncDef):\n method, _ = lookup_target(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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/server\/update.py","language":"Python","license":"NOASSERTION","size":53000} {"code":"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/sharedparse.py","language":"Python","license":"NOASSERTION","size":2102} {"code":"\"\"\"Type inference constraint solving\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections import defaultdict\nfrom typing 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 leafs, 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 = .\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)\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 = . 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/solve.py","language":"Python","license":"NOASSERTION","size":23820} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/split_namespace.py","language":"Python","license":"NOASSERTION","size":1289} {"code":"from __future__ import annotations\n\nfrom contextlib import contextmanager\nfrom typing import Final, Iterator\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=False)\nfind_occurrences: tuple[str, str] | None = None\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/state.py","language":"Python","license":"NOASSERTION","size":824} {"code":"\"\"\"Utilities for calculating and reporting statistics about types.\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nfrom collections import Counter\nfrom contextlib import contextmanager\nfrom typing import Final, Iterator\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/stats.py","language":"Python","license":"NOASSERTION","size":16769} {"code":"\"\"\"Conversion of parse tree nodes to strings.\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport re\nfrom typing import TYPE_CHECKING, Any, Sequence\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.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 = [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 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] = \"\"\n if not a[1]:\n a[1] = \"\"\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/strconv.py","language":"Python","license":"NOASSERTION","size":24325} {"code":"\"\"\"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 typing import Any, Final, MutableMapping, MutableSequence, NamedTuple, Sequence, Tuple\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\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 if self.ret_type else any_val\n if ret_type is not None:\n retfield = \" -> \" + ret_type\n\n prefix = \"async \" if is_async else \"\"\n sig = \"{indent}{prefix}def {name}({args}){ret}:\".format(\n indent=indent, prefix=prefix, name=self.name, args=\", \".join(args), ret=retfield\n )\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 () -> 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 \": \".\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/stubdoc.py","language":"Python","license":"NOASSERTION","size":16804} {"code":"#!\/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 \/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 typing import Final, Iterable, Iterator\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 ListExpr,\n MemberExpr,\n MypyFile,\n NameExpr,\n OpExpr,\n OverloadedFuncDef,\n SetExpr,\n StarExpr,\n Statement,\n StrExpr,\n TempNode,\n TupleExpr,\n TypeInfo,\n UnaryExpr,\n Var,\n)\nfrom mypy.options import Options as MypyOptions\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 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 ) -> None:\n # See parse_options for descriptions of the flags.\n self.pyversion = pyversion\n self.no_import = no_import\n self.inspect = inspect\n self.doc_dir = doc_dir\n self.search_path = search_path\n self.interpreter = interpreter\n self.decointerpreter = interpreter\n self.parse_only = parse_only\n self.ignore_errors = ignore_errors\n self.include_private = include_private\n self.output_dir = output_dir\n self.modules = modules\n self.packages = packages\n self.files = files\n self.verbose = verbose\n self.quiet = quiet\n self.export_less = export_less\n self.include_docstrings = include_docstrings\n\n\nclass StubSource:\n \"\"\"A single source for stub: can be a Python or C module.\n\n A simple extension of BuildSource that also carries the AST and\n the value of __all__ detected at runtime.\n \"\"\"\n\n def __init__(\n self, module: str, path: str | None = None, runtime_all: list[str] | None = None\n ) -> None:\n self.source = BuildSource(path, module, None)\n self.runtime_all = runtime_all\n self.ast: MypyFile | None = None\n\n def __repr__(self) -> str:\n return f\"StubSource({self.source})\"\n\n @property\n def module(self) -> str:\n return self.source.module\n\n @property\n def path(self) -> str | None:\n return self.source.path\n\n\n# What was generated previously in the stub file. We keep track of these to generate\n# nicely formatted output (add empty line between non-empty classes, for example).\nEMPTY: Final = \"EMPTY\"\nFUNC: Final = \"FUNC\"\nCLASS: Final = \"CLASS\"\nEMPTY_CLASS: Final = \"EMPTY_CLASS\"\nVAR: Final = \"VAR\"\nNOT_IN_ALL: Final = \"NOT_IN_ALL\"\n\n# Indicates that we failed to generate a reasonable output\n# for a given node. These should be manually replaced by a user.\n\nERROR_MARKER: Final = \"\"\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]\n return f\"{base}[{index}]\"\n\n def visit_tuple_expr(self, node: TupleExpr) -> str:\n return f\"({', '.join(n.accept(self) for n in node.items)})\"\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\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\ndef find_referenced_names(file: MypyFile) -> set[str]:\n finder = ReferenceFinder()\n file.accept(finder)\n return finder.refs\n\n\ndef is_none_expr(expr: Expression) -> bool:\n return isinstance(expr, NameExpr) and expr.name == \"None\"\n\n\nclass ReferenceFinder(mypy.mixedtraverser.MixedTraverserVisitor):\n \"\"\"Find all name references (both local and global).\"\"\"\n\n # TODO: Filter out local variable and class attribute references\n\n def __init__(self) -> None:\n # Short names of things defined at the top level.\n self.refs: set[str] = set()\n\n def visit_block(self, block: Block) -> None:\n if not block.is_unreachable:\n super().visit_block(block)\n\n def visit_name_expr(self, e: NameExpr) -> None:\n self.refs.add(e.name)\n\n def visit_instance(self, t: Instance) -> None:\n self.add_ref(t.type.name)\n super().visit_instance(t)\n\n def visit_unbound_type(self, t: UnboundType) -> None:\n if t.name:\n self.add_ref(t.name)\n\n def visit_tuple_type(self, t: TupleType) -> None:\n # Ignore fallback\n for item in t.items:\n item.accept(self)\n\n def visit_callable_type(self, t: CallableType) -> None:\n # Ignore fallback\n for arg in t.arg_types:\n arg.accept(self)\n t.ret_type.accept(self)\n\n def add_ref(self, fullname: str) -> None:\n self.refs.add(fullname)\n while \".\" in fullname:\n fullname = fullname.rsplit(\".\", 1)[0]\n self.refs.add(fullname)\n\n\nclass ASTStubGenerator(BaseStubGenerator, mypy.traverser.TraverserVisitor):\n \"\"\"Generate stub text from a mypy AST.\"\"\"\n\n def __init__(\n self,\n _all_: list[str] | None = None,\n include_private: bool = False,\n analyzed: bool = False,\n export_less: bool = False,\n include_docstrings: bool = False,\n ) -> None:\n super().__init__(_all_, include_private, export_less, include_docstrings)\n self._decorators: list[str] = []\n # Stack of defined variables (per scope).\n self._vars: list[list[str]] = [[]]\n # What was generated previously in the stub file.\n self._state = EMPTY\n self._current_class: ClassDef | None = None\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\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 return FunctionSig(func_def.name, args, retname)\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 # implicit Any\n retname = infer_method_ret_type(o.name)\n if retname is not None:\n return retname\n if has_yield_expression(o) or has_yield_from_expression(o):\n generator_name = self.add_name(\"collections.abc.Generator\")\n yield_name = \"None\"\n send_name: str | None = None\n return_name: str | None = None\n if has_yield_from_expression(o):\n yield_name = send_name = self.add_name(\"_typeshed.Incomplete\")\n else:\n for expr, in_assignment in all_yield_expressions(o):\n if expr.expr is not None and not is_none_expr(expr.expr):\n yield_name = self.add_name(\"_typeshed.Incomplete\")\n if in_assignment:\n send_name = self.add_name(\"_typeshed.Incomplete\")\n if has_return_statement(o):\n return_name = self.add_name(\"_typeshed.Incomplete\")\n if return_name is not None:\n if send_name is None:\n send_name = \"None\"\n return f\"{generator_name}[{yield_name}, {send_name}, {return_name}]\"\n elif send_name is not None:\n return f\"{generator_name}[{yield_name}, {send_name}]\"\n else:\n return f\"{generator_name}[{yield_name}]\"\n if not has_return_statement(o) and o.abstract_status == NOT_ABSTRACT:\n return \"None\"\n return None\n\n def _get_func_docstring(self, node: FuncDef) -> str | None:\n if not node.body.body:\n return None\n expr = node.body.body[0]\n if isinstance(expr, ExpressionStmt) and isinstance(expr.expr, StrExpr):\n return expr.expr.value\n return None\n\n def visit_func_def(self, o: FuncDef) -> None:\n is_dataclass_generated = (\n self.analyzed and self.processing_dataclass and o.info.names[o.name].plugin_generated\n )\n if is_dataclass_generated and o.name != \"__init__\":\n # Skip methods generated by the @dataclass decorator (except for __init__)\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 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)\n if init_code:\n self.add(init_code)\n\n if self._current_class is not None:\n if len(o.arguments):\n self_var = o.arguments[0].variable.name\n else:\n self_var = \"self\"\n class_info = ClassInfo(self._current_class.name, self_var)\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 if not isinstance(decorator, (NameExpr, MemberExpr)):\n continue\n qualname = get_qualified_name(decorator)\n fullname = self.get_fullname(decorator)\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\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._current_class = 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 self.add(f\"{self._indent}class {o.name}{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 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.processing_enum = False\n self._current_class = None\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 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 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_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 and 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]] = []\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))\n\n\ndef find_self_initializers(fdef: FuncBase) -> list[tuple[str, Expression]]:\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\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.stdout.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 doc_dir: str = \"\",\n all_modules: list[str],\n) -> None:\n \"\"\"Use analysed (or just parsed) AST to generate type stub for single file.\n\n If directory for target doesn't exist it will created. Existing stub\n will be overwritten.\n \"\"\"\n if inspect:\n ngen = InspectionStubGenerator(\n module_name=mod.module,\n known_modules=all_modules,\n _all_=mod.runtime_all,\n doc_dir=doc_dir,\n include_private=include_private,\n export_less=export_less,\n include_docstrings=include_docstrings,\n )\n ngen.generate_module()\n output = ngen.output()\n\n else:\n gen = ASTStubGenerator(\n mod.runtime_all,\n include_private=include_private,\n analyzed=not parse_only,\n export_less=export_less,\n include_docstrings=include_docstrings,\n )\n assert mod.ast is not None, \"This function must be used only with analyzed modules\"\n mod.ast.accept(gen)\n output = gen.output()\n\n # Write output to file.\n subdir = os.path.dirname(target)\n if subdir and not os.path.isdir(subdir):\n os.makedirs(subdir)\n with open(target, \"w\", encoding=\"utf-8\") as file:\n file.write(output)\n\n\ndef generate_stubs(options: Options) -> None:\n \"\"\"Main entry point for the program.\"\"\"\n mypy_opts = mypy_options(options)\n py_modules, pyc_modules, c_modules = collect_build_targets(options, mypy_opts)\n all_modules = py_modules + pyc_modules + c_modules\n all_module_names = sorted(m.module for m in all_modules)\n # Use parsed sources to generate stubs for Python modules.\n generate_asts_for_modules(py_modules, options.parse_only, mypy_opts, options.verbose)\n files = []\n for mod in py_modules + pyc_modules:\n assert mod.path is not None, \"Not found module was not skipped\"\n target = mod.module.replace(\".\", \"\/\")\n if os.path.basename(mod.path) in [\"__init__.py\", \"__init__.pyc\"]:\n target += \"\/__init__.pyi\"\n else:\n target += \".pyi\"\n target = os.path.join(options.output_dir, target)\n files.append(target)\n with generate_guarded(mod.module, target, options.ignore_errors, options.verbose):\n generate_stub_for_py_module(\n mod,\n target,\n parse_only=options.parse_only,\n inspect=options.inspect or mod in pyc_modules,\n include_private=options.include_private,\n export_less=options.export_less,\n include_docstrings=options.include_docstrings,\n doc_dir=options.doc_dir,\n all_modules=all_module_names,\n )\n\n # Separately analyse C modules using different logic.\n for mod in c_modules:\n if any(py_mod.module.startswith(mod.module + \".\") for py_mod in all_modules):\n target = mod.module.replace(\".\", \"\/\") + \"\/__init__.pyi\"\n else:\n target = mod.module.replace(\".\", \"\/\") + \".pyi\"\n target = os.path.join(options.output_dir, target)\n files.append(target)\n with generate_guarded(mod.module, target, options.ignore_errors, options.verbose):\n generate_stub_for_c_module(\n mod.module,\n target,\n known_modules=all_module_names,\n doc_dir=options.doc_dir,\n include_private=options.include_private,\n export_less=options.export_less,\n include_docstrings=options.include_docstrings,\n )\n num_modules = len(all_modules)\n if not options.quiet and num_modules > 0:\n print(\"Processed %d modules\" % num_modules)\n if len(files) == 1:\n print(f\"Generated {files[0]}\")\n else:\n print(f\"Generated files under {common_dir_prefix(files)}\" + os.sep)\n\n\nHEADER = \"\"\"%(prog)s [-h] [more options, see -h]\n [-m MODULE] [-p PACKAGE] [files ...]\"\"\"\n\nDESCRIPTION = \"\"\"\nGenerate draft stubs for modules.\n\nStubs are generated in directory .\/out, to avoid overriding files with\nmanual changes. This directory is assumed to exist.\n\"\"\"\n\n\ndef parse_options(args: list[str]) -> Options:\n parser = argparse.ArgumentParser(prog=\"stubgen\", usage=HEADER, description=DESCRIPTION)\n\n parser.add_argument(\n \"--ignore-errors\",\n action=\"store_true\",\n help=\"ignore errors when trying to generate stubs for modules\",\n )\n parser.add_argument(\n \"--no-import\",\n action=\"store_true\",\n help=\"don't import the modules, just parse and analyze them \"\n \"(doesn't work with C extension modules and might not \"\n \"respect __all__)\",\n )\n parser.add_argument(\n \"--no-analysis\",\n \"--parse-only\",\n dest=\"parse_only\",\n action=\"store_true\",\n help=\"don't perform semantic analysis of sources, just parse them \"\n \"(only applies to Python modules, might affect quality of stubs. \"\n \"Not compatible with --inspect-mode)\",\n )\n parser.add_argument(\n \"--inspect-mode\",\n dest=\"inspect\",\n action=\"store_true\",\n help=\"import and inspect modules instead of parsing source code.\"\n \"This is the default behavior for c modules and pyc-only packages, but \"\n \"it is also useful for pure python modules with dynamically generated members.\",\n )\n parser.add_argument(\n \"--include-private\",\n action=\"store_true\",\n help=\"generate stubs for objects and members considered private \"\n \"(single leading underscore and no trailing underscores)\",\n )\n parser.add_argument(\n \"--export-less\",\n action=\"store_true\",\n help=\"don't implicitly export all names imported from other modules in the same package\",\n )\n parser.add_argument(\n \"--include-docstrings\",\n action=\"store_true\",\n help=\"include existing docstrings with the stubs\",\n )\n parser.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"show more verbose messages\")\n parser.add_argument(\"-q\", \"--quiet\", action=\"store_true\", help=\"show fewer messages\")\n parser.add_argument(\n \"--doc-dir\",\n metavar=\"PATH\",\n default=\"\",\n help=\"use .rst documentation in PATH (this may result in \"\n \"better stubs in some cases; consider setting this to \"\n \"DIR\/Python-X.Y.Z\/Doc\/library)\",\n )\n parser.add_argument(\n \"--search-path\",\n metavar=\"PATH\",\n default=\"\",\n help=\"specify module search directories, separated by ':' \"\n \"(currently only used if --no-import is given)\",\n )\n parser.add_argument(\n \"-o\",\n \"--output\",\n metavar=\"PATH\",\n dest=\"output_dir\",\n default=\"out\",\n help=\"change the output directory [default: %(default)s]\",\n )\n parser.add_argument(\n \"-m\",\n \"--module\",\n action=\"append\",\n metavar=\"MODULE\",\n dest=\"modules\",\n default=[],\n help=\"generate stub for module; can repeat for more modules\",\n )\n parser.add_argument(\n \"-p\",\n \"--package\",\n action=\"append\",\n metavar=\"PACKAGE\",\n dest=\"packages\",\n default=[],\n help=\"generate stubs for package recursively; can be repeated\",\n )\n parser.add_argument(\n metavar=\"files\",\n nargs=\"*\",\n dest=\"files\",\n help=\"generate stubs for given files or directories\",\n )\n parser.add_argument(\n \"--version\", action=\"version\", version=\"%(prog)s \" + mypy.version.__version__\n )\n\n ns = parser.parse_args(args)\n\n pyversion = sys.version_info[:2]\n ns.interpreter = sys.executable\n\n if ns.modules + ns.packages and ns.files:\n parser.error(\"May only specify one of: modules\/packages or files.\")\n if ns.quiet and ns.verbose:\n parser.error(\"Cannot specify both quiet and verbose messages\")\n if ns.inspect and ns.parse_only:\n parser.error(\"Cannot specify both --parse-only\/--no-analysis and --inspect-mode\")\n\n # Create the output folder if it doesn't already exist.\n os.makedirs(ns.output_dir, exist_ok=True)\n\n return Options(\n pyversion=pyversion,\n no_import=ns.no_import,\n inspect=ns.inspect,\n doc_dir=ns.doc_dir,\n search_path=ns.search_path.split(\":\"),\n interpreter=ns.interpreter,\n ignore_errors=ns.ignore_errors,\n parse_only=ns.parse_only,\n include_private=ns.include_private,\n output_dir=ns.output_dir,\n modules=ns.modules,\n packages=ns.packages,\n files=ns.files,\n verbose=ns.verbose,\n quiet=ns.quiet,\n export_less=ns.export_less,\n include_docstrings=ns.include_docstrings,\n )\n\n\ndef main(args: list[str] | None = None) -> None:\n mypy.util.check_python_version(\"stubgen\")\n # Make sure that the current directory is in sys.path so that\n # stubgen can be run on packages in the current directory.\n if not (\"\" in sys.path or \".\" in sys.path):\n sys.path.insert(0, \"\")\n\n options = parse_options(sys.argv[1:] if args is None else args)\n generate_stubs(options)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/stubgen.py","language":"Python","license":"NOASSERTION","size":73497} {"code":"#!\/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 types import FunctionType, ModuleType\nfrom typing import Any, Callable, Mapping\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)\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 ()\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:\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 ) -> None:\n self.doc_dir = doc_dir\n if module is None:\n self.module = importlib.import_module(module_name)\n else:\n self.module = module\n self.is_c_module = is_c_module(self.module)\n self.known_modules = known_modules\n self.resort_members = self.is_c_module\n super().__init__(_all_, include_private, export_less, include_docstrings)\n self.module_name = module_name\n if self.is_c_module:\n # Add additional implicit imports.\n # C-extensions are given more lattitude 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__\") # noqa: B009\n results = []\n for name in obj_dict:\n if self.is_skipped_attribute(name):\n continue\n # Try to get the value via getattr\n try:\n value = getattr(obj, name)\n except AttributeError:\n continue\n else:\n results.append((name, value))\n return results\n\n def get_type_annotation(self, obj: object) -> str:\n \"\"\"\n Given an instance, return a string representation of its type that is valid\n to use as a type annotation.\n \"\"\"\n if obj is None or obj is type(None):\n return \"None\"\n elif inspect.isclass(obj):\n return f\"type[{self.get_type_fullname(obj)}]\"\n elif isinstance(obj, FunctionType):\n return self.add_name(\"typing.Callable\")\n elif isinstance(obj, ModuleType):\n return self.add_name(\"types.ModuleType\", require=False)\n else:\n return self.get_type_fullname(type(obj))\n\n def is_function(self, obj: object) -> bool:\n if self.is_c_module:\n return inspect.isbuiltin(obj)\n else:\n return inspect.isfunction(obj)\n\n def is_method(self, class_info: ClassInfo, name: str, obj: object) -> bool:\n if self.is_c_module:\n return inspect.ismethoddescriptor(obj) or type(obj) in (\n type(str.index),\n type(str.__add__),\n type(str.__new__),\n )\n else:\n # this is valid because it is only called on members of a class\n return inspect.isfunction(obj)\n\n def is_classmethod(self, class_info: ClassInfo, name: str, obj: object) -> bool:\n if self.is_c_module:\n return inspect.isbuiltin(obj) or type(obj).__name__ in (\n \"classmethod\",\n \"classmethod_descriptor\",\n )\n else:\n return inspect.ismethod(obj)\n\n def is_staticmethod(self, class_info: ClassInfo | None, name: str, obj: object) -> bool:\n if class_info is None:\n return False\n elif self.is_c_module:\n raw_lookup: Mapping[str, Any] = getattr(class_info.cls, \"__dict__\") # noqa: B009\n raw_value = raw_lookup.get(name, obj)\n return isinstance(raw_value, staticmethod)\n else:\n return isinstance(inspect.getattr_static(class_info.cls, name), staticmethod)\n\n @staticmethod\n def is_abstract_method(obj: object) -> bool:\n return getattr(obj, \"__abstractmethod__\", False)\n\n @staticmethod\n def is_property(class_info: ClassInfo, name: str, obj: object) -> bool:\n return inspect.isdatadescriptor(obj) or hasattr(obj, \"fget\")\n\n @staticmethod\n def is_property_readonly(prop: Any) -> bool:\n return hasattr(prop, \"fset\") and prop.fset is None\n\n def is_static_property(self, obj: object) -> bool:\n \"\"\"For c-modules, whether the property behaves like an attribute\"\"\"\n if self.is_c_module:\n # StaticProperty is from boost-python\n return type(obj).__name__ in (\"pybind11_static_property\", \"StaticProperty\")\n else:\n return False\n\n def process_inferred_sigs(self, inferred: list[FunctionSig]) -> None:\n for i, sig in enumerate(inferred):\n for arg in sig.args:\n if arg.type is not None:\n arg.type = self.strip_or_import(arg.type)\n if sig.ret_type is not None:\n inferred[i] = sig._replace(ret_type=self.strip_or_import(sig.ret_type))\n\n def generate_function_stub(\n self, name: str, obj: object, *, output: list[str], class_info: ClassInfo | None = None\n ) -> None:\n \"\"\"Generate stub for a single function or method.\n\n The result (always a single line) will be appended to 'output'.\n If necessary, any required names will be added to 'imports'.\n The 'class_name' is used to find signature of __init__ or __new__ in\n 'class_sigs'.\n \"\"\"\n docstring: Any = getattr(obj, \"__doc__\", None)\n if not isinstance(docstring, str):\n docstring = None\n\n ctx = FunctionContext(\n self.module_name,\n name,\n docstring=docstring,\n is_abstract=self.is_abstract_method(obj),\n class_info=class_info,\n )\n if self.is_private_name(name, ctx.fullname) or self.is_not_in_all(name):\n return\n\n self.record_name(ctx.name)\n default_sig = self.get_default_function_sig(obj, ctx)\n inferred = self.get_signatures(default_sig, self.sig_generators, ctx)\n self.process_inferred_sigs(inferred)\n\n decorators = []\n if len(inferred) > 1:\n decorators.append(\"@{}\".format(self.add_name(\"typing.overload\")))\n\n if ctx.is_abstract:\n decorators.append(\"@{}\".format(self.add_name(\"abc.abstractmethod\")))\n\n if class_info is not None:\n if self.is_staticmethod(class_info, name, obj):\n decorators.append(\"@staticmethod\")\n else:\n for sig in inferred:\n if not sig.args or sig.args[0].name not in (\"self\", \"cls\"):\n sig.args.insert(0, ArgSig(name=class_info.self_var))\n # a sig generator indicates @classmethod by specifying the cls arg.\n if inferred[0].args and inferred[0].args[0].name == \"cls\":\n decorators.append(\"@classmethod\")\n\n 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 if typ is Any: # type: ignore[comparison-overlap]\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(self, class_name: str, cls: type, output: list[str]) -> None:\n \"\"\"Generate stub for a single class using runtime introspection.\n\n The result lines will be appended to 'output'. If necessary, any\n required names will be added to 'imports'.\n \"\"\"\n raw_lookup: Mapping[str, Any] = getattr(cls, \"__dict__\") # noqa: B009\n items = self.get_members(cls)\n if self.resort_members:\n items = sorted(items, key=lambda x: method_name_sort_key(x[0]))\n names = {x[0] for x in items}\n methods: list[str] = []\n types: list[str] = []\n static_properties: list[str] = []\n rw_properties: list[str] = []\n ro_properties: list[str] = []\n attrs: list[tuple[str, Any]] = []\n\n self.record_name(class_name)\n self.indent()\n\n class_info = ClassInfo(class_name, \"\", getattr(cls, \"__doc__\", None), cls)\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)\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/stubgenc.py","language":"Python","license":"NOASSERTION","size":38314} {"code":"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 approved_stub_package_exists(module: str) -> bool:\n top_level = module.split(\".\", 1)[0]\n if top_level in legacy_bundled_packages:\n return True\n if top_level in non_bundled_packages_flat:\n return True\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 if module in namespace:\n return True\n return False\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 \"boto\": \"types-boto\",\n \"cachetools\": \"types-cachetools\",\n \"click_spinner\": \"types-click-spinner\",\n \"contextvars\": \"types-contextvars\",\n \"croniter\": \"types-croniter\",\n \"dataclasses\": \"types-dataclasses\",\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 \"gflags\": \"types-python-gflags\",\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 \"python2\": \"types-six\",\n \"pytz\": \"types-pytz\",\n \"pyVmomi\": \"types-pyvmomi\",\n \"redis\": \"types-redis\",\n \"requests\": \"types-requests\",\n \"retry\": \"types-retry\",\n \"simplejson\": \"types-simplejson\",\n \"singledispatch\": \"types-singledispatch\",\n \"six\": \"types-six\",\n \"slugify\": \"types-python-slugify\",\n \"tabulate\": \"types-tabulate\",\n \"toml\": \"types-toml\",\n \"typed_ast\": \"types-typed-ast\",\n \"tzlocal\": \"types-tzlocal\",\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 \"MySQLdb\": \"types-mysqlclient\",\n \"PIL\": \"types-Pillow\",\n \"PyInstaller\": \"types-pyinstaller\",\n \"Xlib\": \"types-python-xlib\",\n \"aws_xray_sdk\": \"types-aws-xray-sdk\",\n \"babel\": \"types-babel\",\n \"braintree\": \"types-braintree\",\n \"bs4\": \"types-beautifulsoup4\",\n \"bugbear\": \"types-flake8-bugbear\",\n \"caldav\": \"types-caldav\",\n \"cffi\": \"types-cffi\",\n \"chevron\": \"types-chevron\",\n \"colorama\": \"types-colorama\",\n \"commonmark\": \"types-commonmark\",\n \"consolemenu\": \"types-console-menu\",\n \"crontab\": \"types-python-crontab\",\n \"d3dshot\": \"types-D3DShot\",\n \"dockerfile_parse\": \"types-dockerfile-parse\",\n \"docopt\": \"types-docopt\",\n \"editdistance\": \"types-editdistance\",\n \"entrypoints\": \"types-entrypoints\",\n \"farmhash\": \"types-pyfarmhash\",\n \"flake8_2020\": \"types-flake8-2020\",\n \"flake8_builtins\": \"types-flake8-builtins\",\n \"flake8_docstrings\": \"types-flake8-docstrings\",\n \"flake8_plugin_utils\": \"types-flake8-plugin-utils\",\n \"flake8_rst_docstrings\": \"types-flake8-rst-docstrings\",\n \"flake8_simplify\": \"types-flake8-simplify\",\n \"flake8_typing_imports\": \"types-flake8-typing-imports\",\n \"flask_cors\": \"types-Flask-Cors\",\n \"flask_migrate\": \"types-Flask-Migrate\",\n \"fpdf\": \"types-fpdf2\",\n \"gdb\": \"types-gdb\",\n \"hdbcli\": \"types-hdbcli\",\n \"html5lib\": \"types-html5lib\",\n \"httplib2\": \"types-httplib2\",\n \"humanfriendly\": \"types-humanfriendly\",\n \"invoke\": \"types-invoke\",\n \"jack\": \"types-JACK-Client\",\n \"jmespath\": \"types-jmespath\",\n \"jose\": \"types-python-jose\",\n \"jsonschema\": \"types-jsonschema\",\n \"keyboard\": \"types-keyboard\",\n \"ldap3\": \"types-ldap3\",\n \"nmap\": \"types-python-nmap\",\n \"oauthlib\": \"types-oauthlib\",\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 \"playsound\": \"types-playsound\",\n \"psutil\": \"types-psutil\",\n \"psycopg2\": \"types-psycopg2\",\n \"pyaudio\": \"types-pyaudio\",\n \"pyautogui\": \"types-PyAutoGUI\",\n \"pycocotools\": \"types-pycocotools\",\n \"pyflakes\": \"types-pyflakes\",\n \"pygments\": \"types-Pygments\",\n \"pyi_splash\": \"types-pyinstaller\",\n \"pynput\": \"types-pynput\",\n \"pythoncom\": \"types-pywin32\",\n \"pythonwin\": \"types-pywin32\",\n \"pyscreeze\": \"types-PyScreeze\",\n \"pysftp\": \"types-pysftp\",\n \"pytest_lazyfixture\": \"types-pytest-lazy-fixture\",\n \"pywintypes\": \"types-pywin32\",\n \"regex\": \"types-regex\",\n \"send2trash\": \"types-Send2Trash\",\n \"slumber\": \"types-slumber\",\n \"stdlib_list\": \"types-stdlib-list\",\n \"stripe\": \"types-stripe\",\n \"toposort\": \"types-toposort\",\n \"tqdm\": \"types-tqdm\",\n \"tree_sitter\": \"types-tree-sitter\",\n \"tree_sitter_languages\": \"types-tree-sitter-languages\",\n \"ttkthemes\": \"types-ttkthemes\",\n \"vobject\": \"types-vobject\",\n \"whatthepatch\": \"types-whatthepatch\",\n \"win32\": \"types-pywin32\",\n \"win32api\": \"types-pywin32\",\n \"win32con\": \"types-pywin32\",\n \"win32com\": \"types-pywin32\",\n \"win32comext\": \"types-pywin32\",\n \"win32gui\": \"types-pywin32\",\n \"xmltodict\": \"types-xmltodict\",\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/stubinfo.py","language":"Python","license":"NOASSERTION","size":7272} {"code":"\"\"\"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 contextlib import redirect_stderr, redirect_stdout\nfrom functools import singledispatch\nfrom pathlib import Path\nfrom typing import AbstractSet, Any, Generic, Iterator, 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, 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: typing_extensions.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 \"\"\n\n\nUNREPRESENTABLE: typing_extensions.Final = Unrepresentable()\n\n\n_formatter: typing_extensions.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 \"leading double underscore\" in self.message\n\n def get_description(self, concise: bool = False) -> str:\n \"\"\"Returns a description of the error.\n\n :param concise: Whether to return a concise, one-line description\n\n \"\"\"\n if concise:\n return _style(self.object_desc, bold=True) + \" \" + self.message\n\n stub_line = None\n stub_file = None\n if not isinstance(self.stub_object, Missing):\n stub_line = self.stub_object.line\n stub_node = get_stub(self.object_path[0])\n if stub_node is not None:\n stub_file = stub_node.path or None\n\n stub_loc_str = \"\"\n if stub_file:\n stub_loc_str += f\" in file {Path(stub_file)}\"\n if stub_line:\n stub_loc_str += f\"{':' if stub_file else ' at line '}{stub_line}\"\n\n runtime_line = None\n runtime_file = None\n if not isinstance(self.runtime_object, Missing):\n try:\n runtime_line = inspect.getsourcelines(self.runtime_object)[1]\n except (OSError, TypeError, SyntaxError):\n pass\n try:\n runtime_file = inspect.getsourcefile(self.runtime_object)\n except TypeError:\n pass\n\n runtime_loc_str = \"\"\n if runtime_file:\n runtime_loc_str += f\" in file {Path(runtime_file)}\"\n if runtime_line:\n runtime_loc_str += f\"{':' if runtime_file else ' at line '}{runtime_line}\"\n\n output = [\n _style(\"error: \", color=\"red\", bold=True),\n _style(self.object_desc, bold=True),\n \" \",\n self.message,\n \"\\n\",\n \"Stub:\",\n _style(stub_loc_str, dim=True),\n \"\\n\",\n _style(self.stub_desc + \"\\n\", color=\"blue\", dim=True),\n \"Runtime:\",\n _style(runtime_loc_str, dim=True),\n \"\\n\",\n _style(self.runtime_desc + \"\\n\", color=\"blue\", dim=True),\n ]\n return \"\".join(output)\n\n\n# ====================\n# Core logic\n# ====================\n\n\ndef silent_import_module(module_name: str) -> types.ModuleType:\n with open(os.devnull, \"w\") as devnull:\n with warnings.catch_warnings(), redirect_stdout(devnull), redirect_stderr(devnull):\n warnings.simplefilter(\"ignore\")\n runtime = importlib.import_module(module_name)\n # Also run the equivalent of `from module import *`\n # This could have the additional effect of loading not-yet-loaded submodules\n # mentioned in __all__\n __import__(module_name, fromlist=[\"*\"])\n return runtime\n\n\ndef test_module(module_name: str) -> Iterator[Error]:\n \"\"\"Tests a given module's stub against introspecting it at runtime.\n\n Requires the stub to have been built already, accomplished by a call to ``build_stubs``.\n\n :param module_name: The module to test\n\n \"\"\"\n stub = get_stub(module_name)\n if stub is None:\n if not is_probably_private(module_name.split(\".\")[-1]):\n runtime_desc = repr(sys.modules[module_name]) if module_name in sys.modules else \"N\/A\"\n yield Error(\n [module_name], \"failed to find stubs\", MISSING, None, runtime_desc=runtime_desc\n )\n return\n\n try:\n runtime = silent_import_module(module_name)\n except KeyboardInterrupt:\n raise\n except BaseException as e:\n note = \"\"\n if isinstance(e, ModuleNotFoundError):\n note = \" Maybe install the runtime package or alter PYTHONPATH?\"\n yield Error(\n [module_name], f\"failed to import.{note} {type(e).__name__}: {e}\", stub, MISSING\n )\n return\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n try:\n yield from verify(stub, runtime, [module_name])\n except Exception as e:\n bottom_frame = list(traceback.walk_tb(e.__traceback__))[-1][0]\n bottom_module = bottom_frame.f_globals.get(\"__name__\", \"\")\n # Pass on any errors originating from stubtest or mypy\n # These can occur expectedly, e.g. StubtestFailure\n if bottom_module == \"__main__\" or bottom_module.split(\".\")[0] == \"mypy\":\n raise\n yield Error(\n [module_name],\n f\"encountered unexpected error, {type(e).__name__}: {e}\",\n stub,\n runtime,\n stub_desc=\"N\/A\",\n runtime_desc=(\n \"This is most likely the fault of something very dynamic in your library. \"\n \"It's also possible this is a bug in stubtest.\\nIf in doubt, please \"\n \"open an issue at https:\/\/github.com\/python\/mypy\\n\\n\"\n + traceback.format_exc().strip()\n ),\n )\n\n\n@singledispatch\ndef verify(\n stub: MaybeMissing[nodes.Node], runtime: MaybeMissing[Any], object_path: list[str]\n) -> Iterator[Error]:\n \"\"\"Entry point for comparing a stub to a runtime object.\n\n We use single dispatch based on the type of ``stub``.\n\n :param stub: The mypy node representing a part of the stub\n :param runtime: The runtime object corresponding to ``stub``\n\n \"\"\"\n yield Error(object_path, \"is an unknown mypy node\", stub, runtime)\n\n\ndef _verify_exported_names(\n object_path: list[str], stub: nodes.MypyFile, runtime_all_as_set: set[str]\n) -> Iterator[Error]:\n # note that this includes the case the stub simply defines `__all__: list[str]`\n assert \"__all__\" in stub.names\n public_names_in_stub = {m for m, o in stub.names.items() if o.module_public}\n names_in_stub_not_runtime = sorted(public_names_in_stub - runtime_all_as_set)\n names_in_runtime_not_stub = sorted(runtime_all_as_set - public_names_in_stub)\n if not (names_in_runtime_not_stub or names_in_stub_not_runtime):\n return\n yield Error(\n object_path + [\"__all__\"],\n (\n \"names exported from the stub do not correspond to the names exported at runtime. \"\n \"This is probably due to things being missing from the stub or an inaccurate `__all__` in the stub\"\n ),\n # Pass in MISSING instead of the stub and runtime objects, as the line numbers aren't very\n # relevant here, and it makes for a prettier error message\n # This means this error will be ignored when using `--ignore-missing-stub`, which is\n # desirable in at least the `names_in_runtime_not_stub` case\n stub_object=MISSING,\n runtime_object=MISSING,\n stub_desc=(f\"Names exported in the stub but not at runtime: {names_in_stub_not_runtime}\"),\n runtime_desc=(\n f\"Names exported at runtime but not in the stub: {names_in_runtime_not_stub}\"\n ),\n )\n\n\n@functools.lru_cache\ndef _module_symbol_table(runtime: types.ModuleType) -> symtable.SymbolTable | None:\n \"\"\"Retrieve the symbol table for the module (or None on failure).\n\n 1) Use inspect to retrieve the source code of the module\n 2) Use symtable to parse the source (and use what symtable knows for its purposes)\n \"\"\"\n try:\n source = inspect.getsource(runtime)\n except (OSError, TypeError, SyntaxError):\n return None\n\n try:\n return symtable.symtable(source, runtime.__name__, \"exec\")\n except SyntaxError:\n return None\n\n\n@verify.register(nodes.MypyFile)\ndef verify_mypyfile(\n stub: nodes.MypyFile, runtime: MaybeMissing[types.ModuleType], object_path: list[str]\n) -> Iterator[Error]:\n if isinstance(runtime, Missing):\n yield Error(object_path, \"is not present at runtime\", stub, runtime)\n return\n if not isinstance(runtime, types.ModuleType):\n 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 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[misc]\n pass\n\n except TypeError:\n # Enum classes are implicitly @final\n if not stub.is_final and not issubclass(runtime, enum.Enum):\n yield Error(\n object_path,\n \"cannot be subclassed at runtime, but isn't marked with @final in the stub\",\n stub,\n runtime,\n stub_desc=repr(stub),\n )\n except Exception:\n # The class probably wants its subclasses to do something special.\n # Examples: ctypes.Array, ctypes._SimpleCData\n pass\n\n # Runtime class might be annotated with `@final`:\n try:\n runtime_final = getattr(runtime, \"__final__\", False)\n except Exception:\n runtime_final = False\n\n if runtime_final and not stub.is_final:\n yield Error(\n object_path,\n \"has `__final__` attribute, but isn't marked with @final in the stub\",\n stub,\n runtime,\n stub_desc=repr(stub),\n )\n\n\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 # 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 != 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 and (\n stub_default != runtime_arg.default\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 or type(stub_default) is not type(runtime_arg.default) # noqa: E721\n )\n ):\n yield (\n f'runtime argument \"{runtime_arg.name}\" '\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 bool(arg.default != 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'(rename with a leading double underscore, i.e. \"__{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 leading double underscore)\"\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: typing_extensions.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: typing_extensions.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 )\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 \"\" 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(\"\", \"...\")\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.AnyType:\n return mypy.types.AnyType(mypy.types.TypeOfAny.unannotated)\n\n if isinstance(\n runtime,\n (types.FunctionType, types.BuiltinFunctionType, types.MethodType, types.BuiltinMethodType),\n ):\n builtins = get_stub(\"builtins\")\n assert builtins is not None\n type_info = builtins.names[\"function\"].node\n assert isinstance(type_info, nodes.TypeInfo)\n fallback = mypy.types.Instance(type_info, [anytype()])\n signature = safe_inspect_signature(runtime)\n if signature:\n arg_types = []\n arg_kinds = []\n arg_names = []\n for arg in signature.parameters.values():\n arg_types.append(anytype())\n arg_names.append(\n None if arg.kind == inspect.Parameter.POSITIONAL_ONLY else arg.name\n )\n has_default = arg.default == inspect.Parameter.empty\n if arg.kind == inspect.Parameter.POSITIONAL_ONLY:\n arg_kinds.append(nodes.ARG_POS if has_default else nodes.ARG_OPT)\n elif arg.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD:\n arg_kinds.append(nodes.ARG_POS if has_default else nodes.ARG_OPT)\n elif arg.kind == inspect.Parameter.KEYWORD_ONLY:\n arg_kinds.append(nodes.ARG_NAMED if has_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\n\n# typeshed added a stub for __main__, but that causes stubtest to check itself\nANNOYING_STDLIB_MODULES: typing_extensions.Final = frozenset(\n {\"antigravity\", \"this\", \"__main__\", \"_ios_support\"}\n)\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\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\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/stubtest.py","language":"Python","license":"NOASSERTION","size":83603} {"code":"\"\"\"Utilities for mypy.stubgen, mypy.stubgenc, and mypy.stubdoc modules.\"\"\"\n\nfrom __future__ import annotations\n\nimport os.path\nimport re\nimport sys\nfrom abc import abstractmethod\nfrom collections import defaultdict\nfrom contextlib import contextmanager\nfrom typing import Final, Iterable, Iterator, Mapping\nfrom typing_extensions import 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.stubdoc import ArgSig, FunctionSig\nfrom mypy.types import AnyType, NoneType, Type, TypeList, TypeStrVisitor, UnboundType, UnionType\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 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 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, name: str, self_var: str, docstring: str | None = None, cls: type | None = None\n ) -> None:\n self.name = name\n self.self_var = self_var\n self.docstring = docstring\n self.cls = cls\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 self._fullname = f\"{self.module_name}.{self.class_info.name}.{self.name}\"\n else:\n self._fullname = f\"{self.module_name}.{self.name}\"\n return self._fullname\n\n\ndef infer_method_ret_type(name: str) -> str | None:\n \"\"\"Infer return types for known special methods\"\"\"\n if name.startswith(\"__\") and name.endswith(\"__\"):\n name = name[2:-2]\n if name in (\"float\", \"bool\", \"bytes\", \"int\", \"complex\", \"str\"):\n return name\n # Note: __eq__ and co may return arbitrary types, but bool is good enough for stubgen.\n elif name in (\"eq\", \"ne\", \"lt\", \"le\", \"gt\", \"ge\", \"contains\"):\n return \"bool\"\n elif name in (\"len\", \"length_hint\", \"index\", \"hash\", \"sizeof\", \"trunc\", \"floor\", \"ceil\"):\n return \"int\"\n elif name in (\"format\", \"repr\"):\n return \"str\"\n elif name in (\"init\", \"setitem\", \"del\", \"delitem\"):\n return \"None\"\n return None\n\n\ndef infer_method_arg_types(\n name: str, self_var: str = \"self\", arg_names: list[str] | None = None\n) -> list[ArgSig] | None:\n \"\"\"Infer argument types for known special methods\"\"\"\n args: list[ArgSig] | None = None\n if name.startswith(\"__\") and name.endswith(\"__\"):\n if arg_names and len(arg_names) >= 1 and arg_names[0] == \"self\":\n arg_names = arg_names[1:]\n\n name = name[2:-2]\n if name == \"exit\":\n if arg_names is None:\n arg_names = [\"type\", \"value\", \"traceback\"]\n if len(arg_names) == 3:\n arg_types = [\n \"type[BaseException] | None\",\n \"BaseException | None\",\n \"types.TracebackType | None\",\n ]\n args = [\n ArgSig(name=arg_name, type=arg_type)\n for arg_name, arg_type in zip(arg_names, arg_types)\n ]\n if args is not None:\n return [ArgSig(name=self_var)] + args\n return None\n\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass SignatureGenerator:\n \"\"\"Abstract base class for extracting a list of FunctionSigs for each function.\"\"\"\n\n def remove_self_type(\n self, inferred: list[FunctionSig] | None, self_var: str\n ) -> list[FunctionSig] | None:\n \"\"\"Remove type annotation from self\/cls argument\"\"\"\n if inferred:\n for signature in inferred:\n if signature.args:\n if signature.args[0].name == self_var:\n signature.args[0].type = None\n return inferred\n\n @abstractmethod\n def get_function_sig(\n self, default_sig: FunctionSig, ctx: FunctionContext\n ) -> list[FunctionSig] | None:\n \"\"\"Return a list of signatures for the given function.\n\n If no signature can be found, return None. If all of the registered SignatureGenerators\n for the stub generator return None, then the default_sig will be used.\n \"\"\"\n pass\n\n @abstractmethod\n def get_property_type(self, default_type: str | None, ctx: FunctionContext) -> str | None:\n \"\"\"Return the type of the given property\"\"\"\n pass\n\n\nclass ImportTracker:\n \"\"\"Record necessary imports during stub generation.\"\"\"\n\n def __init__(self) -> None:\n # module_for['foo'] has the module name where 'foo' was imported from, or None if\n # 'foo' is a module imported directly;\n # direct_imports['foo'] is the module path used when the name 'foo' was added to the\n # namespace.\n # reverse_alias['foo'] is the name that 'foo' had originally when imported with an\n # alias; examples\n # 'from pkg import mod' ==> module_for['mod'] == 'pkg'\n # 'from pkg import mod as m' ==> module_for['m'] == 'pkg'\n # ==> reverse_alias['m'] == 'mod'\n # 'import pkg.mod as m' ==> module_for['m'] == None\n # ==> reverse_alias['m'] == 'pkg.mod'\n # 'import pkg.mod' ==> module_for['pkg'] == None\n # ==> module_for['pkg.mod'] == None\n # ==> direct_imports['pkg'] == 'pkg.mod'\n # ==> direct_imports['pkg.mod'] == 'pkg.mod'\n self.module_for: dict[str, str | None] = {}\n self.direct_imports: dict[str, str] = {}\n self.reverse_alias: dict[str, str] = {}\n\n # required_names is the set of names that are actually used in a type annotation\n self.required_names: set[str] = set()\n\n # Names that should be reexported if they come from another module\n self.reexports: set[str] = set()\n\n def add_import_from(\n self, module: str, names: list[tuple[str, str | None]], require: bool = False\n ) -> None:\n for name, alias in names:\n if alias:\n # 'from {module} import {name} as {alias}'\n self.module_for[alias] = module\n self.reverse_alias[alias] = name\n else:\n # 'from {module} import {name}'\n self.module_for[name] = module\n self.reverse_alias.pop(name, None)\n if require:\n self.require_name(alias or name)\n self.direct_imports.pop(alias or name, None)\n\n def add_import(self, module: str, alias: str | None = None, require: bool = False) -> None:\n if alias:\n # 'import {module} as {alias}'\n assert \".\" not in alias # invalid syntax\n self.module_for[alias] = None\n self.reverse_alias[alias] = module\n if require:\n self.required_names.add(alias)\n else:\n # 'import {module}'\n name = module\n if require:\n self.required_names.add(name)\n # add module and its parent packages\n while name:\n self.module_for[name] = None\n self.direct_imports[name] = module\n self.reverse_alias.pop(name, None)\n name = name.rpartition(\".\")[0]\n\n def require_name(self, name: str) -> None:\n while name not in self.direct_imports and \".\" in name:\n name = name.rsplit(\".\", 1)[0]\n self.required_names.add(name)\n\n def reexport(self, name: str) -> None:\n \"\"\"Mark a given non qualified name as needed in __all__.\n\n This means that in case it comes from a module, it should be\n imported with an alias even if the alias is the same as the name.\n \"\"\"\n self.require_name(name)\n self.reexports.add(name)\n\n def import_lines(self) -> list[str]:\n \"\"\"The list of required import lines (as strings with python code).\n\n In order for a module be included in this output, an identifier must be both\n 'required' via require_name() and 'imported' via add_import_from()\n or add_import()\n \"\"\"\n result = []\n\n # To summarize multiple names imported from a same module, we collect those\n # in the `module_map` dictionary, mapping a module path to the list of names that should\n # be imported from it. the names can also be alias in the form 'original as alias'\n module_map: Mapping[str, list[str]] = defaultdict(list)\n\n for name in sorted(\n self.required_names,\n key=lambda n: (self.reverse_alias[n], n) if n in self.reverse_alias else (n, \"\"),\n ):\n # If we haven't seen this name in an import statement, ignore it\n if name not in self.module_for:\n continue\n\n m = self.module_for[name]\n if m is not None:\n # This name was found in a from ... import ...\n # Collect the name in the module_map\n if name in self.reverse_alias:\n name = f\"{self.reverse_alias[name]} as {name}\"\n elif name in self.reexports:\n name = f\"{name} as {name}\"\n module_map[m].append(name)\n else:\n # This name was found in an import ...\n # We can already generate the import line\n if name in self.reverse_alias:\n source = self.reverse_alias[name]\n result.append(f\"import {source} as {name}\\n\")\n elif name in self.reexports:\n assert \".\" not in name # Because reexports only has nonqualified names\n result.append(f\"import {name} as {name}\\n\")\n else:\n result.append(f\"import {name}\\n\")\n\n # Now generate all the from ... import ... lines collected in module_map\n for module, names in sorted(module_map.items()):\n result.append(f\"from {module} import {', '.join(sorted(names))}\\n\")\n return result\n\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass BaseStubGenerator:\n # These names should be omitted from generated stubs.\n IGNORED_DUNDERS: Final = {\n \"__all__\",\n \"__author__\",\n \"__about__\",\n \"__copyright__\",\n \"__email__\",\n \"__license__\",\n \"__summary__\",\n \"__title__\",\n \"__uri__\",\n \"__str__\",\n \"__repr__\",\n \"__getstate__\",\n \"__setstate__\",\n \"__slots__\",\n \"__builtins__\",\n \"__cached__\",\n \"__file__\",\n \"__name__\",\n \"__package__\",\n \"__path__\",\n \"__spec__\",\n \"__loader__\",\n }\n TYPING_MODULE_NAMES: Final = (\"typing\", \"typing_extensions\")\n # Special-cased names that are implicitly exported from the stub (from m import y as y).\n EXTRA_EXPORTED: Final = {\n \"pyasn1_modules.rfc2437.univ\",\n \"pyasn1_modules.rfc2459.char\",\n \"pyasn1_modules.rfc2459.univ\",\n }\n\n def __init__(\n self,\n _all_: list[str] | None = None,\n include_private: bool = False,\n export_less: bool = False,\n include_docstrings: bool = False,\n ) -> None:\n # Best known value of __all__.\n self._all_ = _all_\n self._include_private = include_private\n self._include_docstrings = include_docstrings\n # Disable implicit exports of package-internal imports?\n self.export_less = export_less\n self._import_lines: list[str] = []\n self._output: list[str] = []\n # Current indent level (indent is hardcoded to 4 spaces).\n self._indent = \"\"\n self._toplevel_names: list[str] = []\n self.import_tracker = ImportTracker()\n # Top-level members\n self.defined_names: set[str] = set()\n self.sig_generators = self.get_sig_generators()\n # populated by visit_mypy_file\n self.module_name: str = \"\"\n # These are \"soft\" imports for objects which might appear in annotations but not have\n # a corresponding import statement.\n self.known_imports = {\n \"_typeshed\": [\"Incomplete\"],\n \"typing\": [\"Any\", \"TypeVar\", \"NamedTuple\", \"TypedDict\"],\n \"collections.abc\": [\"Generator\"],\n \"typing_extensions\": [\"ParamSpec\", \"TypeVarTuple\"],\n }\n\n def get_sig_generators(self) -> list[SignatureGenerator]:\n return []\n\n def resolve_name(self, name: str) -> str:\n \"\"\"Return the full name resolving imports and import aliases.\"\"\"\n if \".\" not in name:\n real_module = self.import_tracker.module_for.get(name)\n real_short = self.import_tracker.reverse_alias.get(name, name)\n if real_module is None and real_short not in self.defined_names:\n real_module = \"builtins\" # not imported and not defined, must be a builtin\n else:\n name_module, real_short = name.split(\".\", 1)\n real_module = self.import_tracker.reverse_alias.get(name_module, name_module)\n resolved_name = real_short if real_module is None else f\"{real_module}.{real_short}\"\n return resolved_name\n\n def add_name(self, fullname: str, require: bool = True) -> str:\n \"\"\"Add a name to be imported and return the name reference.\n\n The import will be internal to the stub (i.e don't reexport).\n \"\"\"\n module, name = fullname.rsplit(\".\", 1)\n alias = \"_\" + name if name in self.defined_names else None\n while alias in self.defined_names:\n alias = \"_\" + alias\n if module != \"builtins\" or alias: # don't import from builtins unless needed\n self.import_tracker.add_import_from(module, [(name, alias)], require=require)\n return alias or name\n\n def add_import_line(self, line: str) -> None:\n \"\"\"Add a line of text to the import section, unless it's already there.\"\"\"\n if line not in self._import_lines:\n self._import_lines.append(line)\n\n def get_imports(self) -> str:\n \"\"\"Return the import statements for the stub.\"\"\"\n imports = \"\"\n if self._import_lines:\n imports += \"\".join(self._import_lines)\n imports += \"\".join(self.import_tracker.import_lines())\n return imports\n\n def output(self) -> str:\n \"\"\"Return the text for the stub.\"\"\"\n pieces: list[str] = []\n if imports := self.get_imports():\n pieces.append(imports)\n if dunder_all := self.get_dunder_all():\n pieces.append(dunder_all)\n if self._output:\n pieces.append(\"\".join(self._output))\n return \"\\n\".join(pieces)\n\n def get_dunder_all(self) -> str:\n \"\"\"Return the __all__ list for the stub.\"\"\"\n if self._all_:\n # Note we emit all names in the runtime __all__ here, even if they\n # don't actually exist. If that happens, the runtime has a bug, and\n # it's not obvious what the correct behavior should be. We choose\n # to reflect the runtime __all__ as closely as possible.\n return f\"__all__ = {self._all_!r}\\n\"\n return \"\"\n\n def add(self, string: str) -> None:\n \"\"\"Add text to generated stub.\"\"\"\n self._output.append(string)\n\n def is_top_level(self) -> bool:\n \"\"\"Are we processing the top level of a file?\"\"\"\n return self._indent == \"\"\n\n def indent(self) -> None:\n \"\"\"Add one level of indentation.\"\"\"\n self._indent += \" \"\n\n def dedent(self) -> None:\n \"\"\"Remove one level of indentation.\"\"\"\n self._indent = self._indent[:-4]\n\n def record_name(self, name: str) -> None:\n \"\"\"Mark a name as defined.\n\n This only does anything if at the top level of a module.\n \"\"\"\n if self.is_top_level():\n self._toplevel_names.append(name)\n\n def is_recorded_name(self, name: str) -> bool:\n \"\"\"Has this name been recorded previously?\"\"\"\n return self.is_top_level() and name in self._toplevel_names\n\n def set_defined_names(self, defined_names: set[str]) -> None:\n self.defined_names = defined_names\n # Names in __all__ are required\n for name in self._all_ or ():\n self.import_tracker.reexport(name)\n\n for pkg, imports in self.known_imports.items():\n for t in imports:\n # require=False means that the import won't be added unless require_name() is called\n # for the object during generation.\n self.add_name(f\"{pkg}.{t}\", require=False)\n\n def check_undefined_names(self) -> None:\n undefined_names = [name for name in self._all_ or [] if name not in self._toplevel_names]\n if undefined_names:\n if self._output:\n self.add(\"\\n\")\n self.add(\"# Names in __all__ with no definition:\\n\")\n for name in sorted(undefined_names):\n self.add(f\"# {name}\\n\")\n\n def get_signatures(\n self,\n default_signature: FunctionSig,\n sig_generators: list[SignatureGenerator],\n func_ctx: FunctionContext,\n ) -> list[FunctionSig]:\n for sig_gen in sig_generators:\n inferred = sig_gen.get_function_sig(default_signature, func_ctx)\n if inferred:\n return inferred\n\n return [default_signature]\n\n def get_property_type(\n self,\n default_type: str | None,\n sig_generators: list[SignatureGenerator],\n func_ctx: FunctionContext,\n ) -> str | None:\n for sig_gen in sig_generators:\n inferred = sig_gen.get_property_type(default_type, func_ctx)\n if inferred:\n return inferred\n\n return default_type\n\n def format_func_def(\n self,\n sigs: list[FunctionSig],\n is_coroutine: bool = False,\n decorators: list[str] | None = None,\n docstring: str | None = None,\n ) -> list[str]:\n lines: list[str] = []\n if decorators is None:\n decorators = []\n\n for signature in sigs:\n # dump decorators, just before \"def ...\"\n for deco in decorators:\n lines.append(f\"{self._indent}{deco}\")\n\n lines.append(\n signature.format_sig(\n indent=self._indent,\n is_async=is_coroutine,\n docstring=docstring if self._include_docstrings else None,\n )\n )\n return lines\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 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/stubutil.py","language":"Python","license":"NOASSERTION","size":31488} {"code":"from __future__ import annotations\n\nfrom contextlib import contextmanager\nfrom typing import Any, Callable, Final, Iterator, List, 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 LiteralType,\n NoneType,\n NormalizedCallableType,\n Overloaded,\n Parameters,\n ParamSpecType,\n PartialType,\n ProperType,\n TupleType,\n Type,\n TypeAliasType,\n TypedDictType,\n TypeOfAny,\n TypeType,\n TypeVarTupleType,\n TypeVarType,\n TypeVisitor,\n UnboundType,\n UninhabitedType,\n UnionType,\n UnpackType,\n find_unpack_in_list,\n get_proper_type,\n is_named_instance,\n split_with_prefix_and_suffix,\n)\nfrom mypy.types_utils import flatten_types\nfrom mypy.typestate import SubtypeKind, type_state\nfrom mypy.typevars import fill_typevars, fill_typevars_with_any\n\n# Flags for detected protocol members\nIS_SETTABLE: Final = 1\nIS_CLASSVAR: Final = 2\nIS_CLASS_OR_STATIC: Final = 3\nIS_VAR: Final = 4\n\nTypeParameterChecker: _TypeAlias = Callable[[Type, Type, int, bool, \"SubtypeContext\"], bool]\n\n\nclass SubtypeContext:\n def __init__(\n self,\n *,\n # Non-proper subtype flags\n ignore_type_params: bool = False,\n ignore_pos_arg_names: bool = False,\n ignore_declared_variance: bool = False,\n # Supported for both proper and non-proper\n always_covariant: bool = False,\n ignore_promotions: bool = False,\n # Proper subtype flags\n erase_instances: bool = False,\n keep_erased_types: bool = False,\n options: Options | None = None,\n ) -> None:\n self.ignore_type_params = ignore_type_params\n self.ignore_pos_arg_names = ignore_pos_arg_names\n self.ignore_declared_variance = ignore_declared_variance\n self.always_covariant = always_covariant\n self.ignore_promotions = ignore_promotions\n self.erase_instances = erase_instances\n self.keep_erased_types = keep_erased_types\n self.options = options\n\n def check_context(self, proper_subtype: bool) -> None:\n # Historically proper and non-proper subtypes were defined using different helpers\n # and different visitors. Check if flag values are such that we definitely support.\n if proper_subtype:\n assert not self.ignore_pos_arg_names and not self.ignore_declared_variance\n else:\n assert not self.erase_instances and not self.keep_erased_types\n\n\ndef is_subtype(\n left: Type,\n right: Type,\n *,\n subtype_context: SubtypeContext | None = None,\n ignore_type_params: bool = False,\n ignore_pos_arg_names: bool = False,\n ignore_declared_variance: bool = False,\n always_covariant: bool = False,\n ignore_promotions: bool = False,\n options: Options | None = None,\n) -> bool:\n \"\"\"Is 'left' subtype of 'right'?\n\n Also consider Any to be a subtype of any type, and vice versa. This\n recursively applies to components of composite types (List[int] is subtype\n of List[Any], for example).\n\n type_parameter_checker is used to check the type parameters (for example,\n A with B in is_subtype(C[A], C[B]). The default checks for subtype relation\n between the type arguments (e.g., A and B), taking the variance of the\n type var into account.\n \"\"\"\n if 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 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[], 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:\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, CallableType):\n # Special case: Instance can be a subtype of Callable.\n call = find_member(\"__call__\", left, left, is_operator=True)\n if call:\n return self._is_subtype(call, right)\n return False\n else:\n return False\n\n def visit_type_var(self, left: TypeVarType) -> bool:\n right = self.right\n if isinstance(right, TypeVarType) and left.id == right.id:\n 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 not self._is_subtype(left.type_guard, right.type_guard):\n return False\n elif left.type_is is not None and right.type_is is not None:\n # For TypeIs we have to check both ways; it is unsafe to pass\n # a TypeIs[Child] when a TypeIs[Parent] is expected, because\n # if the narrower returns False, we assume that the narrowed value is\n # *not* a Parent.\n if not self._is_subtype(left.type_is, right.type_is) or not self._is_subtype(\n right.type_is, left.type_is\n ):\n return False\n elif right.type_guard is not None and left.type_guard is None:\n # This means that one function has `TypeGuard` and other does not.\n # They are not compatible. See https:\/\/github.com\/python\/mypy\/issues\/11307\n return False\n elif right.type_is is not None and left.type_is is None:\n # Similarly, if one function has `TypeIs` and the other does not,\n # they are not compatible.\n return False\n return is_callable_compatible(\n left,\n right,\n is_compat=self._is_subtype,\n is_proper_subtype=self.proper_subtype,\n ignore_pos_arg_names=self.subtype_context.ignore_pos_arg_names,\n strict_concatenate=(\n (self.options.extra_checks or self.options.strict_concatenate)\n if self.options\n else False\n ),\n )\n elif isinstance(right, Overloaded):\n return all(self._is_subtype(left, item) for item in right.items)\n elif isinstance(right, Instance):\n if right.type.is_protocol and \"__call__\" in right.type.protocol_members:\n # OK, a callable can implement a protocol with a `__call__` member.\n # 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-required key since\n # the prior doesn't support 'del' but the latter should support\n # it.\n #\n # NOTE: 'del' support is currently not implemented (#3550). We\n # don't want to have to change subtyping after 'del' support\n # lands so here we are anticipating that change.\n if (name in left.required_keys) != (name in right.required_keys):\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_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 ignore_names = member != \"__call__\" # __call__ can be passed kwargs\n # The third argument below indicates to what self type is bound.\n # We always bind self to the subtype. (Similarly to nominal types).\n supertype = 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(\n subtype.type,\n [AnyType(TypeOfAny.unannotated)] * len(subtype.type.type_vars),\n )\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(\n subtype, supertype, ignore_pos_arg_names=ignore_names, options=options\n )\n else:\n is_compat = is_proper_subtype(subtype, supertype)\n if not is_compat:\n return False\n if isinstance(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 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 # Non-type cannot be a subtype of type.\n if right.is_type_obj() and not left.is_type_obj() and not allow_partial_overlap:\n return False\n\n # A callable L is a subtype of a generic callable R if L is a\n # subtype of every type obtained from R by substituting types for\n # the variables of R. We can check this by simply leaving the\n # generic variables of R as type variables, effectively varying\n # over all possible values.\n\n # It's okay even if these variables share ids with generic\n # type variables of L, because generating and solving\n # constraints for the variables of L to make L a subtype of R\n # (below) treats type variables on the two sides as independent.\n if left.variables:\n # Apply generic type variables away in left via type inference.\n unified = unify_generic_callable(left, right, ignore_return=ignore_return)\n if unified is None:\n return False\n left = unified\n\n # Check return types.\n if not ignore_return and not is_compat_return(left.ret_type, right.ret_type):\n return False\n\n if check_args_covariantly:\n is_compat = flip_compat_check(is_compat)\n\n if not strict_concatenate and (left.from_concatenate or right.from_concatenate):\n strict_concatenate_check = False\n else:\n strict_concatenate_check = True\n\n return are_parameters_compatible(\n left,\n right,\n is_compat=is_compat,\n is_proper_subtype=is_proper_subtype,\n ignore_pos_arg_names=ignore_pos_arg_names,\n allow_partial_overlap=allow_partial_overlap,\n strict_concatenate_check=strict_concatenate_check,\n )\n\n\ndef are_trivial_parameters(param: Parameters | NormalizedCallableType) -> bool:\n param_star = param.var_arg()\n param_star2 = param.kw_arg()\n return (\n param.arg_kinds == [ARG_STAR, ARG_STAR2]\n and param_star is not None\n and isinstance(get_proper_type(param_star.typ), AnyType)\n and param_star2 is not None\n and isinstance(get_proper_type(param_star2.typ), AnyType)\n )\n\n\ndef is_trivial_suffix(param: Parameters | NormalizedCallableType) -> bool:\n param_star = param.var_arg()\n param_star2 = param.kw_arg()\n return (\n param.arg_kinds[-2:] == [ARG_STAR, ARG_STAR2]\n and param_star is not None\n and isinstance(get_proper_type(param_star.typ), AnyType)\n and param_star2 is not None\n and isinstance(get_proper_type(param_star2.typ), AnyType)\n )\n\n\ndef are_parameters_compatible(\n left: Parameters | NormalizedCallableType,\n right: Parameters | NormalizedCallableType,\n *,\n is_compat: Callable[[Type, Type], bool],\n is_proper_subtype: bool,\n ignore_pos_arg_names: bool = False,\n allow_partial_overlap: bool = False,\n strict_concatenate_check: bool = False,\n) -> bool:\n \"\"\"Helper function for is_callable_compatible, used for Parameter compatibility\"\"\"\n if right.is_ellipsis_args and not is_proper_subtype:\n return True\n\n left_star = left.var_arg()\n left_star2 = left.kw_arg()\n right_star = right.var_arg()\n right_star2 = right.kw_arg()\n\n # Treat \"def _(*a: Any, **kw: Any) -> X\" similarly to \"Callable[..., X]\"\n if are_trivial_parameters(right) and not is_proper_subtype:\n return True\n trivial_suffix = is_trivial_suffix(right) and not is_proper_subtype\n\n 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 if all(k.is_positional() for k in left.arg_kinds) and ignore_pos_arg_names:\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(*args: Any) -> None:\n nonlocal had_errors\n had_errors = True\n\n # This function may be called by the solver, so we need to allow erased types here.\n # We anyway allow checking subtyping between other types containing \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) -> 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)\n for item in p_t.relevant_items()\n if (isinstance(get_proper_type(item), AnyType) or not covers_at_runtime(item, s))\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):\n return UninhabitedType()\n else:\n return t\n\n\ndef covers_at_runtime(item: Type, supertype: Type) -> bool:\n \"\"\"Will isinstance(item, supertype) always return True at runtime?\"\"\"\n item = get_proper_type(item)\n supertype = get_proper_type(supertype)\n\n # Since runtime type checks will ignore type arguments, erase the types.\n supertype = erase_type(supertype)\n if is_proper_subtype(\n erase_type(item), supertype, ignore_promotions=True, erase_instances=True\n ):\n return True\n if isinstance(supertype, Instance):\n if supertype.type.is_protocol:\n # TODO: Implement more robust support for runtime isinstance() checks, see issue #3827.\n if is_proper_subtype(item, supertype, ignore_promotions=True):\n return True\n if isinstance(item, TypedDictType):\n # Special case useful for selecting TypedDicts from unions using isinstance(x, dict).\n if supertype.type.fullname == \"builtins.dict\":\n return True\n elif isinstance(item, TypeVarType):\n if is_proper_subtype(item.upper_bound, supertype, ignore_promotions=True):\n return True\n elif isinstance(item, Instance) and supertype.type.fullname == \"builtins.int\":\n # \"int\" covers all native int types\n if item.type.fullname in MYPYC_NATIVE_INT_NAMES:\n return True\n # TODO: Add more special cases.\n return False\n\n\ndef is_more_precise(left: Type, right: Type, *, ignore_promotions: bool = False) -> bool:\n \"\"\"Check if left is a more precise type than right.\n\n A left is a proper subtype of right, left is also more precise than\n right. Also, if right is Any, left is more precise than right, for\n any left.\n \"\"\"\n # TODO Should List[int] be more precise than List[Any]?\n right = get_proper_type(right)\n if isinstance(right, AnyType):\n return True\n return is_proper_subtype(left, right, ignore_promotions=ignore_promotions)\n\n\ndef all_non_object_members(info: TypeInfo) -> set[str]:\n members = set(info.names)\n for base in info.mro[1:-1]:\n members.update(base.names)\n return members\n\n\ndef infer_variance(info: TypeInfo, i: int) -> bool:\n \"\"\"Infer the variance of the ith type variable of a generic class.\n\n Return True if successful. This can fail if some inferred types aren't ready.\n \"\"\"\n object_type = Instance(info.mro[-1], [])\n\n for variance in COVARIANT, CONTRAVARIANT, INVARIANT:\n tv = info.defn.type_vars[i]\n assert isinstance(tv, TypeVarType)\n if tv.variance != VARIANCE_NOT_READY:\n continue\n tv.variance = variance\n co = True\n contra = True\n tvar = info.defn.type_vars[i]\n self_type = fill_typevars(info)\n for member in all_non_object_members(info):\n # __mypy-replace is an implementation detail of the dataclass plugin\n if member in (\"__init__\", \"__new__\", \"__mypy-replace\"):\n continue\n\n if isinstance(self_type, TupleType):\n self_type = mypy.typeops.tuple_fallback(self_type)\n flags = get_member_flags(member, self_type)\n settable = IS_SETTABLE in flags\n\n node = info[member].node\n if isinstance(node, Var):\n if node.type is None:\n tv.variance = VARIANCE_NOT_READY\n return False\n if has_underscore_prefix(member):\n # Special case to avoid false positives (and to pass conformance tests)\n settable = False\n\n 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/subtypes.py","language":"Python","license":"NOASSERTION","size":92670} {"code":"\"\"\"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 contextlib import contextmanager\nfrom typing import Callable, Iterator, NamedTuple, TypeVar, cast\nfrom typing_extensions import TypedDict\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, , , )\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.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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/suggestions.py","language":"Python","license":"NOASSERTION","size":38070} {"code":"","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"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# 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/config.py","language":"Python","license":"NOASSERTION","size":1160} {"code":"\"\"\"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 dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Any, Final, Iterator, NamedTuple, NoReturn, Pattern, Union\nfrom typing_extensions import TypeAlias as _TypeAlias\n\nimport pytest\n\nfrom mypy import defaults\nfrom mypy.test.config import PREFIX, test_data_prefix, test_temp_dir\n\nroot_dir = os.path.normpath(PREFIX)\n\n# Debuggers that we support for debugging mypyc run tests\n# implementation of using each of these debuggers is in test_run.py\n# TODO: support more debuggers\nSUPPORTED_DEBUGGERS: Final = [\"gdb\", \"lldb\"]\n\n\n# File modify\/create operation: copy module contents from source_path.\nclass UpdateFile(NamedTuple):\n module: str\n content: str\n target_path: str\n\n\n# File delete operation: delete module file.\nclass DeleteFile(NamedTuple):\n module: str\n path: str\n\n\nFileOperation: _TypeAlias = 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 for item in test_items[1:]:\n\n def _item_fail(msg: str) -> NoReturn:\n item_abs_line = case.line + item.line - 2\n pytest.fail(f\"{case.file}:{item_abs_line}: {msg}\", pytrace=False)\n\n if item.id in {\"file\", \"fixture\", \"outfile\", \"outfile-re\"}:\n # Record an extra file needed for the test case.\n assert item.arg is not None\n contents = expand_variables(\"\\n\".join(item.data))\n path = join(base_path, item.arg)\n if item.id != \"fixture\":\n test_modules.append(_file_arg_to_module(item.arg))\n if item.id in {\"file\", \"fixture\"}:\n files.append((path, contents))\n elif item.id == \"outfile-re\":\n output_files.append((path, re.compile(contents.rstrip(), re.S)))\n elif item.id == \"outfile\":\n output_files.append((path, contents))\n elif item.id == \"builtins\":\n # Use an alternative stub file for the builtins module.\n assert item.arg is not None\n mpath = join(os.path.dirname(case.file), item.arg)\n with open(mpath, encoding=\"utf8\") as f:\n files.append((join(base_path, \"builtins.pyi\"), f.read()))\n elif item.id == \"typing\":\n # Use an alternative stub file for the typing module.\n assert item.arg is not None\n src_path = join(os.path.dirname(case.file), item.arg)\n with open(src_path, encoding=\"utf8\") as f:\n files.append((join(base_path, \"typing.pyi\"), f.read()))\n elif item.id == \"_typeshed\":\n # Use an alternative stub file for the _typeshed module.\n assert item.arg is not None\n src_path = join(os.path.dirname(case.file), item.arg)\n with open(src_path, encoding=\"utf8\") as f:\n files.append((join(base_path, \"_typeshed.pyi\"), f.read()))\n elif re.match(r\"stale[0-9]*$\", item.id):\n passnum = 1 if item.id == \"stale\" else int(item.id[len(\"stale\") :])\n assert passnum > 0\n modules = set() if item.arg is None else {t.strip() for t in item.arg.split(\",\")}\n stale_modules[passnum] = modules\n elif re.match(r\"rechecked[0-9]*$\", item.id):\n passnum = 1 if item.id == \"rechecked\" else int(item.id[len(\"rechecked\") :])\n assert passnum > 0\n modules = set() if item.arg is None else {t.strip() for t in item.arg.split(\",\")}\n rechecked_modules[passnum] = modules\n elif re.match(r\"targets[0-9]*$\", item.id):\n passnum = 1 if item.id == \"targets\" else int(item.id[len(\"targets\") :])\n assert passnum > 0\n reprocessed = [] if item.arg is None else [t.strip() for t in item.arg.split(\",\")]\n targets[passnum] = reprocessed\n elif item.id == \"delete\":\n # File\/directory to delete during a multi-step test case\n assert item.arg is not None\n m = re.match(r\"(.*)\\.([0-9]+)$\", item.arg)\n if m is None:\n _item_fail(f\"Invalid delete section {item.arg!r}\")\n num = int(m.group(2))\n if num < 2:\n _item_fail(f\"Can't delete during step {num}\")\n full = join(base_path, m.group(1))\n deleted_paths.setdefault(num, set()).add(full)\n elif re.match(r\"out[0-9]*$\", item.id):\n if item.arg is None:\n args = []\n else:\n args = item.arg.split(\",\")\n\n version_check = True\n for arg in args:\n if arg.startswith(\"version\"):\n compare_op = arg[7:9]\n if compare_op not in {\">=\", \"==\"}:\n _item_fail(\"Only >= and == version checks are currently supported\")\n version_str = arg[9:]\n try:\n version = tuple(int(x) for x in version_str.split(\".\"))\n except ValueError:\n _item_fail(f\"{version_str!r} is not a valid python version\")\n if compare_op == \">=\":\n if version <= defaults.PYTHON3_VERSION:\n _item_fail(\n f\"{arg} always true since minimum runtime version is {defaults.PYTHON3_VERSION}\"\n )\n version_check = sys.version_info >= version\n elif compare_op == \"==\":\n if version < defaults.PYTHON3_VERSION:\n _item_fail(\n f\"{arg} always false since minimum runtime version is {defaults.PYTHON3_VERSION}\"\n )\n if not 1 < len(version) < 4:\n _item_fail(\n f'Only minor or patch version checks are currently supported with \"==\": {version_str!r}'\n )\n version_check = sys.version_info[: len(version)] == version\n if version_check:\n tmp_output = [expand_variables(line) for line in item.data]\n if os.path.sep == \"\\\\\" and case.normalize_output:\n tmp_output = [fix_win_path(line) for line in tmp_output]\n if item.id == \"out\" or item.id == \"out1\":\n output = tmp_output\n else:\n passnum = int(item.id[len(\"out\") :])\n assert passnum > 1\n output2[passnum] = tmp_output\n out_section_missing = False\n elif item.id == \"triggered\" and item.arg is None:\n triggered = item.data\n else:\n section_str = item.id + (f\" {item.arg}\" if item.arg else \"\")\n _item_fail(f\"Invalid section header [{section_str}] in case {case.name!r}\")\n\n if out_section_missing:\n _case_fail(f\"Required output section not found in case {case.name!r}\")\n\n for passnum in stale_modules.keys():\n if passnum not in rechecked_modules:\n # If the set of rechecked modules isn't specified, make it the same as the set\n # of modules with a stale public interface.\n rechecked_modules[passnum] = stale_modules[passnum]\n if (\n passnum in stale_modules\n and passnum in rechecked_modules\n and not stale_modules[passnum].issubset(rechecked_modules[passnum])\n ):\n _case_fail(f\"Stale modules after pass {passnum} must be a subset of rechecked modules\")\n\n output_inline_start = len(output)\n input = first_item.data\n expand_errors(input, output, \"main\")\n for file_path, contents in files:\n expand_errors(contents.split(\"\\n\"), output, file_path)\n\n seen_files = set()\n for file, _ in files:\n if file in seen_files:\n _case_fail(f\"Duplicated filename {file}. Did you include it multiple times?\")\n\n seen_files.add(file)\n\n case.input = input\n case.output = output\n case.output_inline_start = output_inline_start\n case.output2 = output2\n case.last_line = case.line + item.line + len(item.data) - 2\n case.files = files\n case.output_files = output_files\n case.expected_stale_modules = stale_modules\n case.expected_rechecked_modules = rechecked_modules\n case.deleted_paths = deleted_paths\n case.triggered = triggered or []\n case.expected_fine_grained_targets = targets\n case.test_modules = test_modules\n\n\nclass DataDrivenTestCase(pytest.Item):\n \"\"\"Holds parsed data-driven test cases, and handles directory setup and teardown.\"\"\"\n\n # Override parent member type\n parent: 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: tempfile.TemporaryDirectory[str] | None = None\n\n def runtest(self) -> None:\n if self.skip:\n pytest.skip()\n # TODO: add a better error message for when someone uses skip and xfail at the same time\n elif self.xfail:\n self.add_marker(pytest.mark.xfail)\n 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.name))\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.name, 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.TemporaryDirectory(prefix=\"mypy-test-\")\n os.chdir(self.tmpdir.name)\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 try:\n self.tmpdir.cleanup()\n except OSError:\n pass\n self.old_cwd = None\n self.tmpdir = None\n\n def reportinfo(self) -> tuple[str, int, str]:\n return self.file, self.line, self.name\n\n def repr_failure(\n self, excinfo: pytest.ExceptionInfo[BaseException], style: Any | None = None\n ) -> str:\n excrepr: object\n if isinstance(excinfo.value, SystemExit):\n # We assume that before doing exit() (which raises SystemExit) we've printed\n # enough context about what happened so that a stack trace is not useful.\n # In particular, uncaught exceptions during semantic analysis or type checking\n # call exit() and they already print out a stack trace.\n excrepr = excinfo.exconly()\n elif isinstance(excinfo.value, pytest.fail.Exception) and not excinfo.value.pytrace:\n excrepr = excinfo.exconly()\n else:\n excinfo.traceback = self.parent._traceback_filter(excinfo)\n excrepr = excinfo.getrepr(style=\"short\")\n\n return f\"data: {self.file}:{self.line}:\\n{excrepr}\"\n\n def find_steps(self) -> list[list[FileOperation]]:\n \"\"\"Return a list of descriptions of file operations for each incremental step.\n\n The first list item corresponds to the first incremental step, the second for the\n second step, etc. Each operation can either be a file modification\/creation (UpdateFile)\n or deletion (DeleteFile).\n\n Defaults to having two steps if there aern't any operations.\n \"\"\"\n return self.steps\n\n\ndef module_from_path(path: str) -> str:\n path = re.sub(r\"\\.pyi?$\", \"\", path)\n # We can have a mix of Unix-style and Windows-style separators.\n parts = re.split(r\"[\/\\\\]\", path)\n del parts[0]\n module = \".\".join(parts)\n module = re.sub(r\"\\.__init__$\", \"\", module)\n return module\n\n\n@dataclass\nclass TestItem:\n \"\"\"Parsed test caseitem.\n\n An item is of the form\n [id arg]\n .. data ..\n \"\"\"\n\n id: str\n arg: str | None\n # Processed, collapsed text data\n data: list[str]\n # Start line: 1-based, inclusive, relative to testcase\n line: int\n # End line: 1-based, exclusive, relative to testcase; not same as `line + len(test_item.data)` due to collapsing\n end_line: int\n\n @property\n def trimmed_newlines(self) -> int: # compensates for strip_list\n return self.end_line - self.line - len(self.data)\n\n\ndef parse_test_data(raw_data: str, name: str) -> list[TestItem]:\n \"\"\"Parse a list of lines that represent a sequence of test items.\"\"\"\n\n lines = [\"\", \"[case \" + name + \"]\"] + raw_data.split(\"\\n\")\n ret: list[TestItem] = []\n data: list[str] = []\n\n id: str | None = None\n arg: str | None = None\n\n i = 0\n i0 = 0\n while i < len(lines):\n s = lines[i].strip()\n\n if lines[i].startswith(\"[\") and s.endswith(\"]\"):\n if id:\n data = collapse_line_continuation(data)\n data = strip_list(data)\n ret.append(TestItem(id, arg, data, i0 + 1, i))\n\n i0 = i\n id = s[1:-1]\n arg = None\n if \" \" in id:\n arg = id[id.index(\" \") + 1 :]\n id = id[: id.index(\" \")]\n data = []\n elif lines[i].startswith(\"\\\\[\"):\n data.append(lines[i][1:])\n elif not lines[i].startswith(\"--\"):\n data.append(lines[i])\n elif lines[i].startswith(\"----\"):\n data.append(lines[i][2:])\n i += 1\n\n # Process the last item.\n if id:\n data = collapse_line_continuation(data)\n data = strip_list(data)\n ret.append(TestItem(id, arg, data, i0 + 1, i - 1))\n\n return ret\n\n\ndef strip_list(l: list[str]) -> list[str]:\n \"\"\"Return a stripped copy of l.\n\n Strip whitespace at the end of all lines, and strip all empty\n lines from the end of the array.\n \"\"\"\n\n r: list[str] = []\n for s in l:\n # Strip spaces at end of line\n r.append(re.sub(r\"\\s+$\", \"\", s))\n\n while r and r[-1] == \"\":\n r.pop()\n\n return r\n\n\ndef collapse_line_continuation(l: list[str]) -> list[str]:\n r: list[str] = []\n cont = False\n for s in l:\n ss = re.sub(r\"\\\\$\", \"\", s)\n if cont:\n r[-1] += re.sub(\"^ +\", \"\", ss)\n else:\n r.append(ss)\n cont = s.endswith(\"\\\\\")\n return r\n\n\ndef expand_variables(s: str) -> str:\n return s.replace(\"\", root_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\\d+):)? (?P.*)$\", possible_err_comment.strip()\n )\n if m:\n if m.group(1) == \"E\":\n severity = \"error\"\n elif m.group(1) == \"N\":\n severity = \"note\"\n elif m.group(1) == \"W\":\n severity = \"warning\"\n col = m.group(\"col\")\n message = m.group(\"message\")\n message = message.replace(\"\\\\#\", \"#\") # adds back escaped # character\n if col is None:\n output.append(f\"{fnam}:{i + 1}: {severity}: {message}\")\n else:\n output.append(f\"{fnam}:{i + 1}:{col}: {severity}: {message}\")\n\n\ndef fix_win_path(line: str) -> str:\n r\"\"\"Changes Windows paths to Linux paths in error messages.\n\n E.g. foo\\bar.py -> foo\/bar.py.\n \"\"\"\n line = line.replace(root_dir, root_dir.replace(\"\\\\\", \"\/\"))\n m = re.match(r\"^([\\S\/]+):(\\d+:)?(\\s+.*)\", line)\n if not m:\n return line\n else:\n filename, lineno, message = m.groups()\n return \"{}:{}{}\".format(filename.replace(\"\\\\\", \"\/\"), lineno or \"\", message)\n\n\ndef fix_cobertura_filename(line: str) -> str:\n r\"\"\"Changes filename paths to Linux paths in Cobertura output files.\n\n E.g. filename=\"pkg\\subpkg\\a.py\" -> filename=\"pkg\/subpkg\/a.py\".\n \"\"\"\n m = re.search(r'.*?)\"', line)\n if not m:\n return line\n return \"{}{}{}\".format(\n line[: m.start(1)], m.group(\"filename\").replace(\"\\\\\", \"\/\"), line[m.end(1) :]\n )\n\n\n##\n#\n# pytest setup\n#\n##\n\n\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)\n return None\n\n\n_case_name_pattern = re.compile(\n r\"(?P[a-zA-Z_0-9]+)\"\n r\"(?P-writescache)?\"\n r\"(?P-only_when_cache|-only_when_nocache)?\"\n r\"(?P-skip_path_normalization)?\"\n r\"(-(?Pposix|windows))?\"\n r\"(?P-skip)?\"\n r\"(?P-xfail)?\"\n)\n\n\ndef split_test_cases(\n parent: DataFileCollector, suite: DataSuite, file: str\n) -> Iterator[DataDrivenTestCase]:\n \"\"\"Iterate over raw test cases in file, at collection time, ignoring sub items.\n\n The collection phase is slow, so any heavy processing should be deferred to after\n uninteresting tests are filtered (when using -k PATTERN switch).\n \"\"\"\n with open(file, encoding=\"utf-8\") as f:\n data = f.read()\n cases = re.split(r\"^\\[case ([^]+)]+)\\][ \\t]*$\\n\", data, flags=re.DOTALL | re.MULTILINE)\n cases_iter = iter(cases)\n line_no = next(cases_iter).count(\"\\n\") + 1\n test_names = set()\n for case_id in cases_iter:\n data = next(cases_iter)\n\n m = _case_name_pattern.fullmatch(case_id)\n if not m:\n raise RuntimeError(f\"Invalid testcase id {case_id!r}\")\n name = m.group(\"name\")\n if name in test_names:\n raise RuntimeError(\n 'Found a duplicate test name \"{}\" in {} on line {}'.format(\n name, parent.name, line_no\n )\n )\n yield DataDrivenTestCase.from_parent(\n parent=parent,\n suite=suite,\n file=file,\n name=add_test_name_suffix(name, suite.test_name_suffix),\n writescache=bool(m.group(\"writescache\")),\n only_when=m.group(\"only_when\"),\n platform=m.group(\"platform\"),\n skip=bool(m.group(\"skip\")),\n xfail=bool(m.group(\"xfail\")),\n normalize_output=not m.group(\"skip_path_normalization\"),\n data=data,\n line=line_no,\n )\n line_no += data.count(\"\\n\") + 1\n\n # Record existing tests to prevent duplicates:\n test_names.update({name})\n\n\nclass DataSuiteCollector(pytest.Class):\n def collect(self) -> Iterator[DataFileCollector]:\n \"\"\"Called by pytest on each of the object returned from pytest_pycollect_makeitem\"\"\"\n\n # obj is the object for which pytest_pycollect_makeitem returned self.\n suite: DataSuite = self.obj\n\n assert os.path.isdir(\n suite.data_prefix\n ), f\"Test data prefix ({suite.data_prefix}) not set correctly\"\n\n for data_file in suite.files:\n yield DataFileCollector.from_parent(parent=self, name=data_file)\n\n\nclass DataFileFix(NamedTuple):\n lineno: int # 1-offset, inclusive\n end_lineno: int # 1-offset, exclusive\n lines: list[str]\n\n\nclass DataFileCollector(pytest.Collector):\n \"\"\"Represents a single `.test` data driven test file.\n\n More context: https:\/\/github.com\/python\/mypy\/issues\/11662\n \"\"\"\n\n parent: DataSuiteCollector\n\n _fixes: list[DataFileFix]\n\n @classmethod # We have to fight with pytest here:\n def from_parent(\n cls, parent: DataSuiteCollector, *, name: str # type: ignore[override]\n ) -> DataFileCollector:\n collector = super().from_parent(parent, name=name)\n assert isinstance(collector, DataFileCollector)\n return collector\n\n def collect(self) -> Iterator[DataDrivenTestCase]:\n yield from split_test_cases(\n parent=self,\n suite=self.parent.obj,\n file=os.path.join(self.parent.obj.data_prefix, self.name),\n )\n\n def setup(self) -> None:\n super().setup()\n self._fixes = []\n\n def teardown(self) -> None:\n super().teardown()\n self._apply_fixes()\n\n def enqueue_fix(self, fix: DataFileFix) -> None:\n self._fixes.append(fix)\n\n def _apply_fixes(self) -> None:\n if not self._fixes:\n return\n data_path = Path(self.parent.obj.data_prefix) \/ self.name\n lines = data_path.read_text().split(\"\\n\")\n # start from end to prevent line offsets from shifting as we update\n for fix in sorted(self._fixes, reverse=True):\n lines[fix.lineno - 1 : fix.end_lineno - 1] = fix.lines\n data_path.write_text(\"\\n\".join(lines))\n\n\ndef add_test_name_suffix(name: str, suffix: str) -> str:\n # Find magic suffix of form \"-foobar\" (used for things like \"-skip\").\n m = re.search(r\"-[-A-Za-z0-9]+$\", name)\n if m:\n # Insert suite-specific test name suffix before the magic suffix\n # which must be the last thing in the test case name since we\n # are using endswith() checks.\n magic_suffix = m.group(0)\n return name[: -len(magic_suffix)] + suffix + magic_suffix\n else:\n return name + suffix\n\n\ndef is_incremental(testcase: DataDrivenTestCase) -> bool:\n return \"incremental\" in testcase.name.lower() or \"incremental\" in testcase.file\n\n\ndef has_stable_flags(testcase: DataDrivenTestCase) -> bool:\n if any(re.match(r\"# flags[2-9]:\", line) for line in testcase.input):\n return False\n for filename, contents in testcase.files:\n if os.path.basename(filename).startswith(\"mypy.ini.\"):\n return False\n return True\n\n\nclass DataSuite:\n # option fields - class variables\n files: list[str]\n\n base_path = test_temp_dir\n\n # Allow external users of the test code to override the data prefix\n data_prefix = test_data_prefix\n\n required_out_section = False\n\n native_sep = False\n\n # Name suffix automatically added to each test case in the suite (can be\n # used to distinguish test cases in suites that share data files)\n test_name_suffix = \"\"\n\n def setup(self) -> None:\n \"\"\"Setup fixtures (ad-hoc)\"\"\"\n\n @abstractmethod\n def run_case(self, testcase: DataDrivenTestCase) -> None:\n raise NotImplementedError\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/data.py","language":"Python","license":"NOASSERTION","size":29951} {"code":"from __future__ import annotations\n\nimport contextlib\nimport difflib\nimport os\nimport pathlib\nimport re\nimport shutil\nimport sys\nimport time\nfrom typing import IO, Any, Callable, Iterable, Iterator, Pattern\n\n# Exporting Suite as alias to TestCase for backwards compatibility\n# TODO: avoid aliasing - import and subclass TestCase directly\nfrom unittest import TestCase\n\nSuite = TestCase # re-exporting\n\nimport pytest\n\nimport mypy.api as api\nimport mypy.version\nfrom mypy import defaults\nfrom mypy.main import process_options\nfrom mypy.options import Options\nfrom mypy.test.config import test_data_prefix, test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DeleteFile, UpdateFile, fix_cobertura_filename\n\nskip = pytest.mark.skip\n\n# AssertStringArraysEqual displays special line alignment helper messages if\n# the first different line has at least this many characters,\nMIN_LINE_LENGTH_FOR_ALIGNMENT = 5\n\n\ndef run_mypy(args: list[str]) -> None:\n __tracebackhide__ = True\n # We must enable site packages even though they could cause problems,\n # since stubs for typing_extensions live there.\n outval, errval, status = api.run(args + [\"--show-traceback\", \"--no-silence-site-packages\"])\n if status != 0:\n sys.stdout.write(outval)\n sys.stderr.write(errval)\n pytest.fail(reason=\"Sample check failed\", pytrace=False)\n\n\ndef diff_ranges(\n left: list[str], right: list[str]\n) -> tuple[list[tuple[int, int]], list[tuple[int, int]]]:\n seq = difflib.SequenceMatcher(None, left, right)\n # note last triple is a dummy, so don't need to worry\n blocks = seq.get_matching_blocks()\n\n i = 0\n j = 0\n left_ranges = []\n right_ranges = []\n for block in blocks:\n # mismatched range\n left_ranges.append((i, block.a))\n right_ranges.append((j, block.b))\n\n i = block.a + block.size\n j = block.b + block.size\n\n # matched range\n left_ranges.append((block.a, i))\n right_ranges.append((block.b, j))\n return left_ranges, right_ranges\n\n\ndef render_diff_range(\n ranges: list[tuple[int, int]],\n content: list[str],\n *,\n colour: str | None = None,\n output: IO[str] = sys.stderr,\n indent: int = 2,\n) -> None:\n for i, line_range in enumerate(ranges):\n is_matching = i % 2 == 1\n lines = content[line_range[0] : line_range[1]]\n for j, line in enumerate(lines):\n if (\n is_matching\n # elide the middle of matching blocks\n and j >= 3\n and j < len(lines) - 3\n ):\n if j == 3:\n output.write(\" \" * indent + \"...\\n\")\n continue\n\n if not is_matching and colour:\n output.write(colour)\n\n output.write(\" \" * indent + line)\n\n if not is_matching:\n if colour:\n output.write(\"\\033[0m\")\n output.write(\" (diff)\")\n\n output.write(\"\\n\")\n\n\ndef assert_string_arrays_equal(\n expected: list[str], actual: list[str], msg: str, *, traceback: bool = False\n) -> None:\n \"\"\"Assert that two string arrays are equal.\n\n Display any differences in a human-readable form.\n \"\"\"\n actual = clean_up(actual)\n if expected != actual:\n expected_ranges, actual_ranges = diff_ranges(expected, actual)\n sys.stderr.write(\"Expected:\\n\")\n red = \"\\033[31m\" if sys.platform != \"win32\" else None\n render_diff_range(expected_ranges, expected, colour=red)\n sys.stderr.write(\"Actual:\\n\")\n green = \"\\033[32m\" if sys.platform != \"win32\" else None\n render_diff_range(actual_ranges, actual, colour=green)\n\n sys.stderr.write(\"\\n\")\n first_diff = next(\n (i for i, (a, b) in enumerate(zip(expected, actual)) if a != b),\n max(len(expected), len(actual)),\n )\n if 0 <= first_diff < len(actual) and (\n len(expected[first_diff]) >= MIN_LINE_LENGTH_FOR_ALIGNMENT\n or len(actual[first_diff]) >= MIN_LINE_LENGTH_FOR_ALIGNMENT\n ):\n # Display message that helps visualize the differences between two\n # long lines.\n show_align_message(expected[first_diff], actual[first_diff])\n\n sys.stderr.write(\n \"Update the test output using --update-data \"\n \"(implies -n0; you can additionally use the -k selector to update only specific tests)\\n\"\n )\n pytest.fail(msg, pytrace=traceback)\n\n\ndef assert_module_equivalence(name: str, expected: Iterable[str], actual: Iterable[str]) -> None:\n expected_normalized = sorted(expected)\n actual_normalized = sorted(set(actual).difference({\"__main__\"}))\n assert_string_arrays_equal(\n expected_normalized,\n actual_normalized,\n ('Actual modules ({}) do not match expected modules ({}) for \"[{} ...]\"').format(\n \", \".join(actual_normalized), \", \".join(expected_normalized), name\n ),\n )\n\n\ndef assert_target_equivalence(name: str, expected: list[str], actual: list[str]) -> None:\n \"\"\"Compare actual and expected targets (order sensitive).\"\"\"\n assert_string_arrays_equal(\n expected,\n actual,\n ('Actual targets ({}) do not match expected targets ({}) for \"[{} ...]\"').format(\n \", \".join(actual), \", \".join(expected), name\n ),\n )\n\n\ndef show_align_message(s1: str, s2: str) -> None:\n \"\"\"Align s1 and s2 so that the their first difference is highlighted.\n\n For example, if s1 is 'foobar' and s2 is 'fobar', display the\n following lines:\n\n E: foobar\n A: fobar\n ^\n\n If s1 and s2 are long, only display a fragment of the strings around the\n first difference. If s1 is very short, do nothing.\n \"\"\"\n\n # Seeing what went wrong is trivial even without alignment if the expected\n # string is very short. In this case do nothing to simplify output.\n if len(s1) < 4:\n return\n\n maxw = 72 # Maximum number of characters shown\n\n sys.stderr.write(\"Alignment of first line difference:\\n\")\n\n trunc = False\n while s1[:30] == s2[:30]:\n s1 = s1[10:]\n s2 = s2[10:]\n trunc = True\n\n if trunc:\n s1 = \"...\" + s1\n s2 = \"...\" + s2\n\n max_len = max(len(s1), len(s2))\n extra = \"\"\n if max_len > maxw:\n extra = \"...\"\n\n # Write a chunk of both lines, aligned.\n sys.stderr.write(f\" E: {s1[:maxw]}{extra}\\n\")\n sys.stderr.write(f\" A: {s2[:maxw]}{extra}\\n\")\n # Write an indicator character under the different columns.\n sys.stderr.write(\" \")\n for j in range(min(maxw, max(len(s1), len(s2)))):\n if s1[j : j + 1] != s2[j : j + 1]:\n sys.stderr.write(\"^\") # Difference\n break\n else:\n sys.stderr.write(\" \") # Equal\n sys.stderr.write(\"\\n\")\n\n\ndef clean_up(a: list[str]) -> list[str]:\n \"\"\"Remove common directory prefix from all strings in a.\n\n This uses a naive string replace; it seems to work well enough. Also\n remove trailing carriage returns.\n \"\"\"\n res = []\n pwd = os.getcwd()\n driver = pwd + \"\/driver.py\"\n for s in a:\n prefix = os.sep\n ss = s\n for p in prefix, prefix.replace(os.sep, \"\/\"):\n if p != \"\/\" and p != \"\/\/\" and p != \"\\\\\" and p != \"\\\\\\\\\":\n ss = ss.replace(p, \"\")\n # 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\n) -> Options:\n \"\"\"Parse comments like '# flags: --foo' in a test case.\"\"\"\n options = Options()\n flags = re.search(\"# flags: (.*)$\", program_text, flags=re.MULTILINE)\n if incremental_step > 1:\n flags2 = re.search(f\"# flags{incremental_step}: (.*)$\", program_text, flags=re.MULTILINE)\n if flags2:\n flags = flags2\n\n if flags:\n flag_list = flags.group(1).split()\n flag_list.append(\"--no-site-packages\") # the tests shouldn't need an installed Python\n targets, options = process_options(flag_list, require_targets=False)\n if targets:\n # TODO: support specifying targets via the flags pragma\n raise RuntimeError(\"Specifying targets via the flags pragma is not supported.\")\n if \"--show-error-codes\" not in flag_list:\n options.hide_error_codes = True\n else:\n flag_list = []\n options = Options()\n options.error_summary = False\n options.hide_error_codes = True\n options.force_uppercase_builtins = True\n options.force_union_syntax = True\n\n # Allow custom python version to override testfile_pyversion.\n if all(flag.split(\"=\")[0] != \"--python-version\" for flag in flag_list):\n options.python_version = testfile_pyversion(testcase.file)\n\n if testcase.config.getoption(\"--mypy-verbose\"):\n options.verbosity = testcase.config.getoption(\"--mypy-verbose\")\n\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.__version__\n result = [re.sub(r\"\\b\" + re.escape(version) + r\"\\b\", \"$VERSION\", x) for x in result]\n # We generate a new mypy.version when building mypy wheels that\n # lacks base_version, so handle that case.\n base_version = getattr(mypy.version, \"base_version\", version)\n result = [re.sub(r\"\\b\" + re.escape(base_version) + r\"\\b\", \"$VERSION\", x) for x in result]\n result = [timestamp_regex.sub(\"$TIMESTAMP\", x) for x in result]\n return result\n\n\ndef 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/helpers.py","language":"Python","license":"NOASSERTION","size":16067} {"code":"","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/meta\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"import shlex\nimport subprocess\nimport sys\nimport textwrap\nimport uuid\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/meta\/_pytest.py","language":"Python","license":"NOASSERTION","size":2267} {"code":"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/meta\/test_diff_helper.py","language":"Python","license":"NOASSERTION","size":1692} {"code":"\"\"\"\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.8]\n abc\n \"\"\"\n )\n\n # Assert\n assert \"version>=3.8 always true since minimum runtime version is (3, 8)\" 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, 8)\" in actual.stdout\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/meta\/test_parse_data.py","language":"Python","license":"NOASSERTION","size":1931} {"code":"\"\"\"\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/meta\/test_update_data.py","language":"Python","license":"NOASSERTION","size":4814} {"code":"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, file: str) -> bool:\n return file in self.files\n\n def isdir(self, dir: str) -> bool:\n if not dir.endswith(os.sep):\n dir += os.sep\n return any(f.startswith(dir) for f in self.files)\n\n def listdir(self, dir: str) -> list[str]:\n if not dir.endswith(os.sep):\n dir += os.sep\n return list({f[len(dir) :].split(os.sep)[0] for f in self.files if f.startswith(dir)})\n\n def init_under_package_root(self, file: 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/test_find_sources.py","language":"Python","license":"NOASSERTION","size":13684} {"code":"\"\"\"Test exporting line-level reference information (undocumented feature)\"\"\"\n\nfrom __future__ import annotations\n\nimport json\nimport os\nimport sys\n\nfrom mypy import build\nfrom mypy.modulefinder import BuildSource\nfrom mypy.options import Options\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_string_arrays_equal\n\n\nclass RefInfoSuite(DataSuite):\n required_out_section = True\n files = [\"ref-info.test\"]\n\n def run_case(self, testcase: DataDrivenTestCase) -> None:\n options = Options()\n options.use_builtins_fixtures = True\n options.show_traceback = True\n options.export_ref_info = True # This is the flag we are testing\n\n src = \"\\n\".join(testcase.input)\n result = build.build(\n sources=[BuildSource(\"main\", None, src)], options=options, alt_lib_path=test_temp_dir\n )\n assert not result.errors\n\n major, minor = sys.version_info[:2]\n ref_path = os.path.join(options.cache_dir, f\"{major}.{minor}\", \"__main__.refs.json\")\n\n with open(ref_path) as refs_file:\n data = json.load(refs_file)\n\n a = []\n for item in data:\n a.append(f\"{item['line']}:{item['column']}:{item['target']}\")\n\n assert_string_arrays_equal(\n testcase.output, a, f\"Invalid output ({testcase.file}, line {testcase.line})\"\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/test_ref_info.py","language":"Python","license":"NOASSERTION","size":1432} {"code":"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testapi.py","language":"Python","license":"NOASSERTION","size":1447} {"code":"\"\"\"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 options = Options()\n _, parsed_options = process_options([], require_targets=False)\n # FIX: test this too. Requires changing working dir to avoid finding 'setup.cfg'\n options.config_file = parsed_options.config_file\n assert_equal(options.snapshot(), parsed_options.snapshot())\n\n def test_executable_inference(self) -> None:\n \"\"\"Test the --python-executable flag with --python-version\"\"\"\n sys_ver_str = \"{ver.major}.{ver.minor}\".format(ver=sys.version_info)\n\n base = [\"file.py\"] # dummy file\n\n # test inference given one (infer the other)\n matching_version = base + [f\"--python-version={sys_ver_str}\"]\n _, options = process_options(matching_version)\n assert options.python_version == sys.version_info[:2]\n assert options.python_executable == sys.executable\n\n matching_version = base + [f\"--python-executable={sys.executable}\"]\n _, options = process_options(matching_version)\n assert options.python_version == sys.version_info[:2]\n assert options.python_executable == sys.executable\n\n # test inference given both\n matching_version = base + [\n f\"--python-version={sys_ver_str}\",\n f\"--python-executable={sys.executable}\",\n ]\n _, options = process_options(matching_version)\n assert options.python_version == sys.version_info[:2]\n assert options.python_executable == sys.executable\n\n # test that --no-site-packages will disable executable inference\n matching_version = base + [f\"--python-version={sys_ver_str}\", \"--no-site-packages\"]\n _, options = process_options(matching_version)\n assert options.python_version == sys.version_info[:2]\n assert options.python_executable is None\n\n # Test setting python_version\/executable from config file\n special_opts = argparse.Namespace()\n special_opts.python_executable = None\n special_opts.python_version = None\n special_opts.no_executable = None\n\n # first test inferring executable from version\n options = Options()\n options.python_executable = 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testargs.py","language":"Python","license":"NOASSERTION","size":3213} {"code":"\"\"\"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\ntypecheck_files = find_test_files(pattern=\"check-*.test\")\n\n# Tests that use Python version specific features:\nif sys.version_info < (3, 9):\n typecheck_files.remove(\"check-python39.test\")\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\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\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 # Parse options after moving files (in case mypy.ini is being moved).\n options = parse_options(original_program_text, testcase, incremental_step)\n options.use_builtins_fixtures = True\n options.show_traceback = True\n\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:\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 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testcheck.py","language":"Python","license":"NOASSERTION","size":13744} {"code":"\"\"\"Test cases for the command line.\n\nTo begin we test that \"mypy [\/]\" 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 = [\"cmdline.test\", \"cmdline.pyproject.test\", \"reports.test\", \"envvars.test\"]\n\n\nclass PythonCmdlineSuite(DataSuite):\n files = cmdline_files\n native_sep = True\n\n def run_case(self, testcase: DataDrivenTestCase) -> None:\n if lxml is None and os.path.basename(testcase.file) == \"reports.test\":\n pytest.skip(\"Cannot import lxml. Is it installed?\")\n for step in [1] + sorted(testcase.output2):\n test_python_cmdline(testcase, step)\n\n\ndef test_python_cmdline(testcase: DataDrivenTestCase, step: int) -> None:\n assert testcase.old_cwd is not None, \"test was not properly set up\"\n # Write the program to a file.\n program = \"_program.py\"\n program_path = os.path.join(test_temp_dir, program)\n with open(program_path, \"w\", encoding=\"utf8\") as file:\n for s in testcase.input:\n file.write(f\"{s}\\n\")\n args = parse_args(testcase.input[0])\n custom_cwd = parse_cwd(testcase.input[1]) if len(testcase.input) > 1 else None\n args.append(\"--show-traceback\")\n if \"--error-summary\" not in args:\n args.append(\"--no-error-summary\")\n if \"--show-error-codes\" not in args:\n args.append(\"--hide-error-codes\")\n if \"--disallow-empty-bodies\" not in args:\n args.append(\"--allow-empty-bodies\")\n 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 if os.path.isdir(extra_path):\n env[\"PYTHONPATH\"] += os.pathsep + extra_path\n cwd = os.path.join(test_temp_dir, custom_cwd or \"\")\n args = [arg.replace(\"$CWD\", os.path.abspath(cwd)) for arg in args]\n process = subprocess.Popen(\n fixed + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, env=env\n )\n outb, errb = process.communicate()\n result = process.returncode\n # Split output into lines.\n out = [s.rstrip(\"\\n\\r\") for s in str(outb, \"utf8\").splitlines()]\n err = [s.rstrip(\"\\n\\r\") for s in str(errb, \"utf8\").splitlines()]\n\n if \"PYCHARM_HOSTED\" in os.environ:\n for pos, line in enumerate(err):\n if line.startswith(\"pydev debugger: \"):\n # Delete the attaching debugger message itself, plus the extra newline added.\n del err[pos : pos + 2]\n break\n\n # Remove temp file.\n os.remove(program_path)\n # Compare actual output to expected.\n if testcase.output_files:\n # Ignore stdout, but we insist on empty stderr and zero status.\n if err or result:\n raise AssertionError(\n \"Expected zero status and empty stderr%s, got %d and\\n%s\"\n % (\" on step %d\" % step if testcase.output2 else \"\", result, \"\\n\".join(err + out))\n )\n check_test_output_files(testcase, step)\n else:\n if testcase.normalize_output:\n out = normalize_error_messages(err + out)\n obvious_result = 1 if out else 0\n if obvious_result != result:\n out.append(f\"== Return code: {result}\")\n expected_out = testcase.output if step == 1 else testcase.output2[step]\n # Strip \"tmp\/\" out of the test so that # E: works...\n expected_out = [s.replace(\"tmp\" + os.sep, \"\") for s in expected_out]\n assert_string_arrays_equal(\n expected_out,\n out,\n \"Invalid output ({}, line {}){}\".format(\n testcase.file, testcase.line, \" on step %d\" % step if testcase.output2 else \"\"\n ),\n )\n\n\ndef parse_args(line: str) -> list[str]:\n \"\"\"Parse the first line of the program for the command line.\n\n This should have the form\n\n # cmd: mypy \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: \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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testcmdline.py","language":"Python","license":"NOASSERTION","size":5082} {"code":"from __future__ import annotations\n\nfrom mypy.constraints import SUBTYPE_OF, SUPERTYPE_OF, Constraint, infer_constraints\nfrom mypy.test.helpers import Suite\nfrom mypy.test.typefixture import TypeFixture\nfrom mypy.types import Instance, TupleType, UnpackType\n\n\nclass ConstraintsSuite(Suite):\n def setUp(self) -> None:\n self.fx = TypeFixture()\n\n def test_no_type_variables(self) -> None:\n assert not infer_constraints(self.fx.o, self.fx.o, SUBTYPE_OF)\n\n def test_basic_type_variable(self) -> None:\n fx = self.fx\n for direction in [SUBTYPE_OF, SUPERTYPE_OF]:\n assert infer_constraints(fx.gt, fx.ga, direction) == [\n Constraint(type_var=fx.t, op=direction, target=fx.a)\n ]\n\n def test_basic_type_var_tuple_subtype(self) -> None:\n fx = self.fx\n assert infer_constraints(\n Instance(fx.gvi, [UnpackType(fx.ts)]), Instance(fx.gvi, [fx.a, fx.b]), SUBTYPE_OF\n ) == [\n Constraint(type_var=fx.ts, op=SUBTYPE_OF, target=TupleType([fx.a, fx.b], fx.std_tuple))\n ]\n\n def test_basic_type_var_tuple(self) -> None:\n fx = self.fx\n assert set(\n infer_constraints(\n Instance(fx.gvi, [UnpackType(fx.ts)]), Instance(fx.gvi, [fx.a, fx.b]), SUPERTYPE_OF\n )\n ) == {\n Constraint(\n type_var=fx.ts, op=SUPERTYPE_OF, target=TupleType([fx.a, fx.b], fx.std_tuple)\n ),\n Constraint(\n type_var=fx.ts, op=SUBTYPE_OF, target=TupleType([fx.a, fx.b], fx.std_tuple)\n ),\n }\n\n def test_type_var_tuple_with_prefix_and_suffix(self) -> None:\n fx = self.fx\n assert set(\n infer_constraints(\n Instance(fx.gv2i, [fx.t, UnpackType(fx.ts), fx.s]),\n Instance(fx.gv2i, [fx.a, fx.b, fx.c, fx.d]),\n SUPERTYPE_OF,\n )\n ) == {\n Constraint(type_var=fx.t, op=SUPERTYPE_OF, target=fx.a),\n Constraint(\n type_var=fx.ts, op=SUPERTYPE_OF, target=TupleType([fx.b, fx.c], fx.std_tuple)\n ),\n Constraint(\n type_var=fx.ts, op=SUBTYPE_OF, target=TupleType([fx.b, fx.c], fx.std_tuple)\n ),\n Constraint(type_var=fx.s, op=SUPERTYPE_OF, target=fx.d),\n }\n\n def test_unpack_homogenous_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_homogenous_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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testconstraints.py","language":"Python","license":"NOASSERTION","size":5265} {"code":"\"\"\"End-to-end test cases for the daemon (dmypy).\n\nThese are special because they run multiple shell commands.\n\nThis also includes some unit tests.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport subprocess\nimport sys\nimport tempfile\nimport unittest\n\nfrom mypy.dmypy_server import filter_out_missing_top_level_packages\nfrom mypy.fscache import FileSystemCache\nfrom mypy.modulefinder import SearchPaths\nfrom mypy.test.config import PREFIX, test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_string_arrays_equal, normalize_error_messages\n\n# Files containing test cases descriptions.\ndaemon_files = [\"daemon.test\"]\n\n\nclass DaemonSuite(DataSuite):\n files = daemon_files\n\n def run_case(self, testcase: DataDrivenTestCase) -> None:\n try:\n test_daemon(testcase)\n finally:\n # Kill the daemon if it's still running.\n run_cmd(\"dmypy kill\")\n\n\ndef test_daemon(testcase: DataDrivenTestCase) -> None:\n assert testcase.old_cwd is not None, \"test was not properly set up\"\n for i, step in enumerate(parse_script(testcase.input)):\n cmd = step[0]\n expected_lines = step[1:]\n assert cmd.startswith(\"$\")\n cmd = cmd[1:].strip()\n cmd = cmd.replace(\"{python}\", sys.executable)\n sts, output = run_cmd(cmd)\n output_lines = output.splitlines()\n output_lines = normalize_error_messages(output_lines)\n if sts:\n output_lines.append(\"== Return code: %d\" % sts)\n assert_string_arrays_equal(\n expected_lines,\n output_lines,\n \"Command %d (%s) did not give expected output\" % (i + 1, cmd),\n )\n\n\ndef parse_script(input: list[str]) -> list[list[str]]:\n \"\"\"Parse testcase.input into steps.\n\n Each command starts with a line starting with '$'.\n The first line (less '$') is sent to the shell.\n The remaining lines are expected output.\n \"\"\"\n steps = []\n step: list[str] = []\n for line in input:\n if line.startswith(\"$\"):\n if step:\n assert step[0].startswith(\"$\")\n steps.append(step)\n step = []\n step.append(line)\n if step:\n steps.append(step)\n return steps\n\n\ndef run_cmd(input: str) -> tuple[int, str]:\n if input[1:].startswith(\"mypy run --\") and \"--show-error-codes\" not in input:\n input += \" --hide-error-codes\"\n if input.startswith(\"dmypy \"):\n input = sys.executable + \" -m mypy.\" + input\n if input.startswith(\"mypy \"):\n input = sys.executable + \" -m\" + input\n env = os.environ.copy()\n env[\"PYTHONPATH\"] = PREFIX\n try:\n output = subprocess.check_output(\n input, shell=True, stderr=subprocess.STDOUT, text=True, cwd=test_temp_dir, env=env\n )\n return 0, output\n except subprocess.CalledProcessError as err:\n return err.returncode, err.output\n\n\nclass DaemonUtilitySuite(unittest.TestCase):\n \"\"\"Unit tests for helpers\"\"\"\n\n def test_filter_out_missing_top_level_packages(self) -> None:\n with tempfile.TemporaryDirectory() as td:\n self.make_file(td, \"base\/a\/\")\n self.make_file(td, \"base\/b.py\")\n self.make_file(td, \"base\/c.pyi\")\n self.make_file(td, \"base\/missing.txt\")\n self.make_file(td, \"typeshed\/d.pyi\")\n self.make_file(td, \"typeshed\/@python2\/e\") # outdated\n self.make_file(td, \"pkg1\/f-stubs\")\n self.make_file(td, \"pkg2\/g-python2-stubs\") # outdated\n self.make_file(td, \"mpath\/sub\/long_name\/\")\n\n def makepath(p: str) -> str:\n return os.path.join(td, p)\n\n search = SearchPaths(\n python_path=(makepath(\"base\"),),\n mypy_path=(makepath(\"mpath\/sub\"),),\n package_path=(makepath(\"pkg1\"), makepath(\"pkg2\")),\n typeshed_path=(makepath(\"typeshed\"),),\n )\n fscache = FileSystemCache()\n res = filter_out_missing_top_level_packages(\n {\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"long_name\", \"ff\", \"missing\"}, search, fscache\n )\n assert res == {\"a\", \"b\", \"c\", \"d\", \"f\", \"long_name\"}\n\n def make_file(self, base: str, path: str) -> None:\n fullpath = os.path.join(base, path)\n os.makedirs(os.path.dirname(fullpath), exist_ok=True)\n if not path.endswith(\"\/\"):\n with open(fullpath, \"w\") as f:\n f.write(\"# test file\")\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testdaemon.py","language":"Python","license":"NOASSERTION","size":4511} {"code":"\"\"\"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((\" {', '.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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testdeps.py","language":"Python","license":"NOASSERTION","size":3236} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testdiff.py","language":"Python","license":"NOASSERTION","size":2510} {"code":"\"\"\"Tests for mypy incremental error output.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy import build\nfrom mypy.errors import CompileError\nfrom mypy.modulefinder import BuildSource\nfrom mypy.options import Options\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_string_arrays_equal\n\n\nclass ErrorStreamSuite(DataSuite):\n required_out_section = True\n base_path = \".\"\n files = [\"errorstream.test\"]\n\n def run_case(self, testcase: DataDrivenTestCase) -> None:\n test_error_stream(testcase)\n\n\ndef test_error_stream(testcase: DataDrivenTestCase) -> None:\n \"\"\"Perform a single error streaming test case.\n\n The argument contains the description of the test case.\n \"\"\"\n options = Options()\n options.show_traceback = True\n options.hide_error_codes = True\n\n logged_messages: list[str] = []\n\n def flush_errors(filename: str | None, msgs: list[str], serious: bool) -> None:\n if msgs:\n logged_messages.append(\"==== Errors flushed ====\")\n logged_messages.extend(msgs)\n\n sources = [BuildSource(\"main\", \"__main__\", \"\\n\".join(testcase.input))]\n try:\n build.build(sources=sources, options=options, flush_errors=flush_errors)\n except CompileError as e:\n assert e.messages == []\n\n assert_string_arrays_equal(\n testcase.output, logged_messages, f\"Invalid output ({testcase.file}, line {testcase.line})\"\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testerrorstream.py","language":"Python","license":"NOASSERTION","size":1441} {"code":"\"\"\"Test cases for fine-grained incremental checking.\n\nEach test cases runs a batch build followed by one or more fine-grained\nincremental steps. We verify that each step produces the expected output.\n\nSee the comment at the top of test-data\/unit\/fine-grained.test for more\ninformation.\n\nN.B.: Unlike most of the other test suites, testfinegrained does not\nrely on an alt_lib_path for finding source files. This means that they\ncan test interactions with the lib_path that is built implicitly based\non specified sources.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport re\nimport sys\nimport unittest\nfrom typing import Any\n\nimport pytest\n\nfrom mypy import build\nfrom mypy.config_parser import parse_config_file\nfrom mypy.dmypy_server import Server\nfrom mypy.dmypy_util import DEFAULT_STATUS_FILE\nfrom mypy.errors import CompileError\nfrom mypy.find_sources import create_source_list\nfrom mypy.modulefinder import BuildSource\nfrom mypy.options import Options\nfrom mypy.server.mergecheck import check_consistency\nfrom mypy.server.update import sort_messages_preserving_file_order\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite, DeleteFile, UpdateFile\nfrom mypy.test.helpers import (\n assert_module_equivalence,\n assert_string_arrays_equal,\n assert_target_equivalence,\n find_test_files,\n parse_options,\n perform_file_operations,\n)\n\n# Set to True to perform (somewhat expensive) checks for duplicate AST nodes after merge\nCHECK_CONSISTENCY = False\n\n\nclass FineGrainedSuite(DataSuite):\n files = find_test_files(\n pattern=\"fine-grained*.test\", exclude=[\"fine-grained-cache-incremental.test\"]\n )\n\n # Whether to use the fine-grained cache in the testing. This is overridden\n # by a trivial subclass to produce a suite that uses the cache.\n use_cache = False\n\n def should_skip(self, testcase: DataDrivenTestCase) -> bool:\n # Decide whether to skip the test. This could have been structured\n # as a filter() classmethod also, but we want the tests reported\n # as skipped, not just elided.\n if self.use_cache:\n if testcase.only_when == \"-only_when_nocache\":\n return True\n # TODO: In caching mode we currently don't well support\n # starting from cached states with errors in them.\n if testcase.output and testcase.output[0] != \"==\":\n return True\n else:\n if testcase.only_when == \"-only_when_cache\":\n return True\n return False\n\n def run_case(self, testcase: DataDrivenTestCase) -> None:\n if self.should_skip(testcase):\n pytest.skip()\n 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\n a.extend(self.maybe_suggest(step, server, main_src, testcase.tmpdir.name))\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 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\n a.extend(self.maybe_suggest(step, server, main_src, testcase.tmpdir.name))\n a.extend(self.maybe_inspect(step, server, main_src))\n\n return a, triggered\n\n def parse_sources(\n self, program_text: str, incremental_step: int, options: Options\n ) -> list[BuildSource]:\n \"\"\"Return target BuildSources for a test case.\n\n Normally, the unit tests will check all files included in the test\n case. This differs from how testcheck works by default, as dmypy\n doesn't currently support following imports.\n\n You can override this behavior and instruct the tests to check\n multiple modules by using a comment like this in the test case\n input:\n\n # cmd: main a.py\n\n You can also use `# cmdN:` to have a different cmd for incremental\n step N (2, 3, ...).\n\n \"\"\"\n m = re.search(\"# cmd: mypy ([a-zA-Z0-9_.\/ ]+)$\", program_text, flags=re.MULTILINE)\n regex = f\"# cmd{incremental_step}: mypy ([a-zA-Z0-9_.\/ ]+)$\"\n alt_m = re.search(regex, program_text, flags=re.MULTILINE)\n if alt_m is not None:\n # Optionally return a different command if in a later step\n # of incremental mode, otherwise default to reusing the\n # original cmd.\n m = alt_m\n\n if m:\n # The test case wants to use a non-default set of files.\n paths = [os.path.join(test_temp_dir, path) for path in m.group(1).strip().split()]\n return create_source_list(paths, options)\n else:\n base = BuildSource(os.path.join(test_temp_dir, \"main\"), \"__main__\", None)\n # Use expand_dir instead of create_source_list to avoid complaints\n # when there aren't any .py files in an increment\n return [base] + create_source_list([test_temp_dir], options, allow_empty_dir=True)\n\n def maybe_suggest(self, step: int, server: Server, src: str, tmp_dir: str) -> list[str]:\n output: list[str] = []\n targets = self.get_suggest(src, step)\n for flags, target in targets:\n json = \"--json\" in flags\n callsites = \"--callsites\" in flags\n no_any = \"--no-any\" in flags\n no_errors = \"--no-errors\" in flags\n m = re.match(\"--flex-any=([0-9.]+)\", flags)\n flex_any = float(m.group(1)) if m else None\n m = re.match(r\"--use-fixme=(\\w+)\", flags)\n use_fixme = m.group(1) if m else None\n m = re.match(\"--max-guesses=([0-9]+)\", flags)\n max_guesses = int(m.group(1)) if m else None\n res: dict[str, Any] = server.cmd_suggest(\n target.strip(),\n json=json,\n no_any=no_any,\n no_errors=no_errors,\n flex_any=flex_any,\n use_fixme=use_fixme,\n callsites=callsites,\n max_guesses=max_guesses,\n )\n val = res[\"error\"] if \"error\" in res else res[\"out\"] + res[\"err\"]\n if json:\n # JSON contains already escaped \\ on Windows, so requires a bit of care.\n val = val.replace(\"\\\\\\\\\", \"\\\\\")\n val = val.replace(os.path.realpath(tmp_dir) + os.path.sep, \"\")\n val = val.replace(os.path.abspath(tmp_dir) + os.path.sep, \"\")\n output.extend(val.strip().split(\"\\n\"))\n return normalize_messages(output)\n\n def maybe_inspect(self, step: int, server: Server, src: str) -> list[str]:\n output: list[str] = []\n targets = self.get_inspect(src, step)\n for flags, location in targets:\n m = re.match(r\"--show=(\\w+)\", flags)\n show = m.group(1) if m else \"type\"\n verbosity = 0\n if \"-v\" in flags:\n verbosity = 1\n if \"-vv\" in flags:\n verbosity = 2\n m = re.match(r\"--limit=([0-9]+)\", flags)\n limit = int(m.group(1)) if m else 0\n include_span = \"--include-span\" in flags\n include_kind = \"--include-kind\" in flags\n include_object_attrs = \"--include-object-attrs\" in flags\n union_attrs = \"--union-attrs\" in flags\n force_reload = \"--force-reload\" in flags\n res: dict[str, Any] = server.cmd_inspect(\n show,\n location,\n verbosity=verbosity,\n limit=limit,\n include_span=include_span,\n include_kind=include_kind,\n include_object_attrs=include_object_attrs,\n union_attrs=union_attrs,\n force_reload=force_reload,\n )\n val = res[\"error\"] if \"error\" in res else res[\"out\"] + res[\"err\"]\n output.extend(val.strip().split(\"\\n\"))\n return output\n\n def get_suggest(self, program_text: str, incremental_step: int) -> list[tuple[str, str]]:\n step_bit = \"1?\" if incremental_step == 1 else str(incremental_step)\n regex = f\"# suggest{step_bit}: (--[a-zA-Z0-9_\\\\-.\/=?^ ]+ )*([a-zA-Z0-9_.:\/?^ ]+)$\"\n m = re.findall(regex, program_text, flags=re.MULTILINE)\n return m\n\n def get_inspect(self, program_text: str, incremental_step: int) -> list[tuple[str, str]]:\n step_bit = \"1?\" if incremental_step == 1 else str(incremental_step)\n regex = f\"# inspect{step_bit}: (--[a-zA-Z0-9_\\\\-=?^ ]+ )*([a-zA-Z0-9_.:\/?^ ]+)$\"\n m = re.findall(regex, program_text, flags=re.MULTILINE)\n return m\n\n\ndef normalize_messages(messages: list[str]) -> list[str]:\n return [re.sub(\"^tmp\" + re.escape(os.sep), \"\", message) for message in messages]\n\n\nclass TestMessageSorting(unittest.TestCase):\n def test_simple_sorting(self) -> None:\n msgs = ['x.py:1: error: \"int\" not callable', 'foo\/y.py:123: note: \"X\" not defined']\n old_msgs = ['foo\/y.py:12: note: \"Y\" not defined', 'x.py:8: error: \"str\" not callable']\n assert sort_messages_preserving_file_order(msgs, old_msgs) == list(reversed(msgs))\n assert sort_messages_preserving_file_order(list(reversed(msgs)), old_msgs) == list(\n reversed(msgs)\n )\n\n def test_long_form_sorting(self) -> None:\n # Multi-line errors should be sorted together and not split.\n msg1 = [\n 'x.py:1: error: \"int\" not callable',\n \"and message continues (x: y)\",\n \" 1()\",\n \" ^~~\",\n ]\n msg2 = [\n 'foo\/y.py: In function \"f\":',\n 'foo\/y.py:123: note: \"X\" not defined',\n \"and again message continues\",\n ]\n old_msgs = ['foo\/y.py:12: note: \"Y\" not defined', 'x.py:8: error: \"str\" not callable']\n assert sort_messages_preserving_file_order(msg1 + msg2, old_msgs) == msg2 + msg1\n assert sort_messages_preserving_file_order(msg2 + msg1, old_msgs) == msg2 + msg1\n\n def test_mypy_error_prefix(self) -> None:\n # Some errors don't have a file and start with \"mypy: \". These\n # shouldn't be sorted together with file-specific errors.\n msg1 = 'x.py:1: error: \"int\" not callable'\n msg2 = 'foo\/y:123: note: \"X\" not defined'\n msg3 = \"mypy: Error not associated with a file\"\n old_msgs = [\n \"mypy: Something wrong\",\n 'foo\/y:12: note: \"Y\" not defined',\n 'x.py:8: error: \"str\" not callable',\n ]\n assert sort_messages_preserving_file_order([msg1, msg2, msg3], old_msgs) == [\n msg2,\n msg1,\n msg3,\n ]\n assert sort_messages_preserving_file_order([msg3, msg2, msg1], old_msgs) == [\n msg2,\n msg1,\n msg3,\n ]\n\n def test_new_file_at_the_end(self) -> None:\n msg1 = 'x.py:1: error: \"int\" not callable'\n msg2 = 'foo\/y.py:123: note: \"X\" not defined'\n new1 = \"ab.py:3: error: Problem: error\"\n new2 = \"aaa:3: error: Bad\"\n old_msgs = ['foo\/y.py:12: note: \"Y\" not defined', 'x.py:8: error: \"str\" not callable']\n assert sort_messages_preserving_file_order([msg1, msg2, new1], old_msgs) == [\n msg2,\n msg1,\n new1,\n ]\n assert sort_messages_preserving_file_order([new1, msg1, msg2, new2], old_msgs) == [\n msg2,\n msg1,\n new1,\n new2,\n ]\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testfinegrained.py","language":"Python","license":"NOASSERTION","size":17781} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testfinegrainedcache.py","language":"Python","license":"NOASSERTION","size":580} {"code":"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testformatter.py","language":"Python","license":"NOASSERTION","size":2639} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testfscache.py","language":"Python","license":"NOASSERTION","size":4456} {"code":"\"\"\"Test cases for graph processing code in build.py.\"\"\"\n\nfrom __future__ import annotations\n\nimport sys\nfrom typing import AbstractSet\n\nfrom mypy.build import BuildManager, BuildSourceSet, State, order_ascc, sorted_components\nfrom mypy.errors import Errors\nfrom mypy.fscache import FileSystemCache\nfrom mypy.graph_utils import strongly_connected_components, topsort\nfrom mypy.modulefinder import SearchPaths\nfrom mypy.options import Options\nfrom mypy.plugin import Plugin\nfrom mypy.report import Reports\nfrom mypy.test.helpers import Suite, assert_equal\nfrom mypy.version import __version__\n\n\nclass GraphSuite(Suite):\n def test_topsort(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=__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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testgraph.py","language":"Python","license":"NOASSERTION","size":3094} {"code":"\"\"\"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 -- ComparisionExprs\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testinfer.py","language":"Python","license":"NOASSERTION","size":13856} {"code":"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testipc.py","language":"Python","license":"NOASSERTION","size":3966} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testmerge.py","language":"Python","license":"NOASSERTION","size":8661} {"code":"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.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.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.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.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.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.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.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.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.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.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.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.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.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.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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testmodulefinder.py","language":"Python","license":"NOASSERTION","size":13177} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testmypyc.py","language":"Python","license":"NOASSERTION","size":397} {"code":"\"\"\"Test cases for `--output=json`.\n\nThese cannot be run by the usual unit test runner because of the backslashes in\nthe output, which get normalized to forward slashes by the test suite on Windows.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport os.path\n\nfrom mypy import api\nfrom mypy.defaults import PYTHON3_VERSION\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\n\n\nclass OutputJSONsuite(DataSuite):\n files = [\"outputjson.test\"]\n\n def run_case(self, testcase: DataDrivenTestCase) -> None:\n test_output_json(testcase)\n\n\ndef test_output_json(testcase: DataDrivenTestCase) -> None:\n \"\"\"Runs Mypy in a subprocess, and ensures that `--output=json` works as intended.\"\"\"\n mypy_cmdline = [\"--output=json\"]\n mypy_cmdline.append(f\"--python-version={'.'.join(map(str, PYTHON3_VERSION))}\")\n\n # Write the program to a file.\n program_path = os.path.join(test_temp_dir, \"main\")\n mypy_cmdline.append(program_path)\n with open(program_path, \"w\", encoding=\"utf8\") as file:\n for s in testcase.input:\n file.write(f\"{s}\\n\")\n\n output = []\n # Type check the program.\n out, err, returncode = api.run(mypy_cmdline)\n # split lines, remove newlines, and remove directory of test case\n for line in (out + err).rstrip(\"\\n\").splitlines():\n if line.startswith(test_temp_dir + os.sep):\n output.append(line[len(test_temp_dir + os.sep) :].rstrip(\"\\r\\n\"))\n else:\n output.append(line.rstrip(\"\\r\\n\"))\n\n if returncode > 1:\n output.append(\"!!! Mypy crashed !!!\")\n\n # Remove temp file.\n os.remove(program_path)\n\n # JSON encodes every `\\` character into `\\\\`, so we need to remove `\\\\` from windows paths\n # and `\/` from POSIX paths\n json_os_separator = os.sep.replace(\"\\\\\", \"\\\\\\\\\")\n normalized_output = [line.replace(test_temp_dir + json_os_separator, \"\") for line in output]\n\n assert normalized_output == testcase.output\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testoutput.py","language":"Python","license":"NOASSERTION","size":1980} {"code":"\"\"\"Tests for the mypy parser.\"\"\"\n\nfrom __future__ import annotations\n\nimport sys\n\nfrom pytest import skip\n\nfrom mypy import defaults\nfrom mypy.config_parser import parse_mypy_comments\nfrom mypy.errors import CompileError, Errors\nfrom mypy.options import Options\nfrom mypy.parse import parse\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_string_arrays_equal, find_test_files, parse_options\nfrom mypy.util import get_mypy_comments\n\n\nclass ParserSuite(DataSuite):\n required_out_section = True\n base_path = \".\"\n files = find_test_files(pattern=\"parse*.test\", exclude=[\"parse-errors.test\"])\n\n if sys.version_info < (3, 10):\n files.remove(\"parse-python310.test\")\n if sys.version_info < (3, 12):\n files.remove(\"parse-python312.test\")\n\n def run_case(self, testcase: DataDrivenTestCase) -> None:\n test_parser(testcase)\n\n\ndef test_parser(testcase: DataDrivenTestCase) -> None:\n \"\"\"Perform a single parser test case.\n\n The argument contains the description of the test case.\n \"\"\"\n options = Options()\n options.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 else:\n options.python_version = defaults.PYTHON3_VERSION\n\n source = \"\\n\".join(testcase.input)\n\n # Apply mypy: comments to options.\n comments = get_mypy_comments(source)\n changes, _ = parse_mypy_comments(comments, options)\n options = options.apply_changes(changes)\n\n try:\n n = parse(\n bytes(source, \"ascii\"),\n fnam=\"main\",\n module=\"__main__\",\n errors=Errors(options),\n options=options,\n raise_on_error=True,\n )\n a = n.str_with_options(options).split(\"\\n\")\n except CompileError as e:\n a = e.messages\n assert_string_arrays_equal(\n testcase.output, a, f\"Invalid parser output ({testcase.file}, line {testcase.line})\"\n )\n\n\n# The file name shown in test case output. This is displayed in error\n# messages, and must match the file name in the test case descriptions.\nINPUT_FILE_NAME = \"file\"\n\n\nclass ParseErrorSuite(DataSuite):\n required_out_section = True\n base_path = \".\"\n files = [\"parse-errors.test\"]\n\n def run_case(self, testcase: DataDrivenTestCase) -> None:\n test_parse_error(testcase)\n\n\ndef test_parse_error(testcase: DataDrivenTestCase) -> None:\n try:\n options = parse_options(\"\\n\".join(testcase.input), testcase, 0)\n if options.python_version != 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testparse.py","language":"Python","license":"NOASSERTION","size":3490} {"code":"from __future__ import annotations\n\nimport os\nimport re\nimport subprocess\nimport sys\nimport tempfile\nfrom contextlib import contextmanager\nfrom typing import Iterator\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, test_case: DataDrivenTestCase) -> None:\n test_pep561(test_case)\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 or (3, 8, 13) <= sys.version_info < (3, 9)\n ):\n # Skip for more recent Python releases which come with pip>=21.3.1\n # out of the box - for performance reasons.\n return\n\n install_cmd = [python_executable, \"-m\", \"pip\", \"install\", \"pip>=21.3.1\"]\n try:\n with filelock.FileLock(pip_lock, timeout=pip_timeout):\n proc = subprocess.run(install_cmd, capture_output=True, env=os.environ)\n except filelock.Timeout as err:\n raise Exception(f\"Failed to acquire {pip_lock}\") from err\n if proc.returncode != 0:\n raise Exception(proc.stdout.decode(\"utf-8\") + proc.stderr.decode(\"utf-8\"))\n\n\ndef install_package(\n pkg: str, python_executable: str = sys.executable, editable: bool = False\n) -> None:\n \"\"\"Install a package from test-data\/packages\/pkg\/\"\"\"\n working_dir = os.path.join(package_path, pkg)\n with tempfile.TemporaryDirectory() as dir:\n install_cmd = [python_executable, \"-m\", \"pip\", \"install\"]\n if editable:\n install_cmd.append(\"-e\")\n install_cmd.append(\".\")\n\n # Note that newer versions of pip (21.3+) don't\n # follow this env variable, but this is for compatibility\n env = {\"PIP_BUILD\": dir}\n # Inherit environment for Windows\n env.update(os.environ)\n try:\n with filelock.FileLock(pip_lock, timeout=pip_timeout):\n proc = subprocess.run(install_cmd, cwd=working_dir, capture_output=True, env=env)\n except filelock.Timeout as err:\n raise Exception(f\"Failed to acquire {pip_lock}\") from err\n if proc.returncode != 0:\n raise Exception(proc.stdout.decode(\"utf-8\") + proc.stderr.decode(\"utf-8\"))\n\n\ndef test_pep561(testcase: DataDrivenTestCase) -> None:\n \"\"\"Test running mypy on files that depend on PEP 561 packages.\"\"\"\n assert testcase.old_cwd is not None, \"test was not properly set up\"\n python = sys.executable\n\n assert python is not None, \"Should be impossible\"\n pkgs, pip_args = parse_pkgs(testcase.input[0])\n mypy_args = parse_mypy_args(testcase.input[1])\n editable = False\n for arg in pip_args:\n if arg == \"editable\":\n editable = True\n else:\n raise ValueError(f\"Unknown pip argument: {arg}\")\n assert pkgs, \"No packages to install for PEP 561 test?\"\n with virtualenv(python) as venv:\n venv_dir, python_executable = venv\n if editable:\n # Editable installs with PEP 660 require pip>=21.3\n upgrade_pip(python_executable)\n for pkg in pkgs:\n install_package(pkg, python_executable, editable)\n\n cmd_line = list(mypy_args)\n has_program = not (\"-p\" in cmd_line or \"--package\" in cmd_line)\n if has_program:\n program = testcase.name + \".py\"\n with open(program, \"w\", encoding=\"utf-8\") as f:\n for s in testcase.input:\n f.write(f\"{s}\\n\")\n cmd_line.append(program)\n\n cmd_line.extend([\"--no-error-summary\", \"--hide-error-codes\"])\n if python_executable != sys.executable:\n cmd_line.append(f\"--python-executable={python_executable}\")\n\n steps = testcase.find_steps()\n if steps != [[]]:\n steps = [[]] + steps\n\n for i, operations in enumerate(steps):\n perform_file_operations(operations)\n\n output = []\n # Type check the module\n out, err, returncode = mypy.api.run(cmd_line)\n\n # split lines, remove newlines, and remove directory of test case\n for line in (out + err).splitlines():\n if line.startswith(test_temp_dir + os.sep):\n output.append(line[len(test_temp_dir + os.sep) :].rstrip(\"\\r\\n\"))\n else:\n # Normalize paths so that the output is the same on Windows and Linux\/macOS.\n 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testpep561.py","language":"Python","license":"NOASSERTION","size":8064} {"code":"\"\"\"Test cases for running mypy programs using a Python interpreter.\n\nEach test case type checks a program then runs it using Python. The\noutput (stdout) of the program is compared to expected output. Type checking\nuses full builtins and other stubs.\n\nNote: Currently Python interpreter paths are hard coded.\n\nNote: These test cases are *not* included in the main test suite, as including\n this suite would slow down the main suite too much.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport os.path\nimport re\nimport subprocess\nimport sys\nfrom tempfile import TemporaryDirectory\n\nfrom mypy import api\nfrom mypy.defaults import PYTHON3_VERSION\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_string_arrays_equal, split_lines\n\n# Path to Python 3 interpreter\npython3_path = sys.executable\nprogram_re = re.compile(r\"\\b_program.py\\b\")\n\n\nclass PythonEvaluationSuite(DataSuite):\n files = [\"pythoneval.test\", \"pythoneval-asyncio.test\"]\n cache_dir = TemporaryDirectory()\n\n def run_case(self, testcase: DataDrivenTestCase) -> None:\n test_python_evaluation(testcase, os.path.join(self.cache_dir.name, \".mypy_cache\"))\n\n\ndef test_python_evaluation(testcase: DataDrivenTestCase, cache_dir: str) -> None:\n \"\"\"Runs Mypy in a subprocess.\n\n If this passes without errors, executes the script again with a given Python\n version.\n \"\"\"\n assert testcase.old_cwd is not None, \"test was not properly set up\"\n # We must enable site packages to get access to installed stubs.\n mypy_cmdline = [\n \"--show-traceback\",\n \"--no-silence-site-packages\",\n \"--no-error-summary\",\n \"--hide-error-codes\",\n \"--allow-empty-bodies\",\n \"--force-uppercase-builtins\",\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 targetted_python_version = flag.split(\"=\")[1]\n targetted_major, targetted_minor = targetted_python_version.split(\".\")\n if (int(targetted_major), int(targetted_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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testpythoneval.py","language":"Python","license":"NOASSERTION","size":4630} {"code":"\"\"\"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 \n \n \n \n \n \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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testreports.py","language":"Python","license":"NOASSERTION","size":1773} {"code":"\"\"\"Semantic analyzer test cases\"\"\"\n\nfrom __future__ import annotations\n\nimport sys\nfrom typing import Dict\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testsemanal.py","language":"Python","license":"NOASSERTION","size":6711} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testsolve.py","language":"Python","license":"NOASSERTION","size":10031} {"code":"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 common_dir_prefix,\n infer_method_ret_type,\n remove_misplaced_type_comments,\n walk_packages,\n)\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_equal, assert_string_arrays_equal, local_sys_path_set\n\n\nclass StubgenCmdLineSuite(unittest.TestCase):\n \"\"\"Test cases for processing command-line options and finding files.\"\"\"\n\n @unittest.skipIf(sys.platform == \"win32\", \"clean up fails on Windows\")\n def test_files_found(self) -> None:\n current = os.getcwd()\n with tempfile.TemporaryDirectory() as tmp:\n try:\n os.chdir(tmp)\n os.mkdir(\"subdir\")\n self.make_file(\"subdir\", \"a.py\")\n self.make_file(\"subdir\", \"b.py\")\n os.mkdir(os.path.join(\"subdir\", \"pack\"))\n self.make_file(\"subdir\", \"pack\", \"__init__.py\")\n opts = parse_options([\"subdir\"])\n py_mods, pyi_mods, c_mods = collect_build_targets(opts, mypy_options(opts))\n assert_equal(pyi_mods, [])\n assert_equal(c_mods, [])\n files = {mod.path for mod in py_mods}\n assert_equal(\n files,\n {\n os.path.join(\"subdir\", \"pack\", \"__init__.py\"),\n os.path.join(\"subdir\", \"a.py\"),\n os.path.join(\"subdir\", \"b.py\"),\n },\n )\n finally:\n os.chdir(current)\n\n @unittest.skipIf(sys.platform == \"win32\", \"clean up fails on Windows\")\n def test_packages_found(self) -> None:\n current = os.getcwd()\n with tempfile.TemporaryDirectory() as tmp:\n try:\n os.chdir(tmp)\n os.mkdir(\"pack\")\n self.make_file(\"pack\", \"__init__.py\", content=\"from . import a, b\")\n self.make_file(\"pack\", \"a.py\")\n self.make_file(\"pack\", \"b.py\")\n opts = parse_options([\"-p\", \"pack\"])\n py_mods, pyi_mods, c_mods = collect_build_targets(opts, mypy_options(opts))\n assert_equal(pyi_mods, [])\n assert_equal(c_mods, [])\n files = {os.path.relpath(mod.path or \"FAIL\") for mod in py_mods}\n assert_equal(\n files,\n {\n os.path.join(\"pack\", \"__init__.py\"),\n os.path.join(\"pack\", \"a.py\"),\n os.path.join(\"pack\", \"b.py\"),\n },\n )\n finally:\n os.chdir(current)\n\n @unittest.skipIf(sys.platform == \"win32\", \"clean up fails on Windows\")\n def test_module_not_found(self) -> None:\n current = os.getcwd()\n captured_output = io.StringIO()\n sys.stdout = captured_output\n with tempfile.TemporaryDirectory() as tmp:\n try:\n os.chdir(tmp)\n self.make_file(tmp, \"mymodule.py\", content=\"import a\")\n opts = parse_options([\"-m\", \"mymodule\"])\n collect_build_targets(opts, mypy_options(opts))\n assert captured_output.getvalue() == \"\"\n finally:\n sys.stdout = sys.__stdout__\n os.chdir(current)\n\n def make_file(self, *path: str, content: str = \"\") -> None:\n file = os.path.join(*path)\n with open(file, \"w\") as f:\n f.write(content)\n\n def run(self, result: Any | None = None) -> Any | None:\n with local_sys_path_set():\n return super().run(result)\n\n\nclass StubgenCliParseSuite(unittest.TestCase):\n def test_walk_packages(self) -> None:\n with ModuleInspect() as m:\n assert_equal(set(walk_packages(m, [\"mypy.errors\"])), {\"mypy.errors\"})\n\n assert_equal(\n set(walk_packages(m, [\"mypy.errors\", \"mypy.stubgen\"])),\n {\"mypy.errors\", \"mypy.stubgen\"},\n )\n\n all_mypy_packages = set(walk_packages(m, [\"mypy\"]))\n self.assertTrue(\n all_mypy_packages.issuperset(\n {\"mypy\", \"mypy.errors\", \"mypy.stubgen\", \"mypy.test\", \"mypy.test.helpers\"}\n )\n )\n\n\nclass StubgenUtilSuite(unittest.TestCase):\n \"\"\"Unit tests for stubgen utility functions.\"\"\"\n\n def test_parse_signature(self) -> None:\n self.assert_parse_signature(\"func()\", (\"func\", [], []))\n\n def test_parse_signature_with_args(self) -> None:\n self.assert_parse_signature(\"func(arg)\", (\"func\", [\"arg\"], []))\n self.assert_parse_signature(\"do(arg, arg2)\", (\"do\", [\"arg\", \"arg2\"], []))\n\n def test_parse_signature_with_optional_args(self) -> None:\n self.assert_parse_signature(\"func([arg])\", (\"func\", [], [\"arg\"]))\n self.assert_parse_signature(\"func(arg[, arg2])\", (\"func\", [\"arg\"], [\"arg2\"]))\n self.assert_parse_signature(\"func([arg[, arg2]])\", (\"func\", [], [\"arg\", \"arg2\"]))\n\n def test_parse_signature_with_default_arg(self) -> None:\n self.assert_parse_signature(\"func(arg=None)\", (\"func\", [], [\"arg\"]))\n self.assert_parse_signature(\"func(arg, arg2=None)\", (\"func\", [\"arg\"], [\"arg2\"]))\n self.assert_parse_signature('func(arg=1, arg2=\"\")', (\"func\", [], [\"arg\", \"arg2\"]))\n\n def test_parse_signature_with_qualified_function(self) -> None:\n self.assert_parse_signature(\"ClassName.func(arg)\", (\"func\", [\"arg\"], []))\n\n def test_parse_signature_with_kw_only_arg(self) -> None:\n self.assert_parse_signature(\n \"ClassName.func(arg, *, arg2=1)\", (\"func\", [\"arg\", \"*\"], [\"arg2\"])\n )\n\n def test_parse_signature_with_star_arg(self) -> None:\n self.assert_parse_signature(\"ClassName.func(arg, *args)\", (\"func\", [\"arg\", \"*args\"], []))\n\n def test_parse_signature_with_star_star_arg(self) -> None:\n self.assert_parse_signature(\"ClassName.func(arg, **args)\", (\"func\", [\"arg\", \"**args\"], []))\n\n def assert_parse_signature(self, sig: str, result: tuple[str, list[str], list[str]]) -> None:\n assert_equal(parse_signature(sig), result)\n\n def test_build_signature(self) -> None:\n assert_equal(build_signature([], []), \"()\")\n assert_equal(build_signature([\"arg\"], []), \"(arg)\")\n assert_equal(build_signature([\"arg\", \"arg2\"], []), \"(arg, arg2)\")\n assert_equal(build_signature([\"arg\"], [\"arg2\"]), \"(arg, arg2=...)\")\n assert_equal(build_signature([\"arg\"], [\"arg2\", \"**x\"]), \"(arg, arg2=..., **x)\")\n\n def test_parse_all_signatures(self) -> None:\n assert_equal(\n parse_all_signatures(\n [\n \"random text\",\n \".. function:: fn(arg\",\n \".. function:: fn()\",\n \" .. method:: fn2(arg)\",\n ]\n ),\n ([(\"fn\", \"()\"), (\"fn2\", \"(arg)\")], []),\n )\n\n def test_find_unique_signatures(self) -> None:\n assert_equal(\n find_unique_signatures(\n [\n (\"func\", \"()\"),\n (\"func\", \"()\"),\n (\"func2\", \"()\"),\n (\"func2\", \"(arg)\"),\n (\"func3\", \"(arg, arg2)\"),\n ]\n ),\n [(\"func\", \"()\"), (\"func3\", \"(arg, arg2)\")],\n )\n\n def test_infer_sig_from_docstring(self) -> None:\n assert_equal(\n infer_sig_from_docstring(\"\\nfunc(x) - y\", \"func\"),\n [FunctionSig(name=\"func\", args=[ArgSig(name=\"x\")], ret_type=\"Any\")],\n )\n assert_equal(\n infer_sig_from_docstring(\"\\nfunc(x)\", \"func\"),\n [FunctionSig(name=\"func\", args=[ArgSig(name=\"x\")], ret_type=\"Any\")],\n )\n\n assert_equal(\n infer_sig_from_docstring(\"\\nfunc(x, Y_a=None)\", \"func\"),\n [\n FunctionSig(\n name=\"func\",\n args=[ArgSig(name=\"x\"), ArgSig(name=\"Y_a\", default=True)],\n ret_type=\"Any\",\n )\n ],\n )\n\n assert_equal(\n infer_sig_from_docstring(\"\\nfunc(x, Y_a=3)\", \"func\"),\n [\n FunctionSig(\n name=\"func\",\n args=[ArgSig(name=\"x\"), ArgSig(name=\"Y_a\", default=True)],\n ret_type=\"Any\",\n )\n ],\n )\n\n assert_equal(\n infer_sig_from_docstring(\"\\nfunc(x, Y_a=[1, 2, 3])\", \"func\"),\n [\n FunctionSig(\n name=\"func\",\n args=[ArgSig(name=\"x\"), ArgSig(name=\"Y_a\", default=True)],\n ret_type=\"Any\",\n )\n ],\n )\n\n assert_equal(infer_sig_from_docstring(\"\\nafunc(x) - y\", \"func\"), [])\n assert_equal(infer_sig_from_docstring(\"\\nfunc(x, y\", \"func\"), [])\n assert_equal(\n infer_sig_from_docstring(\"\\nfunc(x=z(y))\", \"func\"),\n [FunctionSig(name=\"func\", args=[ArgSig(name=\"x\", default=True)], ret_type=\"Any\")],\n )\n\n assert_equal(infer_sig_from_docstring(\"\\nfunc x\", \"func\"), [])\n # Try to infer signature from type annotation.\n assert_equal(\n infer_sig_from_docstring(\"\\nfunc(x: int)\", \"func\"),\n [FunctionSig(name=\"func\", args=[ArgSig(name=\"x\", type=\"int\")], ret_type=\"Any\")],\n )\n assert_equal(\n infer_sig_from_docstring(\"\\nfunc(x: int=3)\", \"func\"),\n [\n FunctionSig(\n name=\"func\", args=[ArgSig(name=\"x\", type=\"int\", default=True)], ret_type=\"Any\"\n )\n ],\n )\n\n assert_equal(\n infer_sig_from_docstring(\"\\nfunc(x=3)\", \"func\"),\n [\n FunctionSig(\n name=\"func\", args=[ArgSig(name=\"x\", type=None, default=True)], ret_type=\"Any\"\n )\n ],\n )\n\n assert_equal(\n infer_sig_from_docstring(\"\\nfunc() -> int\", \"func\"),\n [FunctionSig(name=\"func\", args=[], ret_type=\"int\")],\n )\n\n assert_equal(\n infer_sig_from_docstring(\"\\nfunc(x: int=3) -> int\", \"func\"),\n [\n FunctionSig(\n name=\"func\", args=[ArgSig(name=\"x\", type=\"int\", default=True)], ret_type=\"int\"\n )\n ],\n )\n\n assert_equal(\n infer_sig_from_docstring(\"\\nfunc(x: int=3) -> int \\n\", \"func\"),\n [\n FunctionSig(\n name=\"func\", args=[ArgSig(name=\"x\", type=\"int\", default=True)], ret_type=\"int\"\n )\n ],\n )\n\n assert_equal(\n infer_sig_from_docstring(\"\\nfunc(x: Tuple[int, str]) -> str\", \"func\"),\n [\n FunctionSig(\n name=\"func\", args=[ArgSig(name=\"x\", type=\"Tuple[int,str]\")], ret_type=\"str\"\n )\n ],\n )\n\n assert_equal(\n infer_sig_from_docstring(\n \"\\nfunc(x: Tuple[int, Tuple[str, int], str], y: int) -> str\", \"func\"\n ),\n [\n FunctionSig(\n name=\"func\",\n args=[\n ArgSig(name=\"x\", type=\"Tuple[int,Tuple[str,int],str]\"),\n ArgSig(name=\"y\", type=\"int\"),\n ],\n ret_type=\"str\",\n )\n ],\n )\n\n assert_equal(\n infer_sig_from_docstring(\"\\nfunc(x: foo.bar)\", \"func\"),\n [FunctionSig(name=\"func\", args=[ArgSig(name=\"x\", type=\"foo.bar\")], ret_type=\"Any\")],\n )\n\n assert_equal(\n infer_sig_from_docstring(\"\\nfunc(x: list=[1,2,[3,4]])\", \"func\"),\n [\n FunctionSig(\n name=\"func\", args=[ArgSig(name=\"x\", type=\"list\", default=True)], ret_type=\"Any\"\n )\n ],\n )\n\n assert_equal(\n infer_sig_from_docstring('\\nfunc(x: str=\"nasty[\")', \"func\"),\n [\n FunctionSig(\n name=\"func\", args=[ArgSig(name=\"x\", type=\"str\", default=True)], ret_type=\"Any\"\n )\n ],\n )\n\n assert_equal(infer_sig_from_docstring(\"\\nfunc[(x: foo.bar, invalid]\", \"func\"), [])\n\n assert_equal(\n infer_sig_from_docstring(\"\\nfunc(x: invalid::type)\", \"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\nclass StubgenHelpersSuite(unittest.TestCase):\n def test_is_blacklisted_path(self) -> None:\n assert not is_blacklisted_path(\"foo\/bar.py\")\n assert not is_blacklisted_path(\"foo.py\")\n assert not is_blacklisted_path(\"foo\/xvendor\/bar.py\")\n assert not is_blacklisted_path(\"foo\/vendorx\/bar.py\")\n assert is_blacklisted_path(\"foo\/vendor\/bar.py\")\n assert is_blacklisted_path(\"foo\/vendored\/bar.py\")\n assert is_blacklisted_path(\"foo\/vendored\/bar\/thing.py\")\n assert is_blacklisted_path(\"foo\/six.py\")\n\n def test_is_non_library_module(self) -> None:\n assert not is_non_library_module(\"foo\")\n assert not is_non_library_module(\"foo.bar\")\n\n # The following could be test modules, but we are very conservative and\n # don't treat them as such since they could plausibly be real modules.\n assert not is_non_library_module(\"foo.bartest\")\n assert not is_non_library_module(\"foo.bartests\")\n assert not is_non_library_module(\"foo.testbar\")\n\n assert is_non_library_module(\"foo.test\")\n assert is_non_library_module(\"foo.test.foo\")\n assert is_non_library_module(\"foo.tests\")\n assert is_non_library_module(\"foo.tests.foo\")\n assert is_non_library_module(\"foo.testing.foo\")\n assert is_non_library_module(\"foo.SelfTest.foo\")\n\n assert is_non_library_module(\"foo.test_bar\")\n assert is_non_library_module(\"foo.bar_tests\")\n assert is_non_library_module(\"foo.testing\")\n assert is_non_library_module(\"foo.conftest\")\n assert is_non_library_module(\"foo.bar_test_util\")\n assert is_non_library_module(\"foo.bar_test_utils\")\n assert is_non_library_module(\"foo.bar_test_base\")\n\n assert is_non_library_module(\"foo.setup\")\n\n assert is_non_library_module(\"foo.__main__\")\n\n\nclass StubgenPythonSuite(DataSuite):\n \"\"\"Data-driven end-to-end test cases that generate stub files.\n\n You can use these magic test case name suffixes:\n\n *_semanal\n Run semantic analysis (slow as this uses real stubs -- only use\n when necessary)\n *_import\n Import module and perform runtime introspection (in the current\n process!)\n\n You can use these magic comments:\n\n # flags: --some-stubgen-option ...\n Specify custom stubgen options\n\n # modules: module1 module2 ...\n Specify which modules to output (by default only 'main')\n \"\"\"\n\n required_out_section = True\n base_path = \".\"\n files = [\"stubgen.test\"]\n\n @unittest.skipIf(sys.platform == \"win32\", \"clean up fails on Windows\")\n def run_case(self, testcase: DataDrivenTestCase) -> None:\n with local_sys_path_set():\n self.run_case_inner(testcase)\n\n def run_case_inner(self, testcase: DataDrivenTestCase) -> None:\n extra = [] # Extra command-line args\n mods = [] # Module names to process\n source = \"\\n\".join(testcase.input)\n for file, content in testcase.files + [(\".\/main.py\", source)]:\n # Strip .\/ prefix and .py suffix.\n mod = file[2:-3].replace(\"\/\", \".\")\n if mod.endswith(\".__init__\"):\n mod, _, _ = mod.rpartition(\".\")\n mods.append(mod)\n if \"-p \" not in source:\n extra.extend([\"-m\", mod])\n with open(file, \"w\") as f:\n f.write(content)\n\n options = self.parse_flags(source, extra)\n if sys.version_info < options.pyversion:\n pytest.skip()\n modules = self.parse_modules(source)\n out_dir = \"out\"\n try:\n try:\n if testcase.name.endswith(\"_inspect\"):\n options.inspect = True\n else:\n if not testcase.name.endswith(\"_import\"):\n options.no_import = True\n if not testcase.name.endswith(\"_semanal\"):\n options.parse_only = True\n\n generate_stubs(options)\n a: list[str] = []\n for module in modules:\n fnam = module_to_path(out_dir, module)\n self.add_file(fnam, a, header=len(modules) > 1)\n except CompileError as e:\n a = e.messages\n assert_string_arrays_equal(\n testcase.output, a, f\"Invalid output ({testcase.file}, line {testcase.line})\"\n )\n finally:\n for mod in mods:\n if mod in sys.modules:\n del sys.modules[mod]\n shutil.rmtree(out_dir)\n\n def parse_flags(self, program_text: str, extra: list[str]) -> Options:\n flags = re.search(\"# flags: (.*)$\", program_text, flags=re.MULTILINE)\n pyversion = None\n if flags:\n flag_list = flags.group(1).split()\n for i, flag in enumerate(flag_list):\n if flag.startswith(\"--python-version=\"):\n pyversion = flag.split(\"=\", 1)[1]\n del flag_list[i]\n break\n else:\n flag_list = []\n options = parse_options(flag_list + extra)\n if pyversion:\n # A hack to allow testing old python versions with new language constructs\n # This should be rarely used in general as stubgen output should not be version-specific\n major, minor = pyversion.split(\".\", 1)\n options.pyversion = (int(major), int(minor))\n if \"--verbose\" not in flag_list:\n options.quiet = True\n else:\n options.verbose = True\n return options\n\n def parse_modules(self, program_text: str) -> list[str]:\n modules = re.search(\"# modules: (.*)$\", program_text, flags=re.MULTILINE)\n if modules:\n return modules.group(1).split()\n else:\n return [\"main\"]\n\n def add_file(self, path: str, result: list[str], header: bool) -> None:\n if not os.path.exists(path):\n result.append(\"<%s was not generated>\" % path.replace(\"\\\\\", \"\/\"))\n return\n if header:\n result.append(f\"# {path[4:]}\")\n with open(path, encoding=\"utf8\") as file:\n result.extend(file.read().splitlines())\n\n\nself_arg = ArgSig(name=\"self\")\n\n\nclass TestBaseClass:\n pass\n\n\nclass TestClass(TestBaseClass):\n pass\n\n\nclass StubgencSuite(unittest.TestCase):\n \"\"\"Unit tests for stub generation from C modules using introspection.\n\n Note that these don't cover a lot!\n \"\"\"\n\n def test_infer_hash_sig(self) -> None:\n assert_equal(infer_c_method_args(\"__hash__\"), [self_arg])\n assert_equal(infer_method_ret_type(\"__hash__\"), \"int\")\n\n def test_infer_getitem_sig(self) -> None:\n assert_equal(infer_c_method_args(\"__getitem__\"), [self_arg, ArgSig(name=\"index\")])\n\n def test_infer_setitem_sig(self) -> None:\n assert_equal(\n infer_c_method_args(\"__setitem__\"),\n [self_arg, ArgSig(name=\"index\"), ArgSig(name=\"object\")],\n )\n assert_equal(infer_method_ret_type(\"__setitem__\"), \"None\")\n\n def test_infer_eq_op_sig(self) -> None:\n for op in (\"eq\", \"ne\", \"lt\", \"le\", \"gt\", \"ge\"):\n assert_equal(\n infer_c_method_args(f\"__{op}__\"), [self_arg, ArgSig(name=\"other\", type=\"object\")]\n )\n\n def test_infer_binary_op_sig(self) -> None:\n for op in (\"add\", \"radd\", \"sub\", \"rsub\", \"mul\", \"rmul\"):\n assert_equal(infer_c_method_args(f\"__{op}__\"), [self_arg, ArgSig(name=\"other\")])\n\n def test_infer_equality_op_sig(self) -> None:\n for op in (\"eq\", \"ne\", \"lt\", \"le\", \"gt\", \"ge\", \"contains\"):\n assert_equal(infer_method_ret_type(f\"__{op}__\"), \"bool\")\n\n def test_infer_unary_op_sig(self) -> None:\n for op in (\"neg\", \"pos\"):\n assert_equal(infer_c_method_args(f\"__{op}__\"), [self_arg])\n\n def test_infer_cast_sig(self) -> None:\n for op in (\"float\", \"bool\", \"bytes\", \"int\"):\n assert_equal(infer_method_ret_type(f\"__{op}__\"), op)\n\n def test_generate_class_stub_no_crash_for_object(self) -> None:\n output: list[str] = []\n mod = ModuleType(\"module\", \"\") # any module is fine\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n\n gen.generate_class_stub(\"alias\", object, output)\n assert_equal(gen.get_imports().splitlines(), [])\n assert_equal(output[0], \"class alias:\")\n\n def test_generate_class_stub_variable_type_annotation(self) -> None:\n # This class mimics the stubgen unit test 'testClassVariable'\n class TestClassVariableCls:\n x = 1\n\n output: list[str] = []\n mod = ModuleType(\"module\", \"\") # any module is fine\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_class_stub(\"C\", TestClassVariableCls, output)\n assert_equal(gen.get_imports().splitlines(), [\"from typing import ClassVar\"])\n assert_equal(output, [\"class C:\", \" x: ClassVar[int] = ...\"])\n\n def test_non_c_generate_signature_with_kw_only_args(self) -> None:\n class TestClass:\n def test(\n self, arg0: str, *, keyword_only: str, keyword_only_with_default: int = 7\n ) -> None:\n pass\n\n output: list[str] = []\n mod = ModuleType(TestClass.__module__, \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.is_c_module = False\n gen.generate_function_stub(\n \"test\",\n TestClass.test,\n output=output,\n class_info=ClassInfo(\n self_var=\"self\",\n cls=TestClass,\n name=\"TestClass\",\n docstring=getattr(TestClass, \"__doc__\", None),\n ),\n )\n assert_equal(\n output,\n [\n \"def test(self, arg0: str, *, keyword_only: str, keyword_only_with_default: int = ...) -> None: ...\"\n ],\n )\n\n def test_generate_c_type_inheritance(self) -> None:\n class TestClass(KeyError):\n pass\n\n output: list[str] = []\n mod = ModuleType(\"module, \")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_class_stub(\"C\", TestClass, output)\n assert_equal(output, [\"class C(KeyError): ...\"])\n assert_equal(gen.get_imports().splitlines(), [])\n\n def test_generate_c_type_inheritance_same_module(self) -> None:\n output: list[str] = []\n mod = ModuleType(TestBaseClass.__module__, \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_class_stub(\"C\", TestClass, output)\n assert_equal(output, [\"class C(TestBaseClass): ...\"])\n assert_equal(gen.get_imports().splitlines(), [])\n\n def test_generate_c_type_inheritance_other_module(self) -> None:\n import argparse\n\n class TestClass(argparse.Action):\n pass\n\n output: list[str] = []\n mod = ModuleType(\"module\", \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_class_stub(\"C\", TestClass, output)\n assert_equal(output, [\"class C(argparse.Action): ...\"])\n assert_equal(gen.get_imports().splitlines(), [\"import argparse\"])\n\n def test_generate_c_type_inheritance_builtin_type(self) -> None:\n class TestClass(type):\n pass\n\n output: list[str] = []\n mod = ModuleType(\"module\", \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_class_stub(\"C\", TestClass, output)\n assert_equal(output, [\"class C(type): ...\"])\n assert_equal(gen.get_imports().splitlines(), [])\n\n def test_generate_c_type_with_docstring(self) -> None:\n class TestClass:\n def test(self, arg0: str) -> None:\n \"\"\"\n test(self: TestClass, arg0: int)\n \"\"\"\n\n output: list[str] = []\n mod = ModuleType(TestClass.__module__, \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_function_stub(\n \"test\",\n TestClass.test,\n output=output,\n class_info=ClassInfo(self_var=\"self\", cls=TestClass, name=\"TestClass\"),\n )\n assert_equal(output, [\"def test(self, arg0: int) -> Any: ...\"])\n assert_equal(gen.get_imports().splitlines(), [])\n\n def test_generate_c_type_with_docstring_no_self_arg(self) -> None:\n class TestClass:\n def test(self, arg0: str) -> None:\n \"\"\"\n test(arg0: int)\n \"\"\"\n\n output: list[str] = []\n mod = ModuleType(TestClass.__module__, \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_function_stub(\n \"test\",\n TestClass.test,\n output=output,\n class_info=ClassInfo(self_var=\"self\", cls=TestClass, name=\"TestClass\"),\n )\n assert_equal(output, [\"def test(self, arg0: int) -> Any: ...\"])\n assert_equal(gen.get_imports().splitlines(), [])\n\n def test_generate_c_type_classmethod(self) -> None:\n class TestClass:\n @classmethod\n def test(cls, arg0: str) -> None:\n pass\n\n output: list[str] = []\n mod = ModuleType(TestClass.__module__, \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_function_stub(\n \"test\",\n TestClass.test,\n output=output,\n class_info=ClassInfo(self_var=\"cls\", cls=TestClass, name=\"TestClass\"),\n )\n assert_equal(output, [\"@classmethod\", \"def test(cls, *args, **kwargs): ...\"])\n assert_equal(gen.get_imports().splitlines(), [])\n\n def test_generate_c_type_classmethod_with_overloads(self) -> None:\n class TestClass:\n @classmethod\n def test(self, arg0: str) -> None:\n \"\"\"\n test(cls, arg0: str)\n test(cls, arg0: int)\n \"\"\"\n pass\n\n output: list[str] = []\n mod = ModuleType(TestClass.__module__, \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_function_stub(\n \"test\",\n TestClass.test,\n output=output,\n class_info=ClassInfo(self_var=\"cls\", cls=TestClass, name=\"TestClass\"),\n )\n assert_equal(\n output,\n [\n \"@overload\",\n \"@classmethod\",\n \"def test(cls, arg0: str) -> Any: ...\",\n \"@overload\",\n \"@classmethod\",\n \"def test(cls, arg0: int) -> Any: ...\",\n ],\n )\n assert_equal(gen.get_imports().splitlines(), [\"from typing import overload\"])\n\n def test_generate_c_type_with_docstring_empty_default(self) -> None:\n class TestClass:\n def test(self, arg0: str = \"\") -> None:\n \"\"\"\n test(self: TestClass, arg0: str = \"\")\n \"\"\"\n\n output: list[str] = []\n mod = ModuleType(TestClass.__module__, \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_function_stub(\n \"test\",\n TestClass.test,\n output=output,\n class_info=ClassInfo(self_var=\"self\", cls=TestClass, name=\"TestClass\"),\n )\n assert_equal(output, [\"def test(self, arg0: str = ...) -> Any: ...\"])\n assert_equal(gen.get_imports().splitlines(), [])\n\n def test_generate_c_function_other_module_arg(self) -> None:\n \"\"\"Test that if argument references type from other module, module will be imported.\"\"\"\n\n # Provide different type in python spec than in docstring to make sure, that docstring\n # information is used.\n def test(arg0: str) -> None:\n \"\"\"\n test(arg0: argparse.Action)\n \"\"\"\n\n output: list[str] = []\n mod = ModuleType(self.__module__, \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_function_stub(\"test\", test, output=output)\n assert_equal(output, [\"def test(arg0: argparse.Action) -> Any: ...\"])\n assert_equal(gen.get_imports().splitlines(), [\"import argparse\"])\n\n def test_generate_c_function_same_module(self) -> None:\n \"\"\"Test that if annotation references type from same module but using full path, no module\n will be imported, and type specification will be striped to local reference.\n \"\"\"\n\n # Provide different type in python spec than in docstring to make sure, that docstring\n # information is used.\n def test(arg0: str) -> None:\n \"\"\"\n test(arg0: argparse.Action) -> argparse.Action\n \"\"\"\n\n output: list[str] = []\n mod = ModuleType(\"argparse\", \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_function_stub(\"test\", test, output=output)\n assert_equal(output, [\"def test(arg0: Action) -> Action: ...\"])\n assert_equal(gen.get_imports().splitlines(), [])\n\n def test_generate_c_function_other_module(self) -> None:\n \"\"\"Test that if annotation references type from other module, module will be imported.\"\"\"\n\n def test(arg0: str) -> None:\n \"\"\"\n test(arg0: argparse.Action) -> argparse.Action\n \"\"\"\n\n output: list[str] = []\n mod = ModuleType(self.__module__, \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_function_stub(\"test\", test, output=output)\n assert_equal(output, [\"def test(arg0: argparse.Action) -> argparse.Action: ...\"])\n assert_equal(gen.get_imports().splitlines(), [\"import argparse\"])\n\n def test_generate_c_function_same_module_nested(self) -> None:\n \"\"\"Test that if annotation references type from same module but using full path, no module\n will be imported, and type specification will be stripped to local reference.\n \"\"\"\n\n # Provide different type in python spec than in docstring to make sure, that docstring\n # information is used.\n def test(arg0: str) -> None:\n \"\"\"\n test(arg0: list[argparse.Action]) -> list[argparse.Action]\n \"\"\"\n\n output: list[str] = []\n mod = ModuleType(\"argparse\", \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_function_stub(\"test\", test, output=output)\n assert_equal(output, [\"def test(arg0: list[Action]) -> list[Action]: ...\"])\n assert_equal(gen.get_imports().splitlines(), [])\n\n def test_generate_c_function_same_module_compound(self) -> None:\n \"\"\"Test that if annotation references type from same module but using full path, no module\n will be imported, and type specification will be stripped to local reference.\n \"\"\"\n\n # Provide different type in python spec than in docstring to make sure, that docstring\n # information is used.\n def test(arg0: str) -> None:\n \"\"\"\n test(arg0: Union[argparse.Action, NoneType]) -> Tuple[argparse.Action, NoneType]\n \"\"\"\n\n output: list[str] = []\n mod = ModuleType(\"argparse\", \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_function_stub(\"test\", test, output=output)\n assert_equal(output, [\"def test(arg0: Union[Action, None]) -> Tuple[Action, None]: ...\"])\n assert_equal(gen.get_imports().splitlines(), [])\n\n def test_generate_c_function_other_module_nested(self) -> None:\n \"\"\"Test that if annotation references type from other module, module will be imported,\n and the import will be restricted to one of the known modules.\"\"\"\n\n def test(arg0: str) -> None:\n \"\"\"\n test(arg0: foo.bar.Action) -> other.Thing\n \"\"\"\n\n output: list[str] = []\n mod = ModuleType(self.__module__, \"\")\n gen = InspectionStubGenerator(\n mod.__name__, known_modules=[\"foo\", \"foo.spangle\", \"bar\"], module=mod\n )\n gen.generate_function_stub(\"test\", test, output=output)\n assert_equal(output, [\"def test(arg0: foo.bar.Action) -> other.Thing: ...\"])\n assert_equal(gen.get_imports().splitlines(), [\"import foo\", \"import other\"])\n\n def test_generate_c_function_no_crash_for_non_str_docstring(self) -> None:\n def test(arg0: str) -> None: ...\n\n test.__doc__ = property(lambda self: \"test(arg0: str) -> None\") # type: ignore[assignment]\n\n output: list[str] = []\n mod = ModuleType(self.__module__, \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_function_stub(\"test\", test, output=output)\n assert_equal(output, [\"def test(*args, **kwargs): ...\"])\n assert_equal(gen.get_imports().splitlines(), [])\n\n def test_generate_c_property_with_pybind11(self) -> None:\n \"\"\"Signatures included by PyBind11 inside property.fget are read.\"\"\"\n\n class TestClass:\n def get_attribute(self) -> None:\n \"\"\"\n (self: TestClass) -> str\n \"\"\"\n\n attribute = property(get_attribute, doc=\"\")\n\n readwrite_properties: list[str] = []\n readonly_properties: list[str] = []\n mod = ModuleType(\"module\", \"\") # any module is fine\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_property_stub(\n \"attribute\",\n TestClass.__dict__[\"attribute\"],\n TestClass.attribute,\n [],\n readwrite_properties,\n readonly_properties,\n )\n assert_equal(readwrite_properties, [])\n assert_equal(readonly_properties, [\"@property\", \"def attribute(self) -> str: ...\"])\n\n def test_generate_c_property_with_rw_property(self) -> None:\n class TestClass:\n def __init__(self) -> None:\n self._attribute = 0\n\n @property\n def attribute(self) -> int:\n return self._attribute\n\n @attribute.setter\n def attribute(self, value: int) -> None:\n self._attribute = value\n\n readwrite_properties: list[str] = []\n readonly_properties: list[str] = []\n mod = ModuleType(\"module\", \"\") # any module is fine\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_property_stub(\n \"attribute\",\n TestClass.__dict__[\"attribute\"],\n TestClass.attribute,\n [],\n readwrite_properties,\n readonly_properties,\n )\n assert_equal(readwrite_properties, [\"attribute: Incomplete\"])\n assert_equal(readonly_properties, [])\n\n def test_generate_c_type_with_single_arg_generic(self) -> None:\n class TestClass:\n def test(self, arg0: str) -> None:\n \"\"\"\n test(self: TestClass, arg0: List[int])\n \"\"\"\n\n output: list[str] = []\n mod = ModuleType(TestClass.__module__, \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_function_stub(\n \"test\",\n TestClass.test,\n output=output,\n class_info=ClassInfo(self_var=\"self\", cls=TestClass, name=\"TestClass\"),\n )\n assert_equal(output, [\"def test(self, arg0: List[int]) -> Any: ...\"])\n assert_equal(gen.get_imports().splitlines(), [])\n\n def test_generate_c_type_with_double_arg_generic(self) -> None:\n class TestClass:\n def test(self, arg0: str) -> None:\n \"\"\"\n test(self: TestClass, arg0: Dict[str, int])\n \"\"\"\n\n output: list[str] = []\n mod = ModuleType(TestClass.__module__, \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_function_stub(\n \"test\",\n TestClass.test,\n output=output,\n class_info=ClassInfo(self_var=\"self\", cls=TestClass, name=\"TestClass\"),\n )\n assert_equal(output, [\"def test(self, arg0: Dict[str, int]) -> Any: ...\"])\n assert_equal(gen.get_imports().splitlines(), [])\n\n def test_generate_c_type_with_nested_generic(self) -> None:\n class TestClass:\n def test(self, arg0: str) -> None:\n \"\"\"\n test(self: TestClass, arg0: Dict[str, List[int]])\n \"\"\"\n\n output: list[str] = []\n mod = ModuleType(TestClass.__module__, \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_function_stub(\n \"test\",\n TestClass.test,\n output=output,\n class_info=ClassInfo(self_var=\"self\", cls=TestClass, name=\"TestClass\"),\n )\n assert_equal(output, [\"def test(self, arg0: Dict[str, List[int]]) -> Any: ...\"])\n assert_equal(gen.get_imports().splitlines(), [])\n\n def test_generate_c_type_with_generic_using_other_module_first(self) -> None:\n class TestClass:\n def test(self, arg0: str) -> None:\n \"\"\"\n test(self: TestClass, arg0: Dict[argparse.Action, int])\n \"\"\"\n\n output: list[str] = []\n mod = ModuleType(TestClass.__module__, \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_function_stub(\n \"test\",\n TestClass.test,\n output=output,\n class_info=ClassInfo(self_var=\"self\", cls=TestClass, name=\"TestClass\"),\n )\n assert_equal(output, [\"def test(self, arg0: Dict[argparse.Action, int]) -> Any: ...\"])\n assert_equal(gen.get_imports().splitlines(), [\"import argparse\"])\n\n def test_generate_c_type_with_generic_using_other_module_last(self) -> None:\n class TestClass:\n def test(self, arg0: str) -> None:\n \"\"\"\n test(self: TestClass, arg0: Dict[str, argparse.Action])\n \"\"\"\n\n output: list[str] = []\n mod = ModuleType(TestClass.__module__, \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_function_stub(\n \"test\",\n TestClass.test,\n output=output,\n class_info=ClassInfo(self_var=\"self\", cls=TestClass, name=\"TestClass\"),\n )\n assert_equal(output, [\"def test(self, arg0: Dict[str, argparse.Action]) -> Any: ...\"])\n assert_equal(gen.get_imports().splitlines(), [\"import argparse\"])\n\n def test_generate_c_type_with_overload_pybind11(self) -> None:\n class TestClass:\n def __init__(self, arg0: str) -> None:\n \"\"\"\n __init__(*args, **kwargs)\n Overloaded function.\n\n 1. __init__(self: TestClass, arg0: str) -> None\n\n 2. __init__(self: TestClass, arg0: str, arg1: str) -> None\n \"\"\"\n\n output: list[str] = []\n mod = ModuleType(TestClass.__module__, \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_function_stub(\n \"__init__\",\n TestClass.__init__,\n output=output,\n class_info=ClassInfo(self_var=\"self\", cls=TestClass, name=\"TestClass\"),\n )\n assert_equal(\n output,\n [\n \"@overload\",\n \"def __init__(self, arg0: str) -> None: ...\",\n \"@overload\",\n \"def __init__(self, arg0: str, arg1: str) -> None: ...\",\n \"@overload\",\n \"def __init__(self, *args, **kwargs) -> Any: ...\",\n ],\n )\n assert_equal(gen.get_imports().splitlines(), [\"from typing import overload\"])\n\n def test_generate_c_type_with_overload_shiboken(self) -> None:\n class TestClass:\n \"\"\"\n TestClass(self: TestClass, arg0: str) -> None\n TestClass(self: TestClass, arg0: str, arg1: str) -> None\n \"\"\"\n\n def __init__(self, arg0: str) -> None:\n pass\n\n output: list[str] = []\n mod = ModuleType(TestClass.__module__, \"\")\n gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n gen.generate_function_stub(\n \"__init__\",\n TestClass.__init__,\n output=output,\n class_info=ClassInfo(\n self_var=\"self\",\n cls=TestClass,\n name=\"TestClass\",\n docstring=getattr(TestClass, \"__doc__\", None),\n ),\n )\n assert_equal(\n output,\n [\n \"@overload\",\n \"def __init__(self, arg0: str) -> None: ...\",\n \"@overload\",\n \"def __init__(self, arg0: str, arg1: str) -> None: ...\",\n ],\n )\n assert_equal(gen.get_imports().splitlines(), [\"from typing import overload\"])\n\n\nclass ArgSigSuite(unittest.TestCase):\n def test_repr(self) -> None:\n assert_equal(\n repr(ArgSig(name='asd\"dsa')), \"ArgSig(name='asd\\\"dsa', type=None, default=False)\"\n )\n assert_equal(\n repr(ArgSig(name=\"asd'dsa\")), 'ArgSig(name=\"asd\\'dsa\", type=None, default=False)'\n )\n assert_equal(repr(ArgSig(\"func\", \"str\")), \"ArgSig(name='func', type='str', default=False)\")\n assert_equal(\n repr(ArgSig(\"func\", \"str\", default=True)),\n \"ArgSig(name='func', type='str', default=True)\",\n )\n\n\nclass IsValidTypeSuite(unittest.TestCase):\n def test_is_valid_type(self) -> None:\n assert is_valid_type(\"int\")\n assert is_valid_type(\"str\")\n assert is_valid_type(\"Foo_Bar234\")\n assert is_valid_type(\"foo.bar\")\n assert is_valid_type(\"List[int]\")\n assert is_valid_type(\"Dict[str, int]\")\n assert is_valid_type(\"None\")\n assert is_valid_type(\"Literal[26]\")\n assert is_valid_type(\"Literal[0x1A]\")\n assert is_valid_type('Literal[\"hello world\"]')\n assert is_valid_type('Literal[b\"hello world\"]')\n assert is_valid_type('Literal[u\"hello world\"]')\n assert is_valid_type(\"Literal[True]\")\n assert is_valid_type(\"Literal[Color.RED]\")\n assert is_valid_type(\"Literal[None]\")\n assert is_valid_type(\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/teststubgen.py","language":"Python","license":"NOASSERTION","size":53668} {"code":"from __future__ import annotations\n\nimport unittest\n\nfrom mypy.stubinfo import (\n approved_stub_package_exists,\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(\"dataclasses\")\n\n def test_approved_stub_package_exists(self) -> None:\n assert not approved_stub_package_exists(\"foobar_asdf\")\n assert approved_stub_package_exists(\"pycurl\")\n assert approved_stub_package_exists(\"babel\")\n assert approved_stub_package_exists(\"google.cloud.ndb\")\n assert approved_stub_package_exists(\"google.cloud.ndb.submodule\")\n assert not approved_stub_package_exists(\"google.cloud.unknown\")\n assert approved_stub_package_exists(\"google.protobuf\")\n assert approved_stub_package_exists(\"google.protobuf.submodule\")\n assert not approved_stub_package_exists(\"google\")\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(\"babel\") == \"types-babel\"\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/teststubinfo.py","language":"Python","license":"NOASSERTION","size":2182} {"code":"from __future__ import annotations\n\nimport contextlib\nimport inspect\nimport io\nimport os\nimport re\nimport sys\nimport tempfile\nimport textwrap\nimport unittest\nfrom typing import Any, Callable, Iterator\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\nCallable: _SpecialForm = ...\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 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 config_file:\n with open(f\"{TEST_MODULE_NAME}_config.ini\", \"w\") as f:\n f.write(config_file)\n options = options + [\"--mypy-config-file\", f\"{TEST_MODULE_NAME}_config.ini\"]\n output = io.StringIO()\n outerr = io.StringIO()\n with contextlib.redirect_stdout(output), contextlib.redirect_stderr(outerr):\n test_stubs(parse_options([TEST_MODULE_NAME] + options), use_builtins_fixtures=True)\n filtered_output = remove_color_code(\n output.getvalue()\n # remove cwd as it's not available from outside\n .replace(os.path.realpath(tmp_dir) + os.sep, \"\").replace(tmp_dir + os.sep, \"\")\n )\n filtered_outerr = remove_color_code(\n outerr.getvalue()\n # remove cwd as it's not available from outside\n .replace(os.path.realpath(tmp_dir) + os.sep, \"\").replace(tmp_dir + os.sep, \"\")\n )\n return filtered_output, filtered_outerr\n\n\ndef run_stubtest(\n stub: str, runtime: str, options: list[str], config_file: str | None = None\n) -> str:\n return run_stubtest_with_stderr(stub, runtime, options, config_file)[0]\n\n\nclass Case:\n def __init__(self, stub: str, runtime: str, error: str | None) -> None:\n self.stub = stub\n self.runtime = runtime\n self.error = error\n\n\ndef collect_cases(fn: Callable[..., Iterator[Case]]) -> Callable[..., None]:\n \"\"\"run_stubtest used to be slow, so we used this decorator to combine cases.\n\n If you're reading this and bored, feel free to refactor this and make it more like\n other mypy tests.\n\n \"\"\"\n\n def test(*args: Any, **kwargs: Any) -> None:\n cases = list(fn(*args, **kwargs))\n expected_errors = set()\n for c in cases:\n if c.error is None:\n continue\n expected_error = c.error\n if expected_error == \"\":\n expected_error = TEST_MODULE_NAME\n elif not expected_error.startswith(f\"{TEST_MODULE_NAME}.\"):\n expected_error = f\"{TEST_MODULE_NAME}.{expected_error}\"\n assert expected_error not in expected_errors, (\n \"collect_cases merges cases into a single stubtest invocation; we already \"\n \"expect an error for {}\".format(expected_error)\n )\n expected_errors.add(expected_error)\n output = run_stubtest(\n stub=\"\\n\\n\".join(textwrap.dedent(c.stub.lstrip(\"\\n\")) for c in cases),\n runtime=\"\\n\\n\".join(textwrap.dedent(c.runtime.lstrip(\"\\n\")) for c in cases),\n options=[\"--generate-allowlist\"],\n )\n\n actual_errors = set(output.splitlines())\n if actual_errors != expected_errors:\n output = run_stubtest(\n stub=\"\\n\\n\".join(textwrap.dedent(c.stub.lstrip(\"\\n\")) for c in cases),\n runtime=\"\\n\\n\".join(textwrap.dedent(c.runtime.lstrip(\"\\n\")) for c in cases),\n options=[],\n )\n assert actual_errors == expected_errors, output\n\n return test\n\n\nclass StubtestUnit(unittest.TestCase):\n @collect_cases\n def test_basic_good(self) -> Iterator[Case]:\n yield Case(\n stub=\"def f(number: int, text: str) -> None: ...\",\n runtime=\"def f(number, text): pass\",\n error=None,\n )\n yield Case(\n stub=\"\"\"\n class X:\n def f(self, number: int, text: str) -> None: ...\n \"\"\",\n runtime=\"\"\"\n class X:\n def f(self, number, text): pass\n \"\"\",\n error=None,\n )\n\n @collect_cases\n def test_types(self) -> Iterator[Case]:\n yield Case(\n stub=\"def mistyped_class() -> None: ...\",\n runtime=\"class mistyped_class: pass\",\n error=\"mistyped_class\",\n )\n yield Case(\n stub=\"class mistyped_fn: ...\", runtime=\"def mistyped_fn(): pass\", error=\"mistyped_fn\"\n )\n yield Case(\n stub=\"\"\"\n class X:\n def mistyped_var(self) -> int: ...\n \"\"\",\n runtime=\"\"\"\n class X:\n mistyped_var = 1\n \"\"\",\n error=\"X.mistyped_var\",\n )\n\n @collect_cases\n def test_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 \"\"\n yield Case(\n stub=\"def f11() -> None: ...\",\n runtime=\"\"\"\n def f11(text=None) -> None: pass\n f11.__text_signature__ = \"(text=)\"\n \"\"\",\n error=\"f11\",\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: int\n b: str\n c: str\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: int\n b: int\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: int\n b: int\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: int\n b: int\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: int\n b: int\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: bytes\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=None,\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=None) # 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\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 if sys.version_info >= (3, 9):\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: int\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\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/teststubtest.py","language":"Python","license":"NOASSERTION","size":83629} {"code":"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, 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, self.fx.nonet), 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 # 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testsubtypes.py","language":"Python","license":"NOASSERTION","size":12248} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testtransform.py","language":"Python","license":"NOASSERTION","size":2199} {"code":"\"\"\"Test cases for the type checker: exporting inferred types\"\"\"\n\nfrom __future__ import annotations\n\nimport re\n\nfrom mypy import build\nfrom mypy.errors import CompileError\nfrom mypy.modulefinder import BuildSource\nfrom mypy.nodes import NameExpr, TempNode\nfrom mypy.options import Options\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_string_arrays_equal\nfrom mypy.test.visitors import SkippedNodeSearcher, ignore_node\nfrom mypy.util import short_type\n\n\nclass TypeExportSuite(DataSuite):\n required_out_section = True\n files = [\"typexport-basic.test\"]\n\n def run_case(self, testcase: DataDrivenTestCase) -> None:\n try:\n line = testcase.input[0]\n mask = \"\"\n if line.startswith(\"##\"):\n mask = \"(\" + line[2:].strip() + \")$\"\n\n src = \"\\n\".join(testcase.input)\n options = Options()\n options.strict_optional = False # TODO: Enable strict optional checking\n options.use_builtins_fixtures = True\n options.show_traceback = True\n options.export_types = True\n options.preserve_asts = True\n options.allow_empty_bodies = True\n options.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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testtypegen.py","language":"Python","license":"NOASSERTION","size":3153} {"code":"\"\"\"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_union, true_only\nfrom mypy.types import (\n AnyType,\n CallableType,\n Instance,\n LiteralType,\n NoneType,\n Overloaded,\n ProperType,\n TupleType,\n Type,\n TypeOfAny,\n TypeType,\n TypeVarId,\n TypeVarType,\n UnboundType,\n UninhabitedType,\n UnionType,\n UnpackType,\n get_proper_type,\n has_recursive_types,\n)\n\n# Solving the import cycle:\nimport mypy.expandtype # ruff: isort: skip\n\n\nclass TypesSuite(Suite):\n def setUp(self) -> None:\n self.x = UnboundType(\"X\") # Helpers\n self.y = UnboundType(\"Y\")\n self.fx = TypeFixture()\n self.function = self.fx.function\n\n def test_any(self) -> None:\n assert_equal(str(AnyType(TypeOfAny.special_form)), \"Any\")\n\n def test_simple_unbound_type(self) -> None:\n u = UnboundType(\"Foo\")\n assert_equal(str(u), \"Foo?\")\n\n def test_generic_unbound_type(self) -> None:\n u = UnboundType(\"Foo\", [UnboundType(\"T\"), AnyType(TypeOfAny.special_form)])\n assert_equal(str(u), \"Foo?[T?, Any]\")\n\n def test_callable_type(self) -> None:\n c = CallableType(\n [self.x, self.y],\n [ARG_POS, ARG_POS],\n [None, None],\n AnyType(TypeOfAny.special_form),\n self.function,\n )\n assert_equal(str(c), \"def (X?, Y?) -> Any\")\n\n c2 = CallableType([], [], [], NoneType(), self.fx.function)\n assert_equal(str(c2), \"def ()\")\n\n def test_callable_type_with_default_args(self) -> None:\n c = CallableType(\n [self.x, self.y],\n [ARG_POS, ARG_OPT],\n [None, None],\n AnyType(TypeOfAny.special_form),\n self.function,\n )\n assert_equal(str(c), \"def (X?, Y? =) -> Any\")\n\n c2 = CallableType(\n [self.x, self.y],\n [ARG_OPT, ARG_OPT],\n [None, None],\n AnyType(TypeOfAny.special_form),\n self.function,\n )\n assert_equal(str(c2), \"def (X? =, Y? =) -> Any\")\n\n def test_callable_type_with_var_args(self) -> None:\n c = CallableType(\n [self.x], [ARG_STAR], [None], AnyType(TypeOfAny.special_form), self.function\n )\n assert_equal(str(c), \"def (*X?) -> Any\")\n\n c2 = CallableType(\n [self.x, self.y],\n [ARG_POS, ARG_STAR],\n [None, None],\n AnyType(TypeOfAny.special_form),\n self.function,\n )\n assert_equal(str(c2), \"def (X?, *Y?) -> Any\")\n\n c3 = CallableType(\n [self.x, self.y],\n [ARG_OPT, ARG_STAR],\n [None, None],\n AnyType(TypeOfAny.special_form),\n self.function,\n )\n assert_equal(str(c3), \"def (X? =, *Y?) -> Any\")\n\n def test_tuple_type_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 modules = A.accept(visitor)\n assert modules == {\"__main__\", \"builtins\"}\n\n A, _ = self.fx.def_alias_2(self.fx.a)\n visitor = TypeIndirectionVisitor()\n modules = A.accept(visitor)\n assert modules == {\"__main__\", \"builtins\"}\n\n\nclass TypeOpsSuite(Suite):\n def setUp(self) -> None:\n self.fx = TypeFixture(INVARIANT)\n self.fx_co = TypeFixture(COVARIANT)\n self.fx_contra = TypeFixture(CONTRAVARIANT)\n\n # expand_type\n\n def test_trivial_expand(self) -> None:\n for t in (\n self.fx.a,\n self.fx.o,\n self.fx.t,\n self.fx.nonet,\n self.tuple(self.fx.a),\n self.callable([], self.fx.a, self.fx.a),\n self.fx.anyt,\n ):\n self.assert_expand(t, [], t)\n self.assert_expand(t, [], t)\n self.assert_expand(t, [], t)\n\n def test_trivial_expand_recursive(self) -> None:\n A, _ = self.fx.def_alias_1(self.fx.a)\n self.assert_expand(A, [], A)\n A, _ = self.fx.def_alias_2(self.fx.a)\n self.assert_expand(A, [], A)\n\n def test_expand_naked_type_var(self) -> None:\n self.assert_expand(self.fx.t, [(self.fx.t.id, self.fx.a)], self.fx.a)\n self.assert_expand(self.fx.t, [(self.fx.s.id, self.fx.a)], self.fx.t)\n\n def test_expand_basic_generic_types(self) -> None:\n self.assert_expand(self.fx.gt, [(self.fx.t.id, self.fx.a)], self.fx.ga)\n\n # IDEA: Add test cases for\n # tuple types\n # callable types\n # multiple arguments\n\n def assert_expand(\n self, orig: Type, map_items: list[tuple[TypeVarId, Type]], result: Type\n ) -> None:\n lower_bounds = {}\n\n for id, t in map_items:\n lower_bounds[id] = t\n\n exp = mypy.expandtype.expand_type(orig, lower_bounds)\n # Remove erased tags (asterisks).\n assert_equal(str(exp).replace(\"*\", \"\"), str(result))\n\n # erase_type\n\n def test_trivial_erase(self) -> None:\n for t in (self.fx.a, self.fx.o, self.fx.nonet, self.fx.anyt):\n self.assert_erase(t, t)\n\n def test_erase_with_type_variable(self) -> None:\n self.assert_erase(self.fx.t, self.fx.anyt)\n\n def test_erase_with_generic_type(self) -> None:\n self.assert_erase(self.fx.ga, self.fx.gdyn)\n self.assert_erase(self.fx.hab, Instance(self.fx.hi, [self.fx.anyt, self.fx.anyt]))\n\n def test_erase_with_generic_type_recursive(self) -> None:\n tuple_any = Instance(self.fx.std_tuplei, [AnyType(TypeOfAny.explicit)])\n A, _ = self.fx.def_alias_1(self.fx.a)\n self.assert_erase(A, tuple_any)\n A, _ = self.fx.def_alias_2(self.fx.a)\n self.assert_erase(A, UnionType([self.fx.a, tuple_any]))\n\n def test_erase_with_tuple_type(self) -> None:\n self.assert_erase(self.tuple(self.fx.a), self.fx.std_tuple)\n\n def test_erase_with_function_type(self) -> None:\n self.assert_erase(\n self.fx.callable(self.fx.a, self.fx.b),\n CallableType(\n arg_types=[self.fx.anyt, self.fx.anyt],\n arg_kinds=[ARG_STAR, ARG_STAR2],\n arg_names=[None, None],\n ret_type=self.fx.anyt,\n fallback=self.fx.function,\n ),\n )\n\n def test_erase_with_type_object(self) -> None:\n self.assert_erase(\n self.fx.callable_type(self.fx.a, self.fx.b),\n CallableType(\n arg_types=[self.fx.anyt, self.fx.anyt],\n arg_kinds=[ARG_STAR, ARG_STAR2],\n arg_names=[None, None],\n ret_type=self.fx.anyt,\n fallback=self.fx.type_type,\n ),\n )\n\n def test_erase_with_type_type(self) -> None:\n self.assert_erase(self.fx.type_a, self.fx.type_a)\n self.assert_erase(self.fx.type_t, self.fx.type_any)\n\n def assert_erase(self, orig: Type, result: Type) -> None:\n assert_equal(str(erase_type(orig)), str(result))\n\n # is_more_precise\n\n def test_is_more_precise(self) -> None:\n fx = self.fx\n assert is_more_precise(fx.b, fx.a)\n assert is_more_precise(fx.b, fx.b)\n assert is_more_precise(fx.b, fx.b)\n assert is_more_precise(fx.b, fx.anyt)\n assert is_more_precise(self.tuple(fx.b, fx.a), self.tuple(fx.b, fx.a))\n assert is_more_precise(self.tuple(fx.b, fx.b), self.tuple(fx.b, fx.a))\n\n assert not is_more_precise(fx.a, fx.b)\n assert not is_more_precise(fx.anyt, fx.b)\n\n # is_proper_subtype\n\n def test_is_proper_subtype(self) -> None:\n fx = self.fx\n\n assert is_proper_subtype(fx.a, fx.a)\n assert is_proper_subtype(fx.b, fx.a)\n assert is_proper_subtype(fx.b, fx.o)\n assert is_proper_subtype(fx.b, fx.o)\n\n assert not is_proper_subtype(fx.a, fx.b)\n assert not is_proper_subtype(fx.o, fx.b)\n\n assert is_proper_subtype(fx.anyt, fx.anyt)\n assert not is_proper_subtype(fx.a, fx.anyt)\n assert not is_proper_subtype(fx.anyt, fx.a)\n\n assert is_proper_subtype(fx.ga, fx.ga)\n assert is_proper_subtype(fx.gdyn, fx.gdyn)\n assert not is_proper_subtype(fx.ga, fx.gdyn)\n assert not is_proper_subtype(fx.gdyn, fx.ga)\n\n assert is_proper_subtype(fx.t, fx.t)\n assert not is_proper_subtype(fx.t, fx.s)\n\n assert is_proper_subtype(fx.a, UnionType([fx.a, fx.b]))\n assert is_proper_subtype(UnionType([fx.a, fx.b]), UnionType([fx.a, fx.b, fx.c]))\n assert not is_proper_subtype(UnionType([fx.a, fx.b]), UnionType([fx.b, fx.c]))\n\n def test_is_proper_subtype_covariance(self) -> None:\n fx_co = self.fx_co\n\n assert is_proper_subtype(fx_co.gsab, fx_co.gb)\n assert is_proper_subtype(fx_co.gsab, fx_co.ga)\n assert not is_proper_subtype(fx_co.gsaa, fx_co.gb)\n assert is_proper_subtype(fx_co.gb, fx_co.ga)\n assert not is_proper_subtype(fx_co.ga, fx_co.gb)\n\n def test_is_proper_subtype_contravariance(self) -> None:\n fx_contra = self.fx_contra\n\n assert is_proper_subtype(fx_contra.gsab, fx_contra.gb)\n assert not is_proper_subtype(fx_contra.gsab, fx_contra.ga)\n assert is_proper_subtype(fx_contra.gsaa, fx_contra.gb)\n assert not is_proper_subtype(fx_contra.gb, fx_contra.ga)\n assert is_proper_subtype(fx_contra.ga, fx_contra.gb)\n\n def test_is_proper_subtype_invariance(self) -> None:\n fx = self.fx\n\n assert is_proper_subtype(fx.gsab, fx.gb)\n assert not is_proper_subtype(fx.gsab, fx.ga)\n assert not is_proper_subtype(fx.gsaa, fx.gb)\n assert not is_proper_subtype(fx.gb, fx.ga)\n assert not is_proper_subtype(fx.ga, fx.gb)\n\n def test_is_proper_subtype_and_subtype_literal_types(self) -> None:\n fx = self.fx\n\n lit1 = fx.lit1\n lit2 = fx.lit2\n lit3 = fx.lit3\n\n assert is_proper_subtype(lit1, fx.a)\n assert not is_proper_subtype(lit1, fx.d)\n assert not is_proper_subtype(fx.a, lit1)\n assert is_proper_subtype(fx.uninhabited, lit1)\n assert not is_proper_subtype(lit1, fx.uninhabited)\n assert is_proper_subtype(lit1, lit1)\n assert not is_proper_subtype(lit1, lit2)\n assert not is_proper_subtype(lit2, lit3)\n\n assert is_subtype(lit1, fx.a)\n assert not is_subtype(lit1, fx.d)\n assert not is_subtype(fx.a, lit1)\n assert is_subtype(fx.uninhabited, lit1)\n assert not is_subtype(lit1, fx.uninhabited)\n assert is_subtype(lit1, lit1)\n assert not is_subtype(lit1, lit2)\n assert not is_subtype(lit2, lit3)\n\n assert not is_proper_subtype(lit1, fx.anyt)\n assert not is_proper_subtype(fx.anyt, lit1)\n\n assert is_subtype(lit1, fx.anyt)\n assert is_subtype(fx.anyt, lit1)\n\n def test_subtype_aliases(self) -> None:\n A1, _ = self.fx.def_alias_1(self.fx.a)\n AA1, _ = self.fx.def_alias_1(self.fx.a)\n assert is_subtype(A1, AA1)\n assert is_subtype(AA1, A1)\n\n A2, _ = self.fx.def_alias_2(self.fx.a)\n AA2, _ = self.fx.def_alias_2(self.fx.a)\n assert is_subtype(A2, AA2)\n assert is_subtype(AA2, A2)\n\n B1, _ = self.fx.def_alias_1(self.fx.b)\n B2, _ = self.fx.def_alias_2(self.fx.b)\n assert is_subtype(B1, A1)\n assert is_subtype(B2, A2)\n assert not is_subtype(A1, B1)\n assert not is_subtype(A2, B2)\n\n assert not is_subtype(A2, A1)\n assert is_subtype(A1, A2)\n\n # can_be_true \/ can_be_false\n\n def test_empty_tuple_always_false(self) -> None:\n tuple_type = self.tuple()\n assert tuple_type.can_be_false\n assert not tuple_type.can_be_true\n\n def test_nonempty_tuple_always_true(self) -> None:\n tuple_type = self.tuple(AnyType(TypeOfAny.special_form), AnyType(TypeOfAny.special_form))\n assert tuple_type.can_be_true\n assert not tuple_type.can_be_false\n\n def test_union_can_be_true_if_any_true(self) -> None:\n union_type = UnionType([self.fx.a, self.tuple()])\n assert union_type.can_be_true\n\n def test_union_can_not_be_true_if_none_true(self) -> None:\n union_type = UnionType([self.tuple(), self.tuple()])\n assert not union_type.can_be_true\n\n def test_union_can_be_false_if_any_false(self) -> None:\n union_type = UnionType([self.fx.a, self.tuple()])\n assert union_type.can_be_false\n\n def test_union_can_not_be_false_if_none_false(self) -> None:\n union_type = UnionType([self.tuple(self.fx.a), self.tuple(self.fx.d)])\n assert not union_type.can_be_false\n\n # true_only \/ false_only\n\n def test_true_only_of_false_type_is_uninhabited(self) -> None:\n to = true_only(NoneType())\n assert_type(UninhabitedType, to)\n\n def test_true_only_of_true_type_is_idempotent(self) -> None:\n always_true = self.tuple(AnyType(TypeOfAny.special_form))\n to = true_only(always_true)\n assert always_true is to\n\n def test_true_only_of_instance(self) -> None:\n to = true_only(self.fx.a)\n assert_equal(str(to), \"A\")\n assert to.can_be_true\n assert not to.can_be_false\n assert_type(Instance, to)\n # The original class still can be false\n assert self.fx.a.can_be_false\n\n def test_true_only_of_union(self) -> None:\n tup_type = self.tuple(AnyType(TypeOfAny.special_form))\n # Union of something that is unknown, something that is always true, something\n # that is always false\n union_type = UnionType([self.fx.a, tup_type, self.tuple()])\n to = true_only(union_type)\n assert isinstance(to, UnionType)\n assert_equal(len(to.items), 2)\n assert to.items[0].can_be_true\n assert not to.items[0].can_be_false\n assert to.items[1] is tup_type\n\n def test_false_only_of_true_type_is_uninhabited(self) -> None:\n with state.strict_optional_set(True):\n fo = false_only(self.tuple(AnyType(TypeOfAny.special_form)))\n assert_type(UninhabitedType, fo)\n\n def test_false_only_tuple(self) -> None:\n with state.strict_optional_set(False):\n fo = false_only(self.tuple(self.fx.a))\n assert_equal(fo, NoneType())\n with state.strict_optional_set(True):\n fo = false_only(self.tuple(self.fx.a))\n assert_equal(fo, UninhabitedType())\n\n def test_false_only_of_false_type_is_idempotent(self) -> None:\n always_false = NoneType()\n fo = false_only(always_false)\n assert always_false is fo\n\n def test_false_only_of_instance(self) -> None:\n fo = false_only(self.fx.a)\n assert_equal(str(fo), \"A\")\n assert not fo.can_be_true\n assert fo.can_be_false\n assert_type(Instance, fo)\n # The original class still can be true\n assert self.fx.a.can_be_true\n\n def test_false_only_of_union(self) -> None:\n with state.strict_optional_set(True):\n tup_type = self.tuple()\n # Union of something that is unknown, something that is always true, something\n # that is always false\n union_type = UnionType(\n [self.fx.a, self.tuple(AnyType(TypeOfAny.special_form)), tup_type]\n )\n assert_equal(len(union_type.items), 3)\n fo = false_only(union_type)\n assert isinstance(fo, UnionType)\n assert_equal(len(fo.items), 2)\n assert not fo.items[0].can_be_true\n assert fo.items[0].can_be_false\n assert fo.items[1] is tup_type\n\n def test_simplified_union(self) -> None:\n fx = self.fx\n\n self.assert_simplified_union([fx.a, fx.a], fx.a)\n self.assert_simplified_union([fx.a, fx.b], fx.a)\n self.assert_simplified_union([fx.a, fx.d], UnionType([fx.a, fx.d]))\n self.assert_simplified_union([fx.a, fx.uninhabited], fx.a)\n self.assert_simplified_union([fx.ga, fx.gs2a], fx.ga)\n self.assert_simplified_union([fx.ga, fx.gsab], UnionType([fx.ga, fx.gsab]))\n self.assert_simplified_union([fx.ga, fx.gsba], fx.ga)\n self.assert_simplified_union([fx.a, UnionType([fx.d])], UnionType([fx.a, fx.d]))\n self.assert_simplified_union([fx.a, UnionType([fx.a])], fx.a)\n self.assert_simplified_union(\n [fx.b, UnionType([fx.c, UnionType([fx.d])])], UnionType([fx.b, fx.c, fx.d])\n )\n\n def test_simplified_union_with_literals(self) -> None:\n fx = self.fx\n\n self.assert_simplified_union([fx.lit1, fx.a], fx.a)\n self.assert_simplified_union([fx.lit1, fx.lit2, fx.a], fx.a)\n self.assert_simplified_union([fx.lit1, fx.lit1], fx.lit1)\n self.assert_simplified_union([fx.lit1, fx.lit2], UnionType([fx.lit1, fx.lit2]))\n self.assert_simplified_union([fx.lit1, fx.lit3], UnionType([fx.lit1, fx.lit3]))\n self.assert_simplified_union([fx.lit1, fx.uninhabited], fx.lit1)\n self.assert_simplified_union([fx.lit1_inst, fx.a], fx.a)\n self.assert_simplified_union([fx.lit1_inst, fx.lit1_inst], fx.lit1_inst)\n self.assert_simplified_union(\n [fx.lit1_inst, fx.lit2_inst], UnionType([fx.lit1_inst, fx.lit2_inst])\n )\n self.assert_simplified_union(\n [fx.lit1_inst, fx.lit3_inst], UnionType([fx.lit1_inst, fx.lit3_inst])\n )\n self.assert_simplified_union([fx.lit1_inst, fx.uninhabited], fx.lit1_inst)\n self.assert_simplified_union([fx.lit1, fx.lit1_inst], fx.lit1)\n self.assert_simplified_union([fx.lit1, fx.lit2_inst], UnionType([fx.lit1, fx.lit2_inst]))\n self.assert_simplified_union([fx.lit1, fx.lit3_inst], UnionType([fx.lit1, fx.lit3_inst]))\n\n def test_simplified_union_with_str_literals(self) -> None:\n fx = self.fx\n\n self.assert_simplified_union([fx.lit_str1, fx.lit_str2, fx.str_type], fx.str_type)\n self.assert_simplified_union([fx.lit_str1, fx.lit_str1, fx.lit_str1], fx.lit_str1)\n self.assert_simplified_union(\n [fx.lit_str1, fx.lit_str2, fx.lit_str3],\n UnionType([fx.lit_str1, fx.lit_str2, fx.lit_str3]),\n )\n self.assert_simplified_union(\n [fx.lit_str1, fx.lit_str2, fx.uninhabited], UnionType([fx.lit_str1, fx.lit_str2])\n )\n\n def test_simplify_very_large_union(self) -> None:\n fx = self.fx\n literals = []\n for i in range(5000):\n literals.append(LiteralType(\"v%d\" % i, fx.str_type))\n # This shouldn't be very slow, even if the union is big.\n self.assert_simplified_union([*literals, fx.str_type], fx.str_type)\n\n def test_simplified_union_with_str_instance_literals(self) -> None:\n fx = self.fx\n\n self.assert_simplified_union(\n [fx.lit_str1_inst, fx.lit_str2_inst, fx.str_type], fx.str_type\n )\n self.assert_simplified_union(\n [fx.lit_str1_inst, fx.lit_str1_inst, fx.lit_str1_inst], fx.lit_str1_inst\n )\n self.assert_simplified_union(\n [fx.lit_str1_inst, fx.lit_str2_inst, fx.lit_str3_inst],\n UnionType([fx.lit_str1_inst, fx.lit_str2_inst, fx.lit_str3_inst]),\n )\n self.assert_simplified_union(\n [fx.lit_str1_inst, fx.lit_str2_inst, fx.uninhabited],\n UnionType([fx.lit_str1_inst, fx.lit_str2_inst]),\n )\n\n def test_simplified_union_with_mixed_str_literals(self) -> None:\n fx = self.fx\n\n self.assert_simplified_union(\n [fx.lit_str1, fx.lit_str2, fx.lit_str3_inst],\n UnionType([fx.lit_str1, fx.lit_str2, fx.lit_str3_inst]),\n )\n self.assert_simplified_union([fx.lit_str1, fx.lit_str1, fx.lit_str1_inst], fx.lit_str1)\n\n def assert_simplified_union(self, original: list[Type], union: Type) -> None:\n assert_equal(make_simplified_union(original), union)\n assert_equal(make_simplified_union(list(reversed(original))), union)\n\n # Helpers\n\n def tuple(self, *a: Type) -> TupleType:\n return TupleType(list(a), self.fx.std_tuple)\n\n def callable(self, vars: list[str], *a: Type) -> CallableType:\n \"\"\"callable(args, a1, ..., an, r) constructs a callable with\n argument types a1, ... an and return type r and type arguments\n vars.\n \"\"\"\n tv: list[TypeVarType] = []\n n = -1\n for v in vars:\n tv.append(\n TypeVarType(\n v, v, TypeVarId(n), [], self.fx.o, AnyType(TypeOfAny.from_omitted_generics)\n )\n )\n n -= 1\n return CallableType(\n list(a[:-1]),\n [ARG_POS] * (len(a) - 1),\n [None] * (len(a) - 1),\n a[-1],\n self.fx.function,\n name=None,\n variables=tv,\n )\n\n\nclass JoinSuite(Suite):\n def setUp(self) -> None:\n self.fx = TypeFixture(INVARIANT)\n self.fx_co = TypeFixture(COVARIANT)\n self.fx_contra = TypeFixture(CONTRAVARIANT)\n\n def test_trivial_cases(self) -> None:\n for simple in self.fx.a, self.fx.o, self.fx.b:\n self.assert_join(simple, simple, simple)\n\n def test_class_subtyping(self) -> None:\n self.assert_join(self.fx.a, self.fx.o, self.fx.o)\n self.assert_join(self.fx.b, self.fx.o, self.fx.o)\n self.assert_join(self.fx.a, self.fx.d, self.fx.o)\n self.assert_join(self.fx.b, self.fx.c, self.fx.a)\n self.assert_join(self.fx.b, self.fx.d, self.fx.o)\n\n def test_tuples(self) -> None:\n self.assert_join(self.tuple(), self.tuple(), self.tuple())\n self.assert_join(self.tuple(self.fx.a), self.tuple(self.fx.a), self.tuple(self.fx.a))\n self.assert_join(\n self.tuple(self.fx.b, self.fx.c),\n self.tuple(self.fx.a, self.fx.d),\n self.tuple(self.fx.a, self.fx.o),\n )\n\n self.assert_join(\n self.tuple(self.fx.a, self.fx.a), self.fx.std_tuple, self.var_tuple(self.fx.anyt)\n )\n self.assert_join(\n self.tuple(self.fx.a), self.tuple(self.fx.a, self.fx.a), self.var_tuple(self.fx.a)\n )\n self.assert_join(\n self.tuple(self.fx.b), self.tuple(self.fx.a, self.fx.c), self.var_tuple(self.fx.a)\n )\n self.assert_join(self.tuple(), self.tuple(self.fx.a), self.var_tuple(self.fx.a))\n\n def test_var_tuples(self) -> None:\n self.assert_join(\n self.tuple(self.fx.a), self.var_tuple(self.fx.a), self.var_tuple(self.fx.a)\n )\n self.assert_join(\n self.var_tuple(self.fx.a), self.tuple(self.fx.a), self.var_tuple(self.fx.a)\n )\n self.assert_join(self.var_tuple(self.fx.a), self.tuple(), self.var_tuple(self.fx.a))\n\n def test_function_types(self) -> None:\n self.assert_join(\n self.callable(self.fx.a, self.fx.b),\n self.callable(self.fx.a, self.fx.b),\n self.callable(self.fx.a, self.fx.b),\n )\n\n self.assert_join(\n self.callable(self.fx.a, self.fx.b),\n self.callable(self.fx.b, self.fx.b),\n self.callable(self.fx.b, self.fx.b),\n )\n self.assert_join(\n self.callable(self.fx.a, self.fx.b),\n self.callable(self.fx.a, self.fx.a),\n self.callable(self.fx.a, self.fx.a),\n )\n self.assert_join(self.callable(self.fx.a, self.fx.b), self.fx.function, self.fx.function)\n self.assert_join(\n self.callable(self.fx.a, self.fx.b),\n self.callable(self.fx.d, self.fx.b),\n self.fx.function,\n )\n\n def test_type_vars(self) -> None:\n self.assert_join(self.fx.t, self.fx.t, self.fx.t)\n self.assert_join(self.fx.s, self.fx.s, self.fx.s)\n self.assert_join(self.fx.t, self.fx.s, self.fx.o)\n\n def test_none(self) -> None:\n # 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 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 self.assert_join(self.fx.ga, self.fx.nonet, self.fx.ga)\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, NoneType())\n self.assert_meet(self.fx.b, self.fx.c, NoneType())\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, NoneType()),\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(self.tuple(self.fx.a), self.tuple(self.fx.a, self.fx.a), NoneType())\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, NoneType())\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 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 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, self.fx.nonet)\n self.assert_meet(self.fx.ga, self.fx.g2a, self.fx.nonet)\n\n self.assert_meet(self.fx.ga, self.fx.nonet, self.fx.nonet)\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, self.fx.nonet)\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, self.fx.nonet)\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, self.fx.nonet)\n\n def test_generics_with_inheritance_and_shared_supertype(self) -> None:\n self.assert_meet(self.fx.gsba, self.fx.gs2a, self.fx.nonet)\n self.assert_meet(self.fx.gsab, self.fx.gs2a, self.fx.nonet)\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, self.fx.nonet)\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, self.fx.nonet)\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, self.fx.nonet)\n self.assert_meet(self.fx.e2, self.fx.e3, self.fx.nonet)\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, fx.nonet)\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.nonet)\n self.assert_meet(self.fx.type_c, self.fx.type_d, self.fx.nonet)\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 = 9\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testtypes.py","language":"Python","license":"NOASSERTION","size":62301} {"code":"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 = \"\"\"\n\n \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 = \"\"\"\n\n \n Test failed\nanother line < > &<\/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 = \"\"\"\n\n \n Test failed\nanother line<\/failure>\n <\/testcase>\n \n 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 = \"\"\"\n\n \n 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/testutil.py","language":"Python","license":"NOASSERTION","size":4233} {"code":"\"\"\"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(\"builtins.function\") # function TODO\n self.ai = self.make_type_info(\"A\", mro=[self.oi]) # class A\n self.bi = self.make_type_info(\"B\", mro=[self.ai, self.oi]) # class B(A)\n self.ci = self.make_type_info(\"C\", mro=[self.ai, self.oi]) # class C(A)\n self.di = self.make_type_info(\"D\", mro=[self.oi]) # class D\n # class E(F)\n self.ei = self.make_type_info(\"E\", mro=[self.fi, self.oi])\n # class E2(F2, F)\n self.e2i = self.make_type_info(\"E2\", mro=[self.f2i, self.fi, self.oi])\n # class E3(F, F2)\n self.e3i = self.make_type_info(\"E3\", mro=[self.fi, self.f2i, self.oi])\n\n # Generic class TypeInfos\n # G[T]\n self.gi = self.make_type_info(\"G\", mro=[self.oi], typevars=[\"T\"], variances=[variance])\n # G2[T]\n self.g2i = self.make_type_info(\"G2\", mro=[self.oi], typevars=[\"T\"], variances=[variance])\n # H[S, T]\n self.hi = self.make_type_info(\n \"H\", mro=[self.oi], typevars=[\"S\", \"T\"], variances=[variance, variance]\n )\n # GS[T, S] <: G[S]\n self.gsi = self.make_type_info(\n \"GS\",\n mro=[self.gi, self.oi],\n typevars=[\"T\", \"S\"],\n variances=[variance, variance],\n bases=[Instance(self.gi, [self.s])],\n )\n # GS2[S] <: G[S]\n self.gs2i = self.make_type_info(\n \"GS2\",\n mro=[self.gi, self.oi],\n typevars=[\"S\"],\n variances=[variance],\n bases=[Instance(self.gi, [self.s1])],\n )\n\n # list[T]\n self.std_listi = self.make_type_info(\n \"builtins.list\", mro=[self.oi], typevars=[\"T\"], variances=[variance]\n )\n\n # Instance types\n self.std_tuple = Instance(self.std_tuplei, [self.anyt]) # tuple\n self.type_type = Instance(self.type_typei, []) # type\n self.function = Instance(self.functioni, []) # function TODO\n self.str_type = Instance(self.str_type_info, [])\n self.bool_type = Instance(self.bool_type_info, [])\n self.a = Instance(self.ai, []) # A\n self.b = Instance(self.bi, []) # B\n self.c = Instance(self.ci, []) # C\n self.d = Instance(self.di, []) # D\n\n self.e = Instance(self.ei, []) # E\n self.e2 = Instance(self.e2i, []) # E2\n self.e3 = Instance(self.e3i, []) # E3\n\n self.f = Instance(self.fi, []) # F\n self.f2 = Instance(self.f2i, []) # F2\n self.f3 = Instance(self.f3i, []) # F3\n\n # Generic instance types\n self.ga = Instance(self.gi, [self.a]) # G[A]\n self.gb = Instance(self.gi, [self.b]) # G[B]\n self.gd = Instance(self.gi, [self.d]) # G[D]\n self.go = Instance(self.gi, [self.o]) # G[object]\n self.gt = Instance(self.gi, [self.t]) # G[T`1]\n self.gtf = Instance(self.gi, [self.tf]) # G[T`-1]\n self.gtf2 = Instance(self.gi, [self.tf2]) # G[T`-2]\n self.gs = Instance(self.gi, [self.s]) # G[S]\n self.gdyn = Instance(self.gi, [self.anyt]) # G[Any]\n self.gn = Instance(self.gi, [NoneType()]) # G[None]\n\n self.g2a = Instance(self.g2i, [self.a]) # G2[A]\n\n self.gsaa = Instance(self.gsi, [self.a, self.a]) # GS[A, A]\n self.gsab = Instance(self.gsi, [self.a, self.b]) # GS[A, B]\n self.gsba = Instance(self.gsi, [self.b, self.a]) # GS[B, A]\n\n self.gs2a = Instance(self.gs2i, [self.a]) # GS2[A]\n self.gs2b = Instance(self.gs2i, [self.b]) # GS2[B]\n self.gs2d = Instance(self.gs2i, [self.d]) # GS2[D]\n\n self.hab = Instance(self.hi, [self.a, self.b]) # H[A, B]\n self.haa = Instance(self.hi, [self.a, self.a]) # H[A, A]\n self.hbb = Instance(self.hi, [self.b, self.b]) # H[B, B]\n self.hts = Instance(self.hi, [self.t, self.s]) # H[T, S]\n self.had = Instance(self.hi, [self.a, self.d]) # H[A, D]\n self.hao = Instance(self.hi, [self.a, self.o]) # H[A, object]\n\n self.lsta = Instance(self.std_listi, [self.a]) # List[A]\n self.lstb = Instance(self.std_listi, [self.b]) # List[B]\n\n self.lit1 = LiteralType(1, self.a)\n self.lit2 = LiteralType(2, self.a)\n self.lit3 = LiteralType(\"foo\", self.d)\n self.lit4 = LiteralType(4, self.a)\n self.lit1_inst = Instance(self.ai, [], last_known_value=self.lit1)\n self.lit2_inst = Instance(self.ai, [], last_known_value=self.lit2)\n self.lit3_inst = Instance(self.di, [], last_known_value=self.lit3)\n self.lit4_inst = Instance(self.ai, [], last_known_value=self.lit4)\n\n self.lit_str1 = LiteralType(\"x\", self.str_type)\n self.lit_str2 = LiteralType(\"y\", self.str_type)\n self.lit_str3 = LiteralType(\"z\", self.str_type)\n self.lit_str1_inst = Instance(self.str_type_info, [], last_known_value=self.lit_str1)\n self.lit_str2_inst = Instance(self.str_type_info, [], last_known_value=self.lit_str2)\n self.lit_str3_inst = Instance(self.str_type_info, [], last_known_value=self.lit_str3)\n\n self.lit_false = LiteralType(False, self.bool_type)\n self.lit_true = LiteralType(True, self.bool_type)\n\n self.type_a = TypeType.make_normalized(self.a)\n self.type_b = TypeType.make_normalized(self.b)\n self.type_c = TypeType.make_normalized(self.c)\n self.type_d = TypeType.make_normalized(self.d)\n self.type_t = TypeType.make_normalized(self.t)\n self.type_any = TypeType.make_normalized(self.anyt)\n\n self._add_bool_dunder(self.bool_type_info)\n self._add_bool_dunder(self.ai)\n\n # TypeVars with non-trivial bounds\n self.ub = make_type_var(\"UB\", 5, [], self.b, variance) # UB`5 (type variable)\n self.uc = make_type_var(\"UC\", 6, [], self.c, variance) # UC`6 (type variable)\n\n def make_type_var_tuple(name: str, id: int, upper_bound: Type) -> TypeVarTupleType:\n return TypeVarTupleType(\n name,\n name,\n TypeVarId(id),\n upper_bound,\n self.std_tuple,\n AnyType(TypeOfAny.from_omitted_generics),\n )\n\n obj_tuple = self.std_tuple.copy_modified(args=[self.o])\n self.ts = make_type_var_tuple(\"Ts\", 1, obj_tuple) # Ts`1 (type var tuple)\n self.ss = make_type_var_tuple(\"Ss\", 2, obj_tuple) # Ss`2 (type var tuple)\n self.us = make_type_var_tuple(\"Us\", 3, obj_tuple) # Us`3 (type var tuple)\n\n self.gvi = self.make_type_info(\"GV\", mro=[self.oi], typevars=[\"Ts\"], typevar_tuple_index=0)\n self.gv2i = self.make_type_info(\n \"GV2\", mro=[self.oi], typevars=[\"T\", \"Ts\", \"S\"], typevar_tuple_index=1\n )\n\n def _add_bool_dunder(self, type_info: TypeInfo) -> None:\n signature = CallableType([], [], [], Instance(self.bool_type_info, []), self.function)\n bool_func = FuncDef(\"__bool__\", [], Block([]))\n bool_func.type = set_callable_name(signature, bool_func)\n type_info.names[bool_func.name] = SymbolTableNode(MDEF, bool_func)\n\n # Helper methods\n\n def callable(self, *a: Type) -> CallableType:\n \"\"\"callable(a1, ..., an, r) constructs a callable with argument types\n a1, ... an and return type r.\n \"\"\"\n return CallableType(\n list(a[:-1]), [ARG_POS] * (len(a) - 1), [None] * (len(a) - 1), a[-1], self.function\n )\n\n def callable_type(self, *a: Type) -> CallableType:\n \"\"\"callable_type(a1, ..., an, r) constructs a callable with\n argument types a1, ... an and return type r, and which\n represents a type.\n \"\"\"\n return CallableType(\n list(a[:-1]), [ARG_POS] * (len(a) - 1), [None] * (len(a) - 1), a[-1], self.type_type\n )\n\n def callable_default(self, min_args: int, *a: Type) -> CallableType:\n \"\"\"callable_default(min_args, a1, ..., an, r) constructs a\n callable with argument types a1, ... an and return type r,\n with min_args mandatory fixed arguments.\n \"\"\"\n n = len(a) - 1\n return CallableType(\n list(a[:-1]),\n [ARG_POS] * min_args + [ARG_OPT] * (n - min_args),\n [None] * n,\n a[-1],\n self.function,\n )\n\n def callable_var_arg(self, min_args: int, *a: Type) -> CallableType:\n \"\"\"callable_var_arg(min_args, a1, ..., an, r) constructs a callable\n with argument types a1, ... *an and return type r.\n \"\"\"\n n = len(a) - 1\n return CallableType(\n list(a[:-1]),\n [ARG_POS] * min_args + [ARG_OPT] * (n - 1 - min_args) + [ARG_STAR],\n [None] * n,\n a[-1],\n self.function,\n )\n\n def make_type_info(\n self,\n name: str,\n module_name: str | None = None,\n is_abstract: bool = False,\n mro: list[TypeInfo] | None = None,\n bases: list[Instance] | None = None,\n typevars: list[str] | None = None,\n typevar_tuple_index: int | None = None,\n variances: list[int] | None = None,\n ) -> TypeInfo:\n \"\"\"Make a TypeInfo suitable for use in unit tests.\"\"\"\n\n class_def = ClassDef(name, Block([]), None, [])\n class_def.fullname = name\n\n if module_name is None:\n if \".\" in name:\n module_name = name.rsplit(\".\", 1)[0]\n else:\n module_name = \"__main__\"\n\n if typevars:\n v: list[TypeVarLikeType] = []\n for id, n in enumerate(typevars, 1):\n if typevar_tuple_index is not None and id - 1 == typevar_tuple_index:\n v.append(\n TypeVarTupleType(\n n,\n n,\n TypeVarId(id),\n self.std_tuple.copy_modified(args=[self.o]),\n self.std_tuple.copy_modified(args=[self.o]),\n AnyType(TypeOfAny.from_omitted_generics),\n )\n )\n else:\n if variances:\n variance = variances[id - 1]\n else:\n variance = COVARIANT\n v.append(\n TypeVarType(\n n,\n n,\n TypeVarId(id),\n [],\n self.o,\n AnyType(TypeOfAny.from_omitted_generics),\n variance=variance,\n )\n )\n class_def.type_vars = v\n\n info = TypeInfo(SymbolTable(), class_def, module_name)\n if mro is None:\n mro = []\n if name != \"builtins.object\":\n mro.append(self.oi)\n info.mro = [info] + mro\n if bases is None:\n if mro:\n # By default, assume that there is a single non-generic base.\n bases = [Instance(mro[0], [])]\n else:\n bases = []\n info.bases = bases\n\n return info\n\n def def_alias_1(self, base: Instance) -> tuple[TypeAliasType, Type]:\n A = TypeAliasType(None, [])\n target = Instance(\n self.std_tuplei, [UnionType([base, A])]\n ) # A = Tuple[Union[base, A], ...]\n AN = TypeAlias(target, \"__main__.A\", -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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/typefixture.py","language":"Python","license":"NOASSERTION","size":15817} {"code":"from __future__ import annotations\n\nimport re\nfrom collections import defaultdict\nfrom typing import Iterator\n\nfrom mypy.test.data import DataDrivenTestCase, DataFileCollector, DataFileFix, parse_test_data\n\n\ndef update_testcase_output(\n testcase: DataDrivenTestCase, actual: list[str], *, incremental_step: int\n) -> None:\n if testcase.xfail:\n return\n collector = testcase.parent\n assert isinstance(collector, DataFileCollector)\n for fix in _iter_fixes(testcase, actual, incremental_step=incremental_step):\n collector.enqueue_fix(fix)\n\n\ndef _iter_fixes(\n testcase: DataDrivenTestCase, actual: list[str], *, incremental_step: int\n) -> Iterator[DataFileFix]:\n reports_by_line: dict[tuple[str, int], list[tuple[str, str]]] = defaultdict(list)\n for error_line in actual:\n comment_match = re.match(\n r\"^(?P[^:]+):(?P\\d+): (?Perror|note|warning): (?P.+)$\",\n error_line,\n )\n if comment_match:\n filename = comment_match.group(\"filename\")\n lineno = int(comment_match.group(\"lineno\"))\n severity = comment_match.group(\"severity\")\n msg = comment_match.group(\"msg\")\n reports_by_line[filename, lineno].append((severity, msg))\n\n test_items = parse_test_data(testcase.data, testcase.name)\n\n # If we have [out] and\/or [outN], we update just those sections.\n if any(re.match(r\"^out\\d*$\", test_item.id) for test_item in test_items):\n for test_item in test_items:\n if (incremental_step < 2 and test_item.id == \"out\") or (\n incremental_step >= 2 and test_item.id == f\"out{incremental_step}\"\n ):\n yield DataFileFix(\n lineno=testcase.line + test_item.line - 1,\n end_lineno=testcase.line + test_item.end_line - 1,\n lines=actual + [\"\"] * test_item.trimmed_newlines,\n )\n\n return\n\n # Update assertion comments within the sections\n for test_item in test_items:\n if test_item.id == \"case\":\n source_lines = test_item.data\n file_path = \"main\"\n elif test_item.id == \"file\":\n source_lines = test_item.data\n file_path = f\"tmp\/{test_item.arg}\"\n else:\n continue # other sections we don't touch\n\n fix_lines = []\n for lineno, source_line in enumerate(source_lines, start=1):\n reports = reports_by_line.get((file_path, lineno))\n comment_match = re.search(r\"(?P\\s+)(?P# [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 emtpy 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/update_data.py","language":"Python","license":"NOASSERTION","size":3676} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/test\/visitors.py","language":"Python","license":"NOASSERTION","size":2089} {"code":"\"\"\"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\n\ndef all_yield_from_expressions(node: Node) -> list[tuple[YieldFromExpr, bool]]:\n v = YieldFromCollector()\n node.accept(v)\n return v.yield_from_expressions\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/traverser.py","language":"Python","license":"NOASSERTION","size":27003} {"code":"\"\"\"Base visitor that implements an identity AST transform.\n\nSubclass TransformVisitor to perform non-trivial transformations.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Iterable, 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))\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/treetransform.py","language":"Python","license":"NOASSERTION","size":28486} {"code":"from __future__ import annotations\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: TypeVarLikeScope | None = self\n while it is not None and it.is_class_scope:\n it = it.parent\n return it\n\n def allow_binding(self, fullname: str) -> bool:\n if fullname in self.scope:\n return False\n elif self.parent and not self.parent.allow_binding(fullname):\n return False\n elif self.prohibited and not self.prohibited.allow_binding(fullname):\n return False\n return True\n\n def method_frame(self, namespace: str) -> TypeVarLikeScope:\n \"\"\"A new scope frame for binding a method\"\"\"\n return TypeVarLikeScope(self, False, None, namespace=namespace)\n\n def class_frame(self, namespace: str) -> TypeVarLikeScope:\n \"\"\"A new scope frame for binding a class. Prohibits *this* class's tvars\"\"\"\n return TypeVarLikeScope(self.get_function_scope(), True, self, namespace=namespace)\n\n def new_unique_func_id(self) -> TypeVarId:\n \"\"\"Used by plugin-like code that needs to make synthetic generic functions.\"\"\"\n self.func_id -= 1\n return TypeVarId(self.func_id)\n\n def bind_new(self, name: str, tvar_expr: TypeVarLikeExpr) -> 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 )\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/tvar_scope.py","language":"Python","license":"NOASSERTION","size":5895} {"code":"\"\"\"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 typing import Any, Callable, Final, Generic, Iterable, Sequence, TypeVar, cast\n\nfrom mypy_extensions import mypyc_attr, trait\n\nfrom mypy.types import (\n AnyType,\n CallableArgument,\n CallableType,\n DeletedType,\n EllipsisType,\n ErasedType,\n Instance,\n LiteralType,\n NoneType,\n Overloaded,\n Parameters,\n ParamSpecType,\n PartialType,\n PlaceholderType,\n RawExpressionType,\n TupleType,\n Type,\n TypeAliasType,\n TypedDictType,\n TypeList,\n TypeType,\n TypeVarLikeType,\n TypeVarTupleType,\n TypeVarType,\n UnboundType,\n UninhabitedType,\n UnionType,\n UnpackType,\n get_proper_type,\n)\n\nT = TypeVar(\"T\")\n\n\n@trait\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass TypeVisitor(Generic[T]):\n \"\"\"Visitor class for types (Type subclasses).\n\n The parameter T is the return type of the visit methods.\n \"\"\"\n\n @abstractmethod\n def visit_unbound_type(self, t: UnboundType) -> T:\n pass\n\n @abstractmethod\n def visit_any(self, t: AnyType) -> T:\n pass\n\n @abstractmethod\n def visit_none_type(self, t: NoneType) -> T:\n pass\n\n @abstractmethod\n def visit_uninhabited_type(self, t: UninhabitedType) -> T:\n pass\n\n @abstractmethod\n def visit_erased_type(self, t: ErasedType) -> T:\n pass\n\n @abstractmethod\n def visit_deleted_type(self, t: DeletedType) -> T:\n pass\n\n @abstractmethod\n def visit_type_var(self, t: TypeVarType) -> T:\n pass\n\n @abstractmethod\n def visit_param_spec(self, t: ParamSpecType) -> T:\n pass\n\n @abstractmethod\n def visit_parameters(self, t: Parameters) -> T:\n pass\n\n @abstractmethod\n def visit_type_var_tuple(self, t: TypeVarTupleType) -> T:\n pass\n\n @abstractmethod\n def visit_instance(self, t: Instance) -> T:\n pass\n\n @abstractmethod\n def visit_callable_type(self, t: CallableType) -> T:\n pass\n\n @abstractmethod\n def visit_overloaded(self, t: Overloaded) -> T:\n pass\n\n @abstractmethod\n def visit_tuple_type(self, t: TupleType) -> T:\n pass\n\n @abstractmethod\n def visit_typeddict_type(self, t: TypedDictType) -> T:\n pass\n\n @abstractmethod\n def visit_literal_type(self, t: LiteralType) -> T:\n pass\n\n @abstractmethod\n def visit_union_type(self, t: UnionType) -> T:\n pass\n\n @abstractmethod\n def visit_partial_type(self, t: PartialType) -> T:\n pass\n\n @abstractmethod\n def visit_type_type(self, t: TypeType) -> T:\n pass\n\n @abstractmethod\n def visit_type_alias_type(self, t: TypeAliasType) -> T:\n pass\n\n @abstractmethod\n def visit_unpack_type(self, t: UnpackType) -> T:\n pass\n\n\n@trait\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass SyntheticTypeVisitor(TypeVisitor[T]):\n \"\"\"A TypeVisitor that also knows how to visit synthetic AST constructs.\n\n Not just real types.\n \"\"\"\n\n @abstractmethod\n def visit_type_list(self, t: TypeList) -> T:\n pass\n\n @abstractmethod\n def visit_callable_argument(self, t: CallableArgument) -> T:\n pass\n\n @abstractmethod\n def visit_ellipsis_type(self, t: EllipsisType) -> T:\n pass\n\n @abstractmethod\n def visit_raw_expression_type(self, t: RawExpressionType) -> T:\n pass\n\n @abstractmethod\n def visit_placeholder_type(self, t: PlaceholderType) -> T:\n pass\n\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass TypeTranslator(TypeVisitor[Type]):\n \"\"\"Identity type transformation.\n\n Subclass this and override some methods to implement a non-trivial\n transformation.\n\n We cache the results of certain translations to avoid\n massively expanding the sizes of types.\n \"\"\"\n\n def __init__(self, cache: dict[Type, Type] | None = None) -> None:\n # For deduplication of results\n self.cache = cache\n\n def get_cached(self, t: Type) -> Type | None:\n if self.cache is None:\n return None\n return self.cache.get(t)\n\n def set_cached(self, orig: Type, new: Type) -> None:\n if self.cache is None:\n # Minor optimization: construct lazily\n self.cache = {}\n self.cache[orig] = new\n\n def visit_unbound_type(self, t: UnboundType) -> Type:\n return t\n\n def visit_any(self, t: AnyType) -> Type:\n return t\n\n def visit_none_type(self, t: NoneType) -> Type:\n return t\n\n def visit_uninhabited_type(self, t: UninhabitedType) -> Type:\n return t\n\n def visit_erased_type(self, t: ErasedType) -> Type:\n return t\n\n def visit_deleted_type(self, t: DeletedType) -> Type:\n return t\n\n def visit_instance(self, t: Instance) -> Type:\n last_known_value: LiteralType | None = None\n if t.last_known_value is not None:\n raw_last_known_value = t.last_known_value.accept(self)\n assert isinstance(raw_last_known_value, LiteralType) # type: ignore[misc]\n last_known_value = raw_last_known_value\n return Instance(\n typ=t.type,\n args=self.translate_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\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 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_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_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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/type_visitor.py","language":"Python","license":"NOASSERTION","size":19402} {"code":"\"\"\"Semantic analysis of types\"\"\"\n\nfrom __future__ import annotations\n\nimport itertools\nfrom contextlib import contextmanager\nfrom typing import Callable, Final, Iterable, Iterator, List, Sequence, Tuple, TypeVar\nfrom typing_extensions import Protocol\n\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 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 LiteralType,\n NoneType,\n Overloaded,\n Parameters,\n ParamSpecFlavor,\n ParamSpecType,\n PartialType,\n PlaceholderType,\n ProperType,\n RawExpressionType,\n ReadOnlyType,\n RequiredType,\n SyntheticTypeVisitor,\n TrivialSyntheticTypeTranslator,\n TupleType,\n Type,\n TypeAliasType,\n TypedDictType,\n TypeList,\n TypeOfAny,\n TypeQuery,\n TypeType,\n TypeVarId,\n TypeVarLikeType,\n TypeVarTupleType,\n TypeVarType,\n UnboundType,\n UninhabitedType,\n UnionType,\n UnpackType,\n callable_with_ellipsis,\n find_unpack_in_list,\n flatten_nested_tuples,\n get_proper_type,\n has_type_vars,\n)\nfrom mypy.types_utils import is_bad_type_type_item\nfrom mypy.typevars import fill_typevars\n\nT = TypeVar(\"T\")\n\ntype_constructors: Final = {\n \"typing.Callable\",\n \"typing.Optional\",\n \"typing.Tuple\",\n \"typing.Type\",\n \"typing.Union\",\n *LITERAL_TYPE_NAMES,\n *ANNOTATED_TYPE_NAMES,\n}\n\nARG_KINDS_BY_CONSTRUCTOR: Final = {\n \"mypy_extensions.Arg\": ARG_POS,\n \"mypy_extensions.DefaultArg\": ARG_OPT,\n \"mypy_extensions.NamedArg\": ARG_NAMED,\n \"mypy_extensions.DefaultNamedArg\": ARG_NAMED_OPT,\n \"mypy_extensions.VarArg\": ARG_STAR,\n \"mypy_extensions.KwArg\": ARG_STAR2,\n}\n\nGENERIC_STUB_NOT_AT_RUNTIME_TYPES: Final = {\n \"queue.Queue\",\n \"builtins._PathLike\",\n \"asyncio.futures.Future\",\n}\n\nSELF_TYPE_NAMES: Final = {\"typing.Self\", \"typing_extensions.Self\"}\n\n\ndef analyze_type_alias(\n type: Type,\n api: SemanticAnalyzerCoreInterface,\n tvar_scope: TypeVarLikeScope,\n plugin: Plugin,\n options: Options,\n 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 is_typeshed_stub,\n defining_alias=True,\n allow_placeholder=allow_placeholder,\n prohibit_self_type=\"type alias target\",\n allowed_alias_tvars=allowed_alias_tvars,\n alias_type_params_names=alias_type_params_names,\n python_3_12_type_alias=python_3_12_type_alias,\n )\n analyzer.in_dynamic_func = in_dynamic_func\n analyzer.global_scope = global_scope\n res = type.accept(analyzer)\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 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_param_spec_literals: bool = False,\n allow_unpack: bool = False,\n report_invalid_types: bool = True,\n prohibit_self_type: 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 # 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.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 # 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, name: str) -> SymbolTableNode:\n return self.api.lookup_fully_qualified(name)\n\n def visit_unbound_type(self, t: UnboundType, defining_literal: bool = False) -> Type:\n typ = self.visit_unbound_type_nonoptional(t, defining_literal)\n if t.optional:\n # We don't need to worry about double-wrapping Optionals or\n # wrapping Anys: Union simplification will take care of that.\n return make_optional_type(typ)\n return typ\n\n def not_declared_in_type_params(self, tvar_name: str) -> bool:\n return (\n self.alias_type_params_names is not None\n and tvar_name not in self.alias_type_params_names\n )\n\n def visit_unbound_type_nonoptional(self, t: UnboundType, defining_literal: bool) -> Type:\n sym = self.lookup_qualified(t.name, t)\n 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 if self.defining_alias and self.not_declared_in_type_params(t.name):\n msg = f'ParamSpec \"{t.name}\" is not included in type_params'\n else:\n msg = f'ParamSpec \"{t.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 # Change the line number\n return ParamSpecType(\n tvar_def.name,\n tvar_def.fullname,\n tvar_def.id,\n tvar_def.flavor,\n tvar_def.upper_bound,\n tvar_def.default,\n line=t.line,\n column=t.column,\n )\n if (\n isinstance(sym.node, TypeVarExpr)\n and self.defining_alias\n and not defining_literal\n and (tvar_def is None or tvar_def not in self.allowed_alias_tvars)\n ):\n if self.not_declared_in_type_params(t.name):\n if self.python_3_12_type_alias:\n msg = message_registry.TYPE_PARAMETERS_SHOULD_BE_DECLARED.format(\n f'\"{t.name}\"'\n )\n else:\n msg = f'Type variable \"{t.name}\" is not included in type_params'\n else:\n msg = f'Can\\'t use bound type variable \"{t.name}\" to define generic alias'\n self.fail(msg, t, code=codes.VALID_TYPE)\n return AnyType(TypeOfAny.from_error)\n if isinstance(sym.node, TypeVarExpr) and tvar_def is not None:\n assert isinstance(tvar_def, TypeVarType)\n if len(t.args) > 0:\n self.fail(\n f'Type variable \"{t.name}\" used with arguments', t, code=codes.VALID_TYPE\n )\n # Change the line number\n return tvar_def.copy_modified(line=t.line, column=t.column)\n if isinstance(sym.node, TypeVarTupleExpr) and (\n tvar_def is not None\n and self.defining_alias\n and tvar_def not in self.allowed_alias_tvars\n ):\n if self.not_declared_in_type_params(t.name):\n msg = f'Type variable \"{t.name}\" is not included in type_params'\n else:\n msg = f'Can\\'t use bound type variable \"{t.name}\" to define generic alias'\n self.fail(msg, t, code=codes.VALID_TYPE)\n return AnyType(TypeOfAny.from_error)\n if isinstance(sym.node, TypeVarTupleExpr):\n if tvar_def is None:\n if self.allow_unbound_tvars:\n return t\n if self.defining_alias and self.not_declared_in_type_params(t.name):\n if self.python_3_12_type_alias:\n msg = message_registry.TYPE_PARAMETERS_SHOULD_BE_DECLARED.format(\n f'\"{t.name}\"'\n )\n else:\n msg = f'TypeVarTuple \"{t.name}\" is not included in type_params'\n else:\n msg = f'TypeVarTuple \"{t.name}\" is unbound'\n self.fail(msg, t, code=codes.VALID_TYPE)\n return AnyType(TypeOfAny.from_error)\n assert isinstance(tvar_def, TypeVarTupleType)\n if not self.allow_type_var_tuple:\n self.fail(\n f'TypeVarTuple \"{t.name}\" is only valid with an unpack',\n t,\n code=codes.VALID_TYPE,\n )\n return AnyType(TypeOfAny.from_error)\n if len(t.args) > 0:\n self.fail(\n f'Type variable \"{t.name}\" used with arguments', t, code=codes.VALID_TYPE\n )\n\n # Change the line number\n return TypeVarTupleType(\n tvar_def.name,\n tvar_def.fullname,\n tvar_def.id,\n tvar_def.upper_bound,\n sym.node.tuple_fallback,\n tvar_def.default,\n line=t.line,\n column=t.column,\n )\n special = self.try_analyze_special_unbound_type(t, fullname)\n if special is not None:\n return special\n if isinstance(node, TypeAlias):\n self.aliases_used.add(fullname)\n an_args = self.anal_array(\n t.args,\n allow_param_spec=True,\n allow_param_spec_literals=node.has_param_spec_type,\n allow_unpack=True, # Fixed length unpacks can be used for non-variadic aliases.\n )\n if node.has_param_spec_type and len(node.alias_tvars) == 1:\n an_args = self.pack_paramspec_args(an_args)\n\n disallow_any = self.options.disallow_any_generics and not self.is_typeshed_stub\n res = instantiate_type_alias(\n node,\n an_args,\n self.fail,\n node.no_args,\n t,\n self.options,\n unexpanded_type=t,\n disallow_any=disallow_any,\n empty_tuple_index=t.empty_tuple_index,\n )\n # The only case where instantiate_type_alias() can return an incorrect instance is\n # when it is top-level instance, so no need to recurse.\n if (\n isinstance(res, ProperType)\n and isinstance(res, Instance)\n and not (self.defining_alias and self.nesting_level == 0)\n and not validate_instance(res, self.fail, t.empty_tuple_index)\n ):\n fix_instance(\n res,\n self.fail,\n self.note,\n disallow_any=disallow_any,\n options=self.options,\n use_generic_error=True,\n unexpanded_type=t,\n )\n if node.eager:\n res = get_proper_type(res)\n return res\n elif isinstance(node, TypeInfo):\n return self.analyze_type_with_type_info(node, t.args, t, t.empty_tuple_index)\n elif node.fullname in TYPE_ALIAS_NAMES:\n return AnyType(TypeOfAny.special_form)\n # Concatenate is an operator, no need for a proper type\n elif node.fullname in (\"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 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 == \"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.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 if len(t.args) != 1:\n type_str = \"Type[...]\" if fullname == \"typing.Type\" else \"type[...]\"\n self.fail(\n type_str + \" must have exactly one type argument\", t, code=codes.VALID_TYPE\n )\n item = self.anal_type(t.args[0])\n if is_bad_type_type_item(item):\n self.fail(\"Type[...] can't contain another Type[...]\", 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 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])\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(t.args[0])\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 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 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 if len(args) > 0 and info.fullname == \"builtins.tuple\":\n fallback = Instance(info, [AnyType(TypeOfAny.special_form)], ctx.line)\n return TupleType(self.anal_array(args, allow_unpack=True), fallback, ctx.line)\n\n # Analyze arguments and (usually) construct Instance type. The\n # number of type arguments and their values are\n # checked only later, since we do not always know the\n # valid count at this point. Thus we may construct an\n # Instance with an invalid number of type arguments.\n #\n # We allow ParamSpec literals based on a heuristic: it will be\n # checked later anyways but the error message may be worse.\n instance = Instance(\n info,\n self.anal_array(\n args,\n allow_param_spec=True,\n allow_param_spec_literals=info.has_param_spec_type,\n allow_unpack=True, # Fixed length tuples can be used for non-variadic types.\n ),\n ctx.line,\n ctx.column,\n )\n 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 # If, in the distant future, we decide to permit things like\n # `def foo(x: Color.RED) -> None: ...`, we can remove that\n # check entirely.\n if (\n isinstance(sym.node, Var)\n and sym.node.info\n and sym.node.info.is_enum\n and not sym.node.name.startswith(\"__\")\n ):\n value = sym.node.name\n base_enum_short_name = sym.node.info.name\n if not defining_literal:\n msg = message_registry.INVALID_TYPE_RAW_ENUM_VALUE.format(\n base_enum_short_name, value\n )\n self.fail(msg.value, t, code=msg.code)\n return AnyType(TypeOfAny.from_error)\n return LiteralType(\n value=value,\n fallback=Instance(sym.node.info, [], line=t.line, column=t.column),\n line=t.line,\n column=t.column,\n )\n\n # None of the above options worked. We parse the args (if there are any)\n # to make sure there are no remaining semanal-only types, then give up.\n t = t.copy_modified(args=self.anal_array(t.args))\n # TODO: Move this message building logic to messages.py.\n notes: list[str] = []\n error_code = codes.VALID_TYPE\n if isinstance(sym.node, Var):\n notes.append(\n \"See https:\/\/mypy.readthedocs.io\/en\/\"\n \"stable\/common_issues.html#variables-vs-type-aliases\"\n )\n message = 'Variable \"{}\" is not valid as a type'\n elif isinstance(sym.node, (SYMBOL_FUNCBASE_TYPES, Decorator)):\n message = 'Function \"{}\" is not valid as a type'\n if name == \"builtins.any\":\n notes.append('Perhaps you meant \"typing.Any\" instead of \"any\"?')\n elif name == \"builtins.callable\":\n notes.append('Perhaps you meant \"typing.Callable\" instead of \"callable\"?')\n else:\n notes.append('Perhaps you need \"Callable[...]\" or a callback protocol?')\n elif isinstance(sym.node, MypyFile):\n message = 'Module \"{}\" is not valid as a type'\n notes.append(\"Perhaps you meant to use a protocol matching the module structure?\")\n elif unbound_tvar:\n assert isinstance(sym.node, TypeVarLikeExpr)\n if sym.node.is_new_style:\n # PEP 695 type paramaters 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 (\n '(Hint: Use \"Generic[{}]\" or \"Protocol[{}]\" base class'\n ' to bind \"{}\" inside a class)'\n ).format(short, short, short)\n )\n notes.append(\n '(Hint: Use \"{}\" in function signature to bind \"{}\"'\n \" inside a function)\".format(short, short)\n )\n else:\n message = 'Cannot interpret reference \"{}\" as a type'\n if not defining_literal:\n # Literal check already gives a custom error. Avoid duplicating errors.\n self.fail(message.format(name), t, code=error_code)\n for note in notes:\n self.note(note, t, code=error_code)\n\n # TODO: Would it be better to always return Any instead of UnboundType\n # in case of an error? On one hand, UnboundType has a name so error messages\n # are more detailed, on the other hand, some of them may be bogus,\n # see https:\/\/github.com\/python\/mypy\/issues\/4987.\n return t\n\n def visit_any(self, t: AnyType) -> Type:\n return t\n\n def visit_none_type(self, t: NoneType) -> Type:\n return t\n\n def visit_uninhabited_type(self, t: UninhabitedType) -> Type:\n return t\n\n def visit_erased_type(self, t: ErasedType) -> Type:\n # This type should exist only temporarily during type inference\n assert False, \"Internal error: Unexpected erased type\"\n\n def visit_deleted_type(self, t: DeletedType) -> Type:\n return t\n\n def visit_type_list(self, t: TypeList) -> Type:\n # Parameters literal (Z[[int, str, Whatever]])\n if self.allow_param_spec_literals:\n params = self.analyze_callable_args(t)\n if params:\n ts, kinds, names = params\n # bind these types\n return Parameters(self.anal_array(ts), kinds, names, line=t.line, column=t.column)\n else:\n return AnyType(TypeOfAny.from_error)\n else:\n self.fail(\n 'Bracketed expression \"[...]\" is not valid as a type', t, code=codes.VALID_TYPE\n )\n if len(t.items) == 1:\n self.note('Did you mean \"List[...]\"?', t)\n return AnyType(TypeOfAny.from_error)\n\n def visit_callable_argument(self, t: CallableArgument) -> Type:\n self.fail(\"Invalid type\", t, code=codes.VALID_TYPE)\n return AnyType(TypeOfAny.from_error)\n\n def visit_instance(self, t: Instance) -> Type:\n return t\n\n def visit_type_alias_type(self, t: TypeAliasType) -> Type:\n # TODO: should we do something here?\n return t\n\n def visit_type_var(self, t: TypeVarType) -> Type:\n return t\n\n def visit_param_spec(self, t: ParamSpecType) -> Type:\n return t\n\n def visit_type_var_tuple(self, t: TypeVarTupleType) -> Type:\n return t\n\n def visit_unpack_type(self, t: UnpackType) -> Type:\n if not self.allow_unpack:\n self.fail(message_registry.INVALID_UNPACK_POSITION, t.type, code=codes.VALID_TYPE)\n return AnyType(TypeOfAny.from_error)\n self.allow_type_var_tuple = True\n result = UnpackType(self.anal_type(t.type), from_star_syntax=t.from_star_syntax)\n self.allow_type_var_tuple = False\n return result\n\n def visit_parameters(self, t: Parameters) -> Type:\n raise NotImplementedError(\"ParamSpec literals cannot have unbound TypeVars\")\n\n def visit_callable_type(\n self, t: CallableType, nested: bool = True, namespace: str = \"\"\n ) -> Type:\n # Every Callable can bind its own type variables, if they're not in the outer scope\n # TODO: attach namespace for nested free type variables (these appear in return type only).\n with self.tvar_scope_frame(namespace=namespace):\n unpacked_kwargs = t.unpack_kwargs\n if self.defining_alias:\n variables = t.variables\n else:\n variables, _ = self.bind_function_type_variables(t, t)\n type_guard = self.anal_type_guard(t.ret_type)\n type_is = self.anal_type_is(t.ret_type)\n arg_kinds = t.arg_kinds\n if len(arg_kinds) >= 2 and arg_kinds[-2] == ARG_STAR and arg_kinds[-1] == ARG_STAR2:\n arg_types = self.anal_array(t.arg_types[:-2], nested=nested) + [\n self.anal_star_arg_type(t.arg_types[-2], ARG_STAR, nested=nested),\n self.anal_star_arg_type(t.arg_types[-1], ARG_STAR2, nested=nested),\n ]\n # If nested is True, it means we are analyzing a Callable[...] type, rather\n # than a function definition type. We need to \"unpack\" ** TypedDict annotation\n # here (for function definitions it is done in semanal).\n if nested and isinstance(arg_types[-1], UnpackType):\n # TODO: it would be better to avoid this get_proper_type() call.\n unpacked = get_proper_type(arg_types[-1].type)\n if isinstance(unpacked, TypedDictType):\n arg_types[-1] = unpacked\n unpacked_kwargs = True\n arg_types = self.check_unpacks_in_list(arg_types)\n else:\n star_index = None\n if ARG_STAR in arg_kinds:\n star_index = arg_kinds.index(ARG_STAR)\n star2_index = None\n if ARG_STAR2 in arg_kinds:\n star2_index = arg_kinds.index(ARG_STAR2)\n arg_types = []\n for i, ut in enumerate(t.arg_types):\n at = self.anal_type(\n ut, nested=nested, allow_unpack=i in (star_index, star2_index)\n )\n if nested and isinstance(at, UnpackType) and i == star_index:\n # TODO: it would be better to avoid this get_proper_type() call.\n p_at = get_proper_type(at.type)\n if isinstance(p_at, TypedDictType) and not at.from_star_syntax:\n # Automatically detect Unpack[Foo] in Callable as backwards\n # compatible syntax for **Foo, if Foo is a TypedDict.\n at = p_at\n arg_kinds[i] = ARG_STAR2\n unpacked_kwargs = True\n arg_types.append(at)\n if nested:\n arg_types = self.check_unpacks_in_list(arg_types)\n # If there were multiple (invalid) unpacks, the arg types list will become shorter,\n # we need to trim the kinds\/names as well to avoid crashes.\n arg_kinds = t.arg_kinds[: len(arg_types)]\n arg_names = t.arg_names[: len(arg_types)]\n\n ret = t.copy_modified(\n arg_types=arg_types,\n arg_kinds=arg_kinds,\n arg_names=arg_names,\n ret_type=self.anal_type(t.ret_type, nested=nested),\n # If the fallback isn't filled in yet,\n # its type will be the falsey FakeInfo\n fallback=(t.fallback if t.fallback.type else self.named_type(\"builtins.function\")),\n variables=self.anal_var_defs(variables),\n type_guard=type_guard,\n type_is=type_is,\n unpack_kwargs=unpacked_kwargs,\n )\n return ret\n\n def anal_type_guard(self, t: Type) -> Type | None:\n if isinstance(t, UnboundType):\n sym = self.lookup_qualified(t.name, t)\n if sym is not None and sym.node is not None:\n return self.anal_type_guard_arg(t, sym.node.fullname)\n # TODO: What if it's an Instance? Then use t.type.fullname?\n return None\n\n def anal_type_guard_arg(self, t: UnboundType, fullname: str) -> Type | None:\n if fullname in (\"typing_extensions.TypeGuard\", \"typing.TypeGuard\"):\n if len(t.args) != 1:\n self.fail(\n \"TypeGuard must have exactly one type argument\", t, code=codes.VALID_TYPE\n )\n return AnyType(TypeOfAny.from_error)\n return self.anal_type(t.args[0])\n return None\n\n def anal_type_is(self, t: Type) -> Type | None:\n if isinstance(t, UnboundType):\n sym = self.lookup_qualified(t.name, t)\n if sym is not None and sym.node is not None:\n return self.anal_type_is_arg(t, sym.node.fullname)\n # TODO: What if it's an Instance? Then use t.type.fullname?\n return None\n\n def anal_type_is_arg(self, t: UnboundType, fullname: str) -> Type | None:\n if fullname in (\"typing_extensions.TypeIs\", \"typing.TypeIs\"):\n if len(t.args) != 1:\n self.fail(\"TypeIs must have exactly one type argument\", t, code=codes.VALID_TYPE)\n return AnyType(TypeOfAny.from_error)\n return self.anal_type(t.args[0])\n return None\n\n def anal_star_arg_type(self, t: Type, kind: ArgKind, nested: bool) -> 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 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 self.anal_type(t, nested=nested, allow_unpack=True)\n\n def visit_overloaded(self, t: Overloaded) -> Type:\n # Overloaded types are manually constructed in semanal.py by analyzing the\n # AST and combining together the Callable types this visitor converts.\n #\n # So if we're ever asked to reanalyze an Overloaded type, we know it's\n # fine to just return it as-is.\n return t\n\n def visit_tuple_type(self, t: TupleType) -> Type:\n # Types such as (t1, t2, ...) only allowed in assignment statements. They'll\n # generate errors elsewhere, and Tuple[t1, t2, ...] must be used instead.\n if t.implicit and not self.allow_tuple_literal:\n self.fail(\"Syntax error in type annotation\", t, code=codes.SYNTAX)\n if len(t.items) == 0:\n self.note(\n \"Suggestion: Use Tuple[()] instead of () for an empty tuple, or \"\n \"None for a function without a return value\",\n t,\n code=codes.SYNTAX,\n )\n elif len(t.items) == 1:\n self.note(\"Suggestion: Is there a spurious trailing comma?\", t, code=codes.SYNTAX)\n else:\n self.note(\n \"Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn)\",\n t,\n code=codes.SYNTAX,\n )\n return AnyType(TypeOfAny.from_error)\n\n any_type = AnyType(TypeOfAny.special_form)\n # If the fallback isn't filled in yet, its type will be the falsey FakeInfo\n fallback = (\n t.partial_fallback\n if t.partial_fallback.type\n else self.named_type(\"builtins.tuple\", [any_type])\n )\n return TupleType(self.anal_array(t.items, allow_unpack=True), fallback, t.line)\n\n def visit_typeddict_type(self, t: TypedDictType) -> Type:\n req_keys = set()\n readonly_keys = set()\n items = {}\n for item_name, item_type in t.items.items():\n # TODO: rework\n analyzed = self.anal_type(item_type, allow_typed_dict_special_forms=True)\n if isinstance(analyzed, RequiredType):\n if analyzed.required:\n req_keys.add(item_name)\n analyzed = analyzed.item\n else:\n # Keys are required by default.\n req_keys.add(item_name)\n if isinstance(analyzed, ReadOnlyType):\n readonly_keys.add(item_name)\n analyzed = analyzed.item\n items[item_name] = analyzed\n if t.fallback.type is MISSING_FALLBACK: # anonymous\/inline TypedDict\n if INLINE_TYPEDDICT not in self.options.enable_incomplete_feature:\n self.fail(\n \"Inline TypedDict is experimental,\"\n \" must be enabled with --enable-incomplete-feature=InlineTypedDict\",\n t,\n )\n required_keys = req_keys\n fallback = self.named_type(\"typing._TypedDict\")\n for typ in t.extra_items_from:\n analyzed = self.analyze_type(typ)\n p_analyzed = get_proper_type(analyzed)\n if not isinstance(p_analyzed, TypedDictType):\n if not isinstance(p_analyzed, (AnyType, PlaceholderType)):\n self.fail(\"Can only merge-in other TypedDict\", t, code=codes.VALID_TYPE)\n continue\n for sub_item_name, sub_item_type in p_analyzed.items.items():\n if sub_item_name in items:\n self.fail(TYPEDDICT_OVERRIDE_MERGE.format(sub_item_name), t)\n continue\n items[sub_item_name] = sub_item_type\n if sub_item_name in p_analyzed.required_keys:\n req_keys.add(sub_item_name)\n if sub_item_name in p_analyzed.readonly_keys:\n readonly_keys.add(sub_item_name)\n else:\n required_keys = t.required_keys\n fallback = t.fallback\n return TypedDictType(items, required_keys, readonly_keys, fallback, t.line, t.column)\n\n def visit_raw_expression_type(self, t: RawExpressionType) -> Type:\n # We should never see a bare Literal. We synthesize these raw literals\n # in the earlier stages of semantic analysis, but those\n # \"fake literals\" should always be wrapped in an UnboundType\n # corresponding to 'Literal'.\n #\n # Note: if at some point in the distant future, we decide to\n # make signatures like \"foo(x: 20) -> None\" legal, we can change\n # this method so it generates and returns an actual LiteralType\n # instead.\n\n if self.report_invalid_types:\n if t.base_type_name in (\"builtins.int\", \"builtins.bool\"):\n # The only time it makes sense to use an int or bool is inside of\n # a literal type.\n msg = f\"Invalid type: try using Literal[{repr(t.literal_value)}] instead?\"\n elif t.base_type_name in (\"builtins.float\", \"builtins.complex\"):\n # We special-case warnings for floats and complex numbers.\n msg = f\"Invalid type: {t.simple_name()} literals cannot be used as a type\"\n else:\n # And in all other cases, we default to a generic error message.\n # Note: the reason why we use a generic error message for strings\n # but not ints or bools is because whenever we see an out-of-place\n # string, it's unclear if the user meant to construct a literal type\n # or just misspelled a regular type. So we avoid guessing.\n msg = \"Invalid type comment or annotation\"\n\n self.fail(msg, t, code=codes.VALID_TYPE)\n if t.note is not None:\n self.note(t.note, t, code=codes.VALID_TYPE)\n\n return AnyType(TypeOfAny.from_error, line=t.line, column=t.column)\n\n def visit_literal_type(self, t: LiteralType) -> Type:\n return t\n\n def visit_union_type(self, t: UnionType) -> Type:\n if (\n t.uses_pep604_syntax is True\n and t.is_evaluated is True\n and not self.always_allow_new_syntax\n and not self.options.python_version >= (3, 10)\n ):\n self.fail(\"X | Y syntax for unions requires Python 3.10\", t, code=codes.SYNTAX)\n return UnionType(self.anal_array(t.items), t.line, uses_pep604_syntax=t.uses_pep604_syntax)\n\n def visit_partial_type(self, t: PartialType) -> Type:\n assert False, \"Internal error: Unexpected partial type\"\n\n def visit_ellipsis_type(self, t: EllipsisType) -> Type:\n if self.allow_ellipsis or self.allow_param_spec_literals:\n any_type = AnyType(TypeOfAny.explicit)\n return Parameters(\n [any_type, any_type], [ARG_STAR, ARG_STAR2], [None, None], is_ellipsis_args=True\n )\n else:\n self.fail('Unexpected \"...\"', t)\n return AnyType(TypeOfAny.from_error)\n\n def visit_type_type(self, t: TypeType) -> Type:\n return TypeType.make_normalized(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 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:\n fallback = self.named_type(\"builtins.function\")\n if len(t.args) == 0:\n # Callable (bare). Treat as Callable[..., Any].\n any_type = self.get_omitted_any(t)\n ret = callable_with_ellipsis(any_type, any_type, fallback)\n elif len(t.args) == 2:\n callable_args = t.args[0]\n ret_type = t.args[1]\n if isinstance(callable_args, TypeList):\n # Callable[[ARG, ...], RET] (ordinary callable type)\n analyzed_args = self.analyze_callable_args(callable_args)\n if analyzed_args is None:\n return AnyType(TypeOfAny.from_error)\n args, kinds, names = analyzed_args\n ret = CallableType(args, kinds, names, ret_type=ret_type, fallback=fallback)\n elif isinstance(callable_args, EllipsisType):\n # Callable[..., RET] (with literal ellipsis; accept arbitrary arguments)\n ret = callable_with_ellipsis(\n AnyType(TypeOfAny.explicit), ret_type=ret_type, fallback=fallback\n )\n else:\n # Callable[P, RET] (where P is ParamSpec)\n with self.tvar_scope_frame(namespace=\"\"):\n # Temporarily bind ParamSpecs to allow code like this:\n # my_fun: Callable[Q, Foo[Q]]\n # We usually do this later in visit_callable_type(), but the analysis\n # below happens at very early stage.\n variables = []\n for name, tvar_expr in self.find_type_var_likes(callable_args):\n variables.append(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:\/\/mypy.readthedocs.io\/en\/stable\/kinds_of_types.html#callable-types-and-lambdas\",\n t,\n )\n return AnyType(TypeOfAny.from_error)\n elif isinstance(maybe_ret, AnyType):\n return maybe_ret\n ret = maybe_ret\n else:\n if self.options.disallow_any_generics:\n self.fail('Please use \"Callable[[], ]\"', t)\n else:\n self.fail('Please use \"Callable[[], ]\" 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, t: Type) -> Type:\n return t.accept(self)\n\n def fail(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None:\n self.fail_func(msg, ctx, code=code)\n\n def note(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None:\n self.note_func(msg, ctx, code=code)\n\n @contextmanager\n def tvar_scope_frame(self, namespace: str) -> Iterator[None]:\n old_scope = self.tvar_scope\n self.tvar_scope = self.tvar_scope.method_frame(namespace)\n yield\n self.tvar_scope = old_scope\n\n def find_type_var_likes(self, t: Type) -> TypeVarLikeList:\n visitor = FindTypeVarVisitor(self.api, self.tvar_scope)\n t.accept(visitor)\n return visitor.type_var_likes\n\n def infer_type_variables(\n self, type: CallableType\n ) -> tuple[list[tuple[str, TypeVarLikeExpr]], bool]:\n \"\"\"Infer type variables from a callable.\n\n Return tuple with these items:\n - list of unique type variables referred to in a callable\n - whether there is a reference to the Self type\n \"\"\"\n visitor = FindTypeVarVisitor(self.api, self.tvar_scope)\n for arg in type.arg_types:\n arg.accept(visitor)\n\n # When finding type variables in the return type of a function, don't\n # look inside Callable types. Type variables only appearing in\n # functions in the return type belong to those functions, not the\n # function we're currently analyzing.\n visitor.include_callables = False\n type.ret_type.accept(visitor)\n\n return visitor.type_var_likes, visitor.has_self_type\n\n def bind_function_type_variables(\n self, fun_type: CallableType, defn: Context\n ) -> tuple[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(var.name, var_expr)\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)\n defs.append(binding)\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 ) -> 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 old_allow_ellipsis = self.allow_ellipsis\n self.allow_ellipsis = allow_ellipsis\n old_allow_unpack = self.allow_unpack\n self.allow_unpack = allow_unpack\n try:\n analyzed = t.accept(self)\n finally:\n if nested:\n self.nesting_level -= 1\n self.allow_typed_dict_special_forms = old_allow_typed_dict_special_forms\n self.allow_ellipsis = old_allow_ellipsis\n self.allow_unpack = old_allow_unpack\n if (\n not allow_param_spec\n and isinstance(analyzed, ParamSpecType)\n and analyzed.flavor == ParamSpecFlavor.BARE\n ):\n if analyzed.prefix.arg_types:\n self.fail(\"Invalid location for Concatenate\", t, code=codes.VALID_TYPE)\n self.note(\"You can use Concatenate as the first argument to Callable\", t)\n analyzed = AnyType(TypeOfAny.from_error)\n else:\n self.fail(\n INVALID_PARAM_SPEC_LOCATION.format(format_type(analyzed, self.options)),\n t,\n code=codes.VALID_TYPE,\n )\n self.note(\n INVALID_PARAM_SPEC_LOCATION_NOTE.format(analyzed.name),\n t,\n code=codes.VALID_TYPE,\n )\n analyzed = AnyType(TypeOfAny.from_error)\n return analyzed\n\n def anal_var_def(self, var_def: TypeVarLikeType) -> TypeVarLikeType:\n if isinstance(var_def, TypeVarType):\n return TypeVarType(\n name=var_def.name,\n fullname=var_def.fullname,\n id=var_def.id,\n values=self.anal_array(var_def.values),\n upper_bound=var_def.upper_bound.accept(self),\n default=var_def.default.accept(self),\n variance=var_def.variance,\n line=var_def.line,\n column=var_def.column,\n )\n else:\n return var_def\n\n def anal_var_defs(self, var_defs: Sequence[TypeVarLikeType]) -> list[TypeVarLikeType]:\n return [self.anal_var_def(vd) for vd in var_defs]\n\n def named_type(\n self,\n fully_qualified_name: str,\n args: list[Type] | None = None,\n line: int = -1,\n column: int = -1,\n ) -> Instance:\n node = self.lookup_fully_qualified(fully_qualified_name)\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 else:\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:\/\/mypy.readthedocs.io\/en\/stable\/runtime_troubles.html\"\n \"#not-generic-runtime\",\n typ,\n code=codes.TYPE_ARG,\n )\n\n any_type = AnyType(TypeOfAny.from_error, line=typ.line, column=typ.column)\n else:\n any_type = AnyType(\n TypeOfAny.from_omitted_generics, line=orig_type.line, column=orig_type.column\n )\n return any_type\n\n\ndef fix_type_var_tuple_argument(t: Instance) -> None:\n if t.type.has_type_var_tuple_type:\n args = list(t.args)\n assert t.type.type_var_tuple_prefix is not None\n tvt = t.type.defn.type_vars[t.type.type_var_tuple_prefix]\n assert isinstance(tvt, TypeVarTupleType)\n args[t.type.type_var_tuple_prefix] = UnpackType(\n Instance(tvt.tuple_fallback.type, [args[t.type.type_var_tuple_prefix]])\n )\n t.args = tuple(args)\n\n\ndef fix_instance(\n t: Instance,\n fail: MsgCallback,\n note: MsgCallback,\n disallow_any: bool,\n options: Options,\n use_generic_error: bool = False,\n unexpanded_type: Type | None = None,\n) -> None:\n \"\"\"Fix a malformed instance by replacing all type arguments with TypeVar default or Any.\n\n Also emit a suitable error if this is not due to implicit Any's.\n \"\"\"\n arg_count = len(t.args)\n min_tv_count = sum(not tv.has_default() for tv in t.type.defn.type_vars)\n max_tv_count = len(t.type.type_vars)\n if arg_count < min_tv_count or arg_count > max_tv_count:\n # Don't use existing args if arg_count doesn't match\n if arg_count > max_tv_count:\n # Already wrong arg count error, don't emit missing type parameters error as well.\n disallow_any = False\n t.args = ()\n 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 or disallow_any:\n type_of_any = TypeOfAny.from_error\n elif special_form:\n type_of_any = TypeOfAny.special_form\n else:\n type_of_any = TypeOfAny.from_omitted_generics\n any_type = AnyType(type_of_any, line=newline, column=newcolumn)\n\n env: dict[TypeVarId, Type] = {}\n used_any_type = False\n has_type_var_tuple_type = False\n for tv, arg in itertools.zip_longest(node.alias_tvars, args, fillvalue=None):\n if tv is None:\n continue\n if arg is None:\n if tv.has_default():\n arg = tv.default\n else:\n arg = any_type\n used_any_type = True\n if isinstance(tv, TypeVarTupleType):\n # TODO Handle TypeVarTuple defaults\n has_type_var_tuple_type = True\n arg = UnpackType(Instance(tv.tuple_fallback.type, [any_type]))\n args.append(arg)\n env[tv.id] = arg\n t = TypeAliasType(node, args, newline, newcolumn)\n if not has_type_var_tuple_type:\n 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\ndef flatten_tvars(lists: list[list[T]]) -> list[T]:\n result: list[T] = []\n for lst in lists:\n for item in lst:\n if item not in result:\n result.append(item)\n return result\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\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 = None\n\n # Special case P.args and P.kwargs for ParamSpecs only.\n if name.endswith(\"args\"):\n if name.endswith((\".args\", \".kwargs\")):\n base = \".\".join(name.split(\".\")[:-1])\n n = self.api.lookup_qualified(base, t)\n if n is not None and isinstance(n.node, ParamSpecExpr):\n node = n\n name = base\n if node is None:\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_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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/typeanal.py","language":"Python","license":"NOASSERTION","size":115252} {"code":"\"\"\"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 typing import Any, Iterable, List, Sequence, 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 ENUM_REMOVED_PROPS,\n AnyType,\n CallableType,\n ExtraAttrs,\n FormalArgument,\n FunctionLike,\n Instance,\n LiteralType,\n NoneType,\n NormalizedCallableType,\n Overloaded,\n Parameters,\n ParamSpecType,\n PartialType,\n ProperType,\n TupleType,\n Type,\n TypeAliasType,\n TypedDictType,\n TypeOfAny,\n TypeQuery,\n TypeType,\n TypeVarLikeType,\n TypeVarTupleType,\n TypeVarType,\n UninhabitedType,\n UnionType,\n UnpackType,\n flatten_nested_unions,\n get_proper_type,\n get_proper_types,\n)\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) -> F:\n \"\"\"Return a copy of `method`, with the type of its first parameter (usually\n self or cls) bound to original_type.\n\n If the type of `self` is a generic type (T, or Type[T] for classmethods),\n instantiate every occurrence of type with original_type in the rest of the\n signature and in the return type.\n\n original_type is the type of E in the expression E.copy(). It is None in\n compatibility checks. In this case we treat it as the erasure of the\n declared type of self.\n\n This way we can express \"the type of self\". For example:\n\n T = TypeVar('T', bound='A')\n class A:\n def copy(self: T) -> T: ...\n\n class B(A): pass\n\n b = B().copy() # type: B\n\n \"\"\"\n if isinstance(method, Overloaded):\n items = []\n 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)\n if func.arg_kinds[0] in (ARG_STAR, ARG_STAR2):\n # The signature is of the form 'def foo(*args, ...)'.\n # In this case we shouldn't drop the first arg,\n # since func will be absorbed by the *args.\n # TODO: infer bounds on the type of *args?\n\n # In the case of **kwargs we should probably emit an error, but\n # for now we simply skip it, to avoid crashes down the line.\n return cast(F, func)\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 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 )\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 _get_type_method_ret_type(t: Type, *, name: str) -> Type | None:\n t = get_proper_type(t)\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) and t.type.is_final:\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] + [AnyType(TypeOfAny.unannotated)] * (len(fdef.arg_names) - 1)\n else:\n args = [AnyType(TypeOfAny.unannotated)] * len(fdef.arg_names)\n\n return CallableType(\n args,\n fdef.arg_kinds,\n fdef.arg_names,\n ret_type or AnyType(TypeOfAny.unannotated),\n fallback,\n name=fdef.name,\n line=fdef.line,\n column=fdef.column,\n implicit=True,\n # We need this for better error messages, like missing `self` note:\n definition=fdef if isinstance(fdef, FuncDef) else None,\n )\n\n\ndef try_getting_str_literals(expr: Expression, typ: Type) -> list[str] | None:\n \"\"\"If the given expression or type corresponds to a string literal\n or a union of string literals, returns a list of the underlying strings.\n Otherwise, returns None.\n\n Specifically, this function is guaranteed to return a list with\n one or more strings if one of the following is true:\n\n 1. 'expr' is a StrExpr\n 2. 'typ' is a LiteralType containing a string\n 3. 'typ' is a UnionType containing only LiteralType of strings\n \"\"\"\n if isinstance(expr, StrExpr):\n return [expr.value]\n\n # TODO: See if we can eliminate this function and call the below one directly\n return try_getting_str_literals_from_type(typ)\n\n\ndef try_getting_str_literals_from_type(typ: Type) -> list[str] | None:\n \"\"\"If the given expression or type corresponds to a string Literal\n or a union of string Literals, returns a list of the underlying strings.\n Otherwise, returns None.\n\n For example, if we had the type 'Literal[\"foo\", \"bar\"]' as input, this function\n would return a list of strings [\"foo\", \"bar\"].\n \"\"\"\n return try_getting_literals_from_type(typ, str, \"builtins.str\")\n\n\ndef try_getting_int_literals_from_type(typ: Type) -> list[int] | None:\n \"\"\"If the given expression or type corresponds to an int Literal\n or a union of int Literals, returns a list of the underlying ints.\n Otherwise, returns None.\n\n For example, if we had the type 'Literal[1, 2, 3]' as input, this function\n would return a list of ints [1, 2, 3].\n \"\"\"\n return try_getting_literals_from_type(typ, int, \"builtins.int\")\n\n\nT = TypeVar(\"T\")\n\n\ndef try_getting_literals_from_type(\n typ: Type, target_literal_type: type[T], target_fullname: str\n) -> list[T] | None:\n \"\"\"If the given expression or type corresponds to a Literal or\n union of Literals where the underlying values correspond to the given\n target type, returns a list of those underlying values. Otherwise,\n returns None.\n \"\"\"\n typ = get_proper_type(typ)\n\n if isinstance(typ, Instance) and typ.last_known_value is not None:\n possible_literals: list[Type] = [typ.last_known_value]\n elif isinstance(typ, UnionType):\n possible_literals = list(typ.items)\n else:\n possible_literals = [typ]\n\n literals: list[T] = []\n for lit in get_proper_types(possible_literals):\n if isinstance(lit, LiteralType) and lit.fallback.type.fullname == target_fullname:\n val = lit.value\n if isinstance(val, target_literal_type):\n literals.append(val)\n else:\n return None\n else:\n return None\n return literals\n\n\ndef is_literal_type_like(t: Type | None) -> bool:\n \"\"\"Returns 'true' if the given type context is potentially either a LiteralType,\n a Union of LiteralType, or something similar.\n \"\"\"\n t = get_proper_type(t)\n if t is None:\n return False\n elif isinstance(t, LiteralType):\n return True\n elif isinstance(t, UnionType):\n return any(is_literal_type_like(item) for item in t.items)\n elif isinstance(t, TypeVarType):\n return is_literal_type_like(t.upper_bound) or any(\n is_literal_type_like(item) for item in t.values\n )\n else:\n return False\n\n\ndef is_singleton_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 elif isinstance(typ, Instance) and typ.type.fullname == target_fullname:\n if typ.type.is_enum:\n new_items = []\n for name, symbol in typ.type.names.items():\n if not isinstance(symbol.node, Var):\n continue\n # Skip these since Enum will remove it\n if name in ENUM_REMOVED_PROPS:\n continue\n # Skip private attributes\n if name.startswith(\"__\"):\n continue\n new_items.append(LiteralType(name, typ))\n return make_simplified_union(new_items, contract_literals=False)\n elif typ.type.fullname == \"builtins.bool\":\n return make_simplified_union(\n [LiteralType(True, typ), LiteralType(False, typ)], contract_literals=False\n )\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.get_enum_values())\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.get_enum_values()\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, 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/typeops.py","language":"Python","license":"NOASSERTION","size":44620} {"code":"\"\"\"Classes for representing mypy types.\"\"\"\n\nfrom __future__ import annotations\n\nimport sys\nfrom abc import abstractmethod\nfrom typing import (\n TYPE_CHECKING,\n Any,\n ClassVar,\n Dict,\n Final,\n Iterable,\n NamedTuple,\n NewType,\n Sequence,\n TypeVar,\n Union,\n cast,\n)\nfrom typing_extensions import Self, TypeAlias as _TypeAlias, TypeGuard, overload\n\nimport mypy.nodes\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\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.\nENUM_REMOVED_PROPS: Final = (\"_ignore_\", \"_order_\", \"__order__\")\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\")\n\n values: list[Type] # Value restriction, empty list if no restriction\n variance: int\n\n def __init__(\n self,\n name: str,\n fullname: str,\n id: TypeVarId,\n values: list[Type],\n upper_bound: Type,\n default: Type,\n variance: int = INVARIANT,\n line: int = -1,\n column: int = -1,\n ) -> None:\n super().__init__(name, fullname, id, upper_bound, default, line, column)\n assert values is not None, \"No restrictions must be represented by empty list\"\n self.values = values\n self.variance = variance\n\n def copy_modified(\n self,\n *,\n values: Bogus[list[Type]] = _dummy,\n upper_bound: Bogus[Type] = _dummy,\n default: Bogus[Type] = _dummy,\n id: Bogus[TypeVarId] = _dummy,\n line: int = _dummy_int,\n column: int = _dummy_int,\n **kwargs: Any,\n ) -> TypeVarType:\n return TypeVarType(\n name=self.name,\n fullname=self.fullname,\n id=self.id if id is _dummy else id,\n values=self.values if values is _dummy else values,\n upper_bound=self.upper_bound if upper_bound is _dummy else upper_bound,\n default=self.default if default is _dummy else default,\n variance=self.variance,\n line=self.line if line == _dummy_int else line,\n column=self.column if column == _dummy_int else column,\n )\n\n def accept(self, visitor: TypeVisitor[T]) -> T:\n return visitor.visit_type_var(self)\n\n def __hash__(self) -> int:\n return hash((self.id, self.upper_bound, tuple(self.values)))\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, TypeVarType):\n return NotImplemented\n return (\n self.id == other.id\n and self.upper_bound == other.upper_bound\n and self.values == other.values\n )\n\n def serialize(self) -> JsonDict:\n assert not self.id.is_meta_var()\n return {\n \".class\": \"TypeVarType\",\n \"name\": self.name,\n \"fullname\": self.fullname,\n \"id\": self.id.raw_id,\n \"namespace\": self.id.namespace,\n \"values\": [v.serialize() for v in self.values],\n \"upper_bound\": self.upper_bound.serialize(),\n \"default\": self.default.serialize(),\n \"variance\": self.variance,\n }\n\n @classmethod\n def deserialize(cls, data: JsonDict) -> TypeVarType:\n assert data[\".class\"] == \"TypeVarType\"\n return TypeVarType(\n name=data[\"name\"],\n fullname=data[\"fullname\"],\n id=TypeVarId(data[\"id\"], namespace=data[\"namespace\"]),\n values=[deserialize_type(v) for v in data[\"values\"]],\n upper_bound=deserialize_type(data[\"upper_bound\"]),\n default=deserialize_type(data[\"default\"]),\n variance=data[\"variance\"],\n )\n\n\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 )\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 ) -> None:\n super().__init__(line, column)\n if not args:\n args = []\n self.name = name\n self.args = tuple(args)\n # Should this type be wrapped in an Optional?\n self.optional = optional\n # Special case for X[()]\n self.empty_tuple_index = empty_tuple_index\n # If this UnboundType was originally defined as a str or bytes, keep track of\n # the original contents of that string-like thing. This way, if this UnboundExpr\n # ever shows up inside of a LiteralType, we can determine whether that\n # Literal[...] is valid or not. E.g. Literal[foo] is most likely invalid\n # (unless 'foo' is an alias for another literal or something) and\n # Literal[\"foo\"] most likely is.\n #\n # We keep track of the entire string instead of just using a boolean flag\n # so we can distinguish between things like Literal[\"foo\"] vs\n # Literal[\" foo \"].\n #\n # We also keep track of what the original base fallback type was supposed to be\n # so we don't have to try and recompute it later\n self.original_str_expr = original_str_expr\n self.original_str_fallback = original_str_fallback\n\n def copy_modified(self, args: Bogus[Sequence[Type] | None] = _dummy) -> UnboundType:\n if args is _dummy:\n args = self.args\n return UnboundType(\n name=self.name,\n args=args,\n line=self.line,\n column=self.column,\n optional=self.optional,\n empty_tuple_index=self.empty_tuple_index,\n original_str_expr=self.original_str_expr,\n original_str_fallback=self.original_str_fallback,\n )\n\n def accept(self, visitor: TypeVisitor[T]) -> T:\n return visitor.visit_unbound_type(self)\n\n def __hash__(self) -> int:\n return hash((self.name, self.optional, tuple(self.args), self.original_str_expr))\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, UnboundType):\n return NotImplemented\n return (\n self.name == other.name\n and self.optional == other.optional\n and self.args == other.args\n and self.original_str_expr == other.original_str_expr\n and self.original_str_fallback == other.original_str_fallback\n )\n\n def serialize(self) -> JsonDict:\n return {\n \".class\": \"UnboundType\",\n \"name\": self.name,\n \"args\": [a.serialize() for a in self.args],\n \"expr\": self.original_str_expr,\n \"expr_fallback\": self.original_str_fallback,\n }\n\n @classmethod\n def deserialize(cls, data: JsonDict) -> UnboundType:\n assert data[\".class\"] == \"UnboundType\"\n return UnboundType(\n data[\"name\"],\n [deserialize_type(a) for a in data[\"args\"]],\n original_str_expr=data[\"expr\"],\n original_str_fallback=data[\"expr_fallback\"],\n )\n\n\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\": \"AnyType\",\n \"type_of_any\": self.type_of_any,\n \"source_any\": self.source_any.serialize() if self.source_any is not None else None,\n \"missing_import_name\": self.missing_import_name,\n }\n\n @classmethod\n def deserialize(cls, data: JsonDict) -> AnyType:\n assert data[\".class\"] == \"AnyType\"\n source = data[\"source_any\"]\n return AnyType(\n data[\"type_of_any\"],\n AnyType.deserialize(source) if source is not None else None,\n data[\"missing_import_name\"],\n )\n\n\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\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__ = (\"type\", \"args\", \"invalid\", \"type_ref\", \"last_known_value\", \"_hash\", \"extra_attrs\")\n\n def __init__(\n self,\n typ: mypy.nodes.TypeInfo,\n args: Sequence[Type],\n line: int = -1,\n column: int = -1,\n *,\n last_known_value: LiteralType | None = None,\n extra_attrs: ExtraAttrs | None = None,\n ) -> None:\n super().__init__(line, column)\n self.type = typ\n self.args = tuple(args)\n self.type_ref: str | None = None\n\n # 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\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 = {\".class\": \"Instance\"}\n data[\"type_ref\"] = type_ref\n data[\"args\"] = [arg.serialize() for arg in self.args]\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 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.get_enum_values()) == 1\n or self.type.fullname in {\"builtins.ellipsis\", \"types.EllipsisType\"}\n )\n\n def get_enum_values(self) -> list[str]:\n \"\"\"Return the list of values for an Enum.\"\"\"\n return [\n name for name, sym in self.type.names.items() if isinstance(sym.node, mypy.nodes.Var)\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\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 value is 'dict' for a signature similar to\n # 'dict')\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 )\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: Type | None = None,\n type_is: Type | None = None,\n from_concatenate: bool = False,\n imprecise_arg_kinds: bool = False,\n unpack_kwargs: bool = False,\n ) -> None:\n super().__init__(line, column)\n assert len(arg_types) == len(arg_kinds) == len(arg_names)\n 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 \" 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: 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 deserialize_type(data[\"type_guard\"]) if data[\"type_guard\"] is not None else None\n ),\n type_is=(deserialize_type(data[\"type_is\"]) if data[\"type_is\"] is not None else None),\n from_concatenate=data[\"from_concatenate\"],\n imprecise_arg_kinds=data[\"imprecise_arg_kinds\"],\n unpack_kwargs=data[\"unpack_kwargs\"],\n )\n\n\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 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 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\")\n\n def __init__(\n self,\n literal_value: LiteralValue | None,\n base_type_name: str,\n line: int = -1,\n column: int = -1,\n note: str | None = None,\n ) -> None:\n super().__init__(line, column)\n self.literal_value = literal_value\n self.base_type_name = base_type_name\n self.note = note\n\n def simple_name(self) -> str:\n return self.base_type_name.replace(\"builtins.\", \"\")\n\n def accept(self, visitor: TypeVisitor[T]) -> T:\n assert isinstance(visitor, SyntheticTypeVisitor)\n ret: T = visitor.visit_raw_expression_type(self)\n return ret\n\n def serialize(self) -> JsonDict:\n assert False, \"Synthetic types don't serialize\"\n\n def __hash__(self) -> int:\n return hash((self.literal_value, self.base_type_name))\n\n def __eq__(self, other: object) -> bool:\n if isinstance(other, RawExpressionType):\n return (\n self.base_type_name == other.base_type_name\n and self.literal_value == other.literal_value\n )\n else:\n return NotImplemented\n\n\nclass LiteralType(ProperType):\n \"\"\"The type of a Literal instance. Literal[Value]\n\n A Literal always consists of:\n\n 1. A native Python object corresponding to the contained inner value\n 2. A fallback for this Literal. The fallback also corresponds to the\n parent type this Literal subtypes.\n\n For example, 'Literal[42]' is represented as\n 'LiteralType(value=42, fallback=instance_of_int)'\n\n As another example, `Literal[Color.RED]` (where Color is an enum) is\n represented as `LiteralType(value=\"RED\", fallback=instance_of_color)'.\n \"\"\"\n\n __slots__ = (\"value\", \"fallback\", \"_hash\")\n\n def __init__(\n self, value: LiteralValue, fallback: Instance, line: int = -1, column: int = -1\n ) -> None:\n super().__init__(line, column)\n self.value = value\n self.fallback = fallback\n self._hash = -1 # Cached hash value\n\n def can_be_false_default(self) -> bool:\n return not self.value\n\n def can_be_true_default(self) -> bool:\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 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 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\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\"\"\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 \"Any\"\n\n def visit_none_type(self, t: NoneType) -> str:\n return \"None\"\n\n def visit_uninhabited_type(self, t: UninhabitedType) -> str:\n return \"Never\"\n\n def visit_erased_type(self, t: ErasedType) -> str:\n return \"\"\n\n def visit_deleted_type(self, t: DeletedType) -> str:\n if t.source is None:\n return \"\"\n else:\n return f\"\"\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 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 return s\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 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 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 s += f\" -> TypeGuard[{t.type_guard.accept(self)}]\"\n elif t.type_is is not None:\n s += f\" -> TypeIs[{t.type_is.accept(self)}]\"\n else:\n s += f\" -> {t.ret_type.accept(self)}\"\n\n if t.variables:\n vs = []\n for var in t.variables:\n if isinstance(var, TypeVarType):\n # We reimplement TypeVarType.__repr__ here in order to support id_mapper.\n if var.values:\n vals = f\"({', '.join(val.accept(self) for val in var.values)})\"\n vs.append(f\"{var.name} in {vals}\")\n elif not is_named_instance(var.upper_bound, \"builtins.object\"):\n vs.append(\n f\"{var.name} <: {var.upper_bound.accept(self)}{f' = {var.default.accept(self)}' if var.has_default() else ''}\"\n )\n else:\n vs.append(\n f\"{var.name}{f' = {var.default.accept(self)}' if var.has_default() else ''}\"\n )\n else:\n # For other TypeVarLikeTypes, use the name and default\n vs.append(\n f\"{var.name}{f' = {var.default.accept(self)}' if var.has_default() else ''}\"\n )\n s = f\"[{', '.join(vs)}] {s}\"\n\n return f\"def {s}\"\n\n def visit_overloaded(self, t: Overloaded) -> str:\n a = []\n for i in t.items:\n a.append(i.accept(self))\n return f\"Overload({', '.join(a)})\"\n\n def visit_tuple_type(self, t: TupleType) -> str:\n s = self.list_str(t.items) or \"()\"\n 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}, fallback={t.partial_fallback.accept(self)}]\"\n return f\"{tuple_name}[{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 return f\"Literal[{t.value_repr()}]\"\n\n def visit_union_type(self, t: UnionType) -> str:\n s = self.list_str(t.items)\n return f\"Union[{s}]\"\n\n def visit_partial_type(self, t: PartialType) -> str:\n if t.type is None:\n return \"\"\n else:\n return \"\".format(t.type.name, \", \".join([\"?\"] * len(t.type.type_vars)))\n\n def visit_ellipsis_type(self, t: EllipsisType) -> str:\n return \"...\"\n\n def visit_type_type(self, t: TypeType) -> str:\n if 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\"\"\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 \"\"\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\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(t: Type, fullnames: str | tuple[str, ...]) -> TypeGuard[Instance]:\n if not isinstance(fullnames, tuple):\n fullnames = (fullnames,)\n\n t = get_proper_type(t)\n return isinstance(t, Instance) and t.type.fullname in fullnames\n\n\nclass 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 def __init__(self) -> None:\n super().__init__(ANY_STRATEGY)\n self.skip_alias_target = True\n\n def visit_type_var(self, t: TypeVarType) -> bool:\n return True\n\n def visit_type_var_tuple(self, t: TypeVarTupleType) -> bool:\n return True\n\n def visit_param_spec(self, t: ParamSpecType) -> bool:\n return True\n\n\ndef has_type_vars(typ: Type) -> bool:\n \"\"\"Check if a type contains any type variables (recursively).\"\"\"\n return typ.accept(HasTypeVars())\n\n\nclass HasRecursiveType(BoolTypeQuery):\n def __init__(self) -> None:\n super().__init__(ANY_STRATEGY)\n\n def visit_type_alias_type(self, t: TypeAliasType) -> bool:\n return t.is_recursive or self.query_types(t.args)\n\n\n# Use singleton since this is hot (note: call reset() before using)\n_has_recursive_type: Final = HasRecursiveType()\n\n\ndef has_recursive_types(typ: Type) -> bool:\n \"\"\"Check if a type contains any recursive aliases (recursively).\"\"\"\n _has_recursive_type.reset()\n return typ.accept(_has_recursive_type)\n\n\ndef split_with_prefix_and_suffix(\n types: tuple[Type, ...], prefix: int, suffix: int\n) -> tuple[tuple[Type, ...], tuple[Type, ...], tuple[Type, ...]]:\n if len(types) <= prefix + suffix:\n types = extend_args_for_prefix_and_suffix(types, prefix, suffix)\n if suffix:\n return types[:prefix], types[prefix:-suffix], types[-suffix:]\n else:\n return types[:prefix], types[prefix:], ()\n\n\ndef extend_args_for_prefix_and_suffix(\n types: tuple[Type, ...], prefix: int, suffix: int\n) -> tuple[Type, ...]:\n \"\"\"Extend list of types by eating out from variadic tuple to satisfy prefix and suffix.\"\"\"\n idx = None\n item = None\n for i, t in enumerate(types):\n if isinstance(t, UnpackType):\n p_type = get_proper_type(t.type)\n if isinstance(p_type, Instance) and p_type.type.fullname == \"builtins.tuple\":\n item = p_type.args[0]\n idx = i\n break\n\n if idx is None:\n return types\n assert item is not None\n if idx < prefix:\n start = (item,) * (prefix - idx)\n else:\n start = ()\n if len(types) - idx - 1 < suffix:\n end = (item,) * (suffix - len(types) + idx + 1)\n else:\n end = ()\n return types[:idx] + start + (types[idx],) + end + types[idx + 1 :]\n\n\ndef flatten_nested_unions(\n types: Sequence[Type], *, handle_type_alias_type: bool = True, handle_recursive: bool = True\n) -> list[Type]:\n \"\"\"Flatten nested unions in a type list.\"\"\"\n if not isinstance(types, list):\n typelist = list(types)\n else:\n typelist = cast(\"list[Type]\", types)\n\n # Fast path: most of the time there is nothing to flatten\n if not any(isinstance(t, (TypeAliasType, UnionType)) for t in typelist): # type: ignore[misc]\n return typelist\n\n flat_items: list[Type] = []\n for t in typelist:\n if handle_type_alias_type:\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, UnionType):\n flat_items.extend(\n flatten_nested_unions(tp.items, handle_type_alias_type=handle_type_alias_type)\n )\n else:\n # Must preserve original aliases when possible.\n flat_items.append(t)\n return flat_items\n\n\ndef find_unpack_in_list(items: Sequence[Type]) -> int | None:\n unpack_index: int | None = None\n for i, item in enumerate(items):\n if isinstance(item, UnpackType):\n # We cannot fail here, so we must check this in an earlier\n # semanal phase.\n # Funky code here avoids mypyc narrowing the type of unpack_index.\n old_index = unpack_index\n assert old_index is None\n # Don't return so that we can also sanity check there is only one.\n unpack_index = i\n return unpack_index\n\n\ndef flatten_nested_tuples(types: 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 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/types.py","language":"Python","license":"NOASSERTION","size":137495} {"code":"\"\"\"\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 typing import Callable, Iterable, cast\n\nfrom mypy.nodes import ARG_STAR, ARG_STAR2, FuncItem, TypeAlias\nfrom mypy.types import (\n AnyType,\n CallableType,\n Instance,\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 is_bad_type_type_item(item: Type) -> bool:\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 item = get_proper_type(item)\n if isinstance(item, TypeType):\n return True\n if isinstance(item, UnionType):\n return any(\n isinstance(get_proper_type(i), TypeType) for i in flatten_nested_unions(item.items)\n )\n return False\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/types_utils.py","language":"Python","license":"NOASSERTION","size":5671} {"code":"\"\"\"\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 Dict, Final, Set, Tuple\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 -> \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. ..., , -> \n 2. ..., , -> [for every attr in Proto members]\n 3. -> 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 -> to invalidate the assignment (module target in this case),\n whenever the signature of a.A.__iter__ changes. We also add -> 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 -> 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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/typestate.py","language":"Python","license":"NOASSERTION","size":16005} {"code":"from __future__ import annotations\n\nfrom typing import Iterable\n\nfrom mypy_extensions import trait\n\nfrom mypy.types import (\n AnyType,\n CallableArgument,\n CallableType,\n DeletedType,\n EllipsisType,\n ErasedType,\n Instance,\n LiteralType,\n NoneType,\n Overloaded,\n Parameters,\n ParamSpecType,\n PartialType,\n PlaceholderType,\n RawExpressionType,\n SyntheticTypeVisitor,\n TupleType,\n Type,\n TypeAliasType,\n TypedDictType,\n TypeList,\n TypeType,\n TypeVarTupleType,\n TypeVarType,\n UnboundType,\n UninhabitedType,\n UnionType,\n UnpackType,\n)\n\n\n@trait\nclass TypeTraverserVisitor(SyntheticTypeVisitor[None]):\n \"\"\"Visitor that traverses all components of a type\"\"\"\n\n # Atomic types\n\n def visit_any(self, t: AnyType) -> None:\n pass\n\n def visit_uninhabited_type(self, t: UninhabitedType) -> None:\n pass\n\n def visit_none_type(self, t: NoneType) -> None:\n pass\n\n def visit_erased_type(self, t: ErasedType) -> None:\n pass\n\n def visit_deleted_type(self, t: DeletedType) -> None:\n pass\n\n def visit_type_var(self, t: TypeVarType) -> None:\n # Note that type variable values and upper bound aren't treated as\n # components, since they are components of the type variable\n # definition. We want to traverse everything just once.\n t.default.accept(self)\n\n def visit_param_spec(self, t: ParamSpecType) -> None:\n 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_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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/typetraverser.py","language":"Python","license":"NOASSERTION","size":3924} {"code":"from __future__ import annotations\n\nfrom mypy.erasetype import erase_typevars\nfrom mypy.nodes import TypeInfo\nfrom mypy.types import (\n Instance,\n ParamSpecType,\n ProperType,\n TupleType,\n Type,\n TypeOfAny,\n TypeVarLikeType,\n TypeVarTupleType,\n TypeVarType,\n UnpackType,\n)\nfrom mypy.typevartuples import erased_vars\n\n\ndef fill_typevars(typ: TypeInfo) -> Instance | TupleType:\n \"\"\"For a non-generic type, return instance type representing the type.\n\n For a generic G type with parameters T1, .., Tn, return G[T1, ..., Tn].\n \"\"\"\n tvs: list[Type] = []\n # TODO: why do we need to keep both typ.type_vars and typ.defn.type_vars?\n for i in range(len(typ.defn.type_vars)):\n tv: TypeVarLikeType | UnpackType = typ.defn.type_vars[i]\n # Change the line number\n if isinstance(tv, TypeVarType):\n tv = tv.copy_modified(line=-1, column=-1)\n elif isinstance(tv, TypeVarTupleType):\n tv = UnpackType(\n TypeVarTupleType(\n tv.name,\n tv.fullname,\n tv.id,\n tv.upper_bound,\n tv.tuple_fallback,\n tv.default,\n line=-1,\n column=-1,\n )\n )\n else:\n assert isinstance(tv, ParamSpecType)\n tv = ParamSpecType(\n tv.name,\n tv.fullname,\n tv.id,\n tv.flavor,\n tv.upper_bound,\n tv.default,\n line=-1,\n column=-1,\n )\n tvs.append(tv)\n inst = Instance(typ, tvs)\n # TODO: do we need to also handle typeddict_type here and below?\n if typ.tuple_type is None:\n return inst\n return typ.tuple_type.copy_modified(fallback=inst)\n\n\ndef fill_typevars_with_any(typ: TypeInfo) -> Instance | TupleType:\n \"\"\"Apply a correct number of Any's as type arguments to a type.\"\"\"\n inst = Instance(typ, erased_vars(typ.defn.type_vars, TypeOfAny.special_form))\n if typ.tuple_type is None:\n return inst\n erased_tuple_type = erase_typevars(typ.tuple_type, {tv.id for tv in typ.defn.type_vars})\n assert isinstance(erased_tuple_type, ProperType)\n if isinstance(erased_tuple_type, TupleType):\n return typ.tuple_type.copy_modified(fallback=inst)\n return inst\n\n\ndef has_no_typevars(typ: Type) -> bool:\n # We test if a type contains type variables by erasing all type variables\n # and comparing the result to the original type. We use comparison by equality that\n # in turn uses `__eq__` defined for types. Note: we can't use `is_same_type` because\n # it is not safe with unresolved forward references, while this function may be called\n # before forward references resolution patch pass. Note also that it is not safe to use\n # `is` comparison because `erase_typevars` doesn't preserve type identity.\n return typ == erase_typevars(typ)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/typevars.py","language":"Python","license":"NOASSERTION","size":2996} {"code":"\"\"\"Helpers for interacting with type var tuples.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Sequence\n\nfrom mypy.types import (\n AnyType,\n Instance,\n ProperType,\n Type,\n TypeVarLikeType,\n TypeVarTupleType,\n UnpackType,\n get_proper_type,\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 extract_unpack(types: Sequence[Type]) -> ProperType | None:\n \"\"\"Given a list of types, extracts either a single type from an unpack, or returns None.\"\"\"\n if len(types) == 1:\n if isinstance(types[0], UnpackType):\n return get_proper_type(types[0].type)\n return None\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/typevartuples.py","language":"Python","license":"NOASSERTION","size":1383} {"code":"\"\"\"Utility functions with no non-trivial dependencies.\"\"\"\n\nfrom __future__ import annotations\n\nimport hashlib\nimport io\nimport json\nimport os\nimport re\nimport shutil\nimport sys\nimport time\nfrom importlib import resources as importlib_resources\nfrom typing import IO, Any, Callable, Container, Final, Iterable, Sequence, Sized, TypeVar\nfrom typing_extensions import Literal\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\n\n import _curses # noqa: F401\n\n CURSES_ENABLED = True\nexcept ImportError:\n CURSES_ENABLED = False\n\nT = TypeVar(\"T\")\n\nif sys.version_info >= (3, 9):\n TYPESHED_DIR: Final = str(importlib_resources.files(\"mypy\") \/ \"typeshed\")\nelse:\n with importlib_resources.path(\n \"mypy\", # mypy-c doesn't support __package__\n \"py.typed\", # a marker file for type information, we assume typeshed to live in the same dir\n ) as _resource:\n TYPESHED_DIR = str(_resource.parent \/ \"typeshed\")\n\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 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 = \"\"\"\n\n\"\"\"\n\nJUNIT_TESTCASE_FAIL_TEMPLATE: Final = \"\"\" \n {text}<\/failure>\n <\/testcase>\n\"\"\"\n\nJUNIT_ERROR_TEMPLATE: Final = \"\"\" \n {text}<\/error>\n <\/testcase>\n\"\"\"\n\nJUNIT_TESTCASE_PASS_TEMPLATE: Final = \"\"\" \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, 8): # noqa: UP036\n sys.exit(\n \"Running {name} with Python 3.7 or lower is not supported; \"\n \"please upgrade to 3.8 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\"])\n gray = curses.tparm(set_color.encode(\"utf-8\"), 1, 9).decode()\n return gray\n\n\ndef should_force_color() -> bool:\n env_var = os.getenv(\"MYPY_FORCE_COLOR\", os.getenv(\"FORCE_COLOR\", \"0\"))\n try:\n return bool(int(env_var))\n except ValueError:\n return bool(env_var)\n\n\nclass FancyFormatter:\n \"\"\"Apply color and bold font to terminal output.\n\n This currently only works on Linux and Mac.\n \"\"\"\n\n def __init__(\n self, f_out: IO[str], f_err: IO[str], hide_error_codes: bool, hide_success: bool = False\n ) -> None:\n self.hide_error_codes = hide_error_codes\n self.hide_success = hide_success\n\n # Check if we are in a human-facing terminal on a supported platform.\n if sys.platform not in (\"linux\", \"darwin\", \"win32\", \"emscripten\"):\n self.dummy_term = True\n return\n if not should_force_color() and (not f_out.isatty() or not f_err.isatty()):\n self.dummy_term = True\n return\n if sys.platform == \"win32\":\n self.dummy_term = not self.initialize_win_colors()\n elif sys.platform == \"emscripten\":\n self.dummy_term = not self.initialize_vt100_colors()\n else:\n self.dummy_term = not self.initialize_unix_colors()\n if not self.dummy_term:\n self.colors = {\n \"red\": self.RED,\n \"green\": self.GREEN,\n \"blue\": self.BLUE,\n \"yellow\": self.YELLOW,\n \"none\": \"\",\n }\n\n def initialize_vt100_colors(self) -> bool:\n \"\"\"Return True if initialization was successful and we can use colors, False otherwise\"\"\"\n # Windows and Emscripten can both use ANSI\/VT100 escape sequences for color\n assert sys.platform in (\"win32\", \"emscripten\")\n self.BOLD = \"\\033[1m\"\n self.UNDER = \"\\033[4m\"\n self.BLUE = \"\\033[94m\"\n self.GREEN = \"\\033[92m\"\n self.RED = \"\\033[91m\"\n self.YELLOW = \"\\033[93m\"\n self.NORMAL = \"\\033[0m\"\n self.DIM = \"\\033[2m\"\n return True\n\n def initialize_win_colors(self) -> bool:\n \"\"\"Return True if initialization was successful and we can use colors, False otherwise\"\"\"\n # Windows ANSI escape sequences are only supported on Threshold 2 and above.\n # we check with an assert at runtime and an if check for mypy, as asserts do not\n # yet narrow platform\n 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),\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\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:\n # setupterm wants a fd to potentially write an \"initialization sequence\".\n # We override sys.stdout for the daemon API so if stdout doesn't have an fd,\n # just give it \/dev\/null.\n try:\n fd = sys.stdout.fileno()\n except io.UnsupportedOperation:\n with open(\"\/dev\/null\", \"rb\") as f:\n curses.setupterm(fd=f.fileno())\n else:\n curses.setupterm(fd=fd)\n except curses.error:\n # Most likely terminfo not found.\n return False\n bold = curses.tigetstr(\"bold\")\n under = curses.tigetstr(\"smul\")\n set_color = curses.tigetstr(\"setaf\")\n set_eseq = curses.tigetstr(\"cup\")\n normal = curses.tigetstr(\"sgr0\")\n\n if not (bold and under and set_color and set_eseq and normal):\n return False\n\n self.NORMAL = normal.decode()\n self.BOLD = bold.decode()\n self.UNDER = under.decode()\n self.DIM = parse_gray_color(set_eseq)\n self.BLUE = curses.tparm(set_color, curses.COLOR_BLUE).decode()\n self.GREEN = curses.tparm(set_color, curses.COLOR_GREEN).decode()\n self.RED = curses.tparm(set_color, curses.COLOR_RED).decode()\n self.YELLOW = curses.tparm(set_color, curses.COLOR_YELLOW).decode()\n return True\n\n def style(\n self,\n text: str,\n color: Literal[\"red\", \"green\", \"blue\", \"yellow\", \"none\"],\n bold: bool = False,\n underline: bool = False,\n dim: bool = False,\n ) -> str:\n \"\"\"Apply simple color and style (underlined or bold).\"\"\"\n if self.dummy_term:\n return text\n if bold:\n start = self.BOLD\n else:\n start = \"\"\n if underline:\n start += self.UNDER\n if dim:\n start += self.DIM\n return start + self.colors[color] + text + self.NORMAL\n\n def fit_in_terminal(\n self, messages: list[str], fixed_terminal_width: int | None = None\n ) -> list[str]:\n \"\"\"Improve readability by wrapping error messages and trimming source code.\"\"\"\n width = fixed_terminal_width or get_terminal_width()\n new_messages = messages.copy()\n for i, error in enumerate(messages):\n 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 ) -> str:\n \"\"\"Format a short summary in case of errors.\"\"\"\n msg = f\"Found {n_errors} error{plural_s(n_errors)} in {n_files} file{plural_s(n_files)}\"\n if blockers:\n msg += \" (errors prevented further checking)\"\n else:\n msg += f\" (checked {n_sources} source file{plural_s(n_sources)})\"\n if not use_color:\n return msg\n return self.style(msg, \"red\", bold=True)\n\n\ndef is_typeshed_file(typeshed_dir: str | None, file: str) -> bool:\n typeshed_dir = typeshed_dir if typeshed_dir is not None else TYPESHED_DIR\n try:\n return os.path.commonpath((typeshed_dir, os.path.abspath(file))) == typeshed_dir\n except ValueError: # Different drives on Windows\n return False\n\n\ndef is_stub_package_file(file: str) -> bool:\n # Use hacky heuristics to check whether file is part of a PEP 561 stub package.\n if not file.endswith(\".pyi\"):\n return False\n return any(component.endswith(\"-stubs\") for component in os.path.split(os.path.abspath(file)))\n\n\ndef unnamed_function(name: str | None) -> bool:\n return name is not None and name == \"_\"\n\n\ntime_ref = time.perf_counter_ns\n\n\ndef time_spent_us(t0: int) -> int:\n return int((time.perf_counter_ns() - t0) \/ 1000)\n\n\ndef plural_s(s: int | Sized) -> str:\n count = s if isinstance(s, int) else len(s)\n if count != 1:\n return \"s\"\n else:\n return \"\"\n\n\ndef quote_docstring(docstr: str) -> str:\n \"\"\"Returns docstring correctly encapsulated in a single or double quoted form.\"\"\"\n # Uses repr to get hint on the correct quotes and escape everything properly.\n # Creating multiline string for prettier output.\n docstr_repr = \"\\n\".join(re.split(r\"(?<=[^\\\\])\\\\n\", repr(docstr)))\n\n if docstr_repr.startswith(\"'\"):\n # Enforce double quotes when it's safe to do so.\n # That is when double quotes are not in the string\n # or when it doesn't end with a single quote.\n if '\"' not in docstr_repr[1:-1] and docstr_repr[-2] != \"'\":\n return f'\"\"\"{docstr_repr[1:-1]}\"\"\"'\n return f\"''{docstr_repr}''\"\n else:\n return f'\"\"{docstr_repr}\"\"'\n\n\ndef json_dumps(obj: object, debug: bool = False) -> bytes:\n if orjson is not None:\n if debug:\n return orjson.dumps(obj, option=orjson.OPT_INDENT_2 | orjson.OPT_SORT_KEYS) # type: ignore[no-any-return]\n else:\n # TODO: If we don't sort keys here, testIncrementalInternalScramble fails\n # We should document exactly what is going on there\n return orjson.dumps(obj, option=orjson.OPT_SORT_KEYS) # type: ignore[no-any-return]\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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/util.py","language":"Python","license":"NOASSERTION","size":32334} {"code":"from __future__ import annotations\n\nimport os\n\nfrom mypy import git\n\n# Base version.\n# - Release versions have the form \"1.2.3\".\n# - Dev versions have the form \"1.2.3+dev\" (PLUS sign to conform to PEP 440).\n# - Before 1.0 we had the form \"0.NNN\".\n__version__ = \"1.13.0\"\nbase_version = __version__\n\nmypy_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))\nif __version__.endswith(\"+dev\") and git.is_git_repo(mypy_dir) and git.have_git():\n __version__ += \".\" + git.git_revision(mypy_dir).decode(\"utf-8\")\n if git.is_dirty(mypy_dir):\n __version__ += \".dirty\"\ndel mypy_dir\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/version.py","language":"Python","license":"NOASSERTION","size":595} {"code":"\"\"\"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","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/_vendor\/mypy\/visitor.py","language":"Python","license":"NOASSERTION","size":16072} {"code":"","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"import typing\nfrom collections.abc import Iterator, Mapping, Sequence\n\nimport attrs\nimport mypy.nodes\nimport mypy.types\nimport mypy.visitor\n\nfrom puya import log\nfrom puya.errors import InternalError\nfrom puya.parse import SourceLocation\nfrom puya.program_refs import ContractReference\nfrom puyapy.awst_build import constants, pytypes\nfrom puyapy.awst_build.arc4_decorators import get_arc4_abimethod_data\nfrom puyapy.awst_build.base_mypy_visitor import BaseMyPyStatementVisitor\nfrom puyapy.awst_build.context import ASTConversionModuleContext\nfrom puyapy.awst_build.utils import get_decorators_by_fullname\nfrom puyapy.models import (\n ARC4ABIMethodData,\n ContractFragmentBase,\n ContractFragmentMethod,\n ContractFragmentStorage,\n)\n\nlogger = log.get_logger(__name__)\n\n\n@attrs.frozen\nclass _ARC4ClientFragment(ContractFragmentBase):\n id: ContractReference\n _methods: dict[str, ContractFragmentMethod] = attrs.field(factory=dict, init=False)\n mro: Sequence[ContractFragmentBase] = attrs.field(default=(), init=False)\n _symbols: dict[str, pytypes.PyType] = attrs.field(factory=dict, init=False)\n\n def add_method(self, data: ARC4ABIMethodData, source_location: SourceLocation) -> None:\n method = ContractFragmentMethod(\n member_name=data.member_name,\n metadata=data,\n is_trivial=True,\n source_location=source_location,\n )\n set_result = self._methods.setdefault(method.member_name, method)\n if set_result is method:\n self._symbols[data.member_name] = data.pytype\n else:\n logger.info(\n f\"previous definition of {method.member_name} was here\",\n location=set_result.source_location,\n )\n logger.error(\n f\"redefinition of {method.member_name}\",\n location=method.source_location,\n )\n\n @typing.override\n @property\n def symbols(self) -> Mapping[str, pytypes.PyType | None]:\n return self._symbols\n\n @typing.override\n def resolve_method(\n self, name: str, *, include_inherited: bool = True\n ) -> ContractFragmentMethod | None:\n return self._methods.get(name)\n\n @typing.override\n def methods(\n self, *, include_inherited: bool = True, include_overridden: bool = False\n ) -> Iterator[ContractFragmentMethod]:\n yield from self._methods.values()\n\n @typing.override\n def resolve_storage(\n self, name: str, *, include_inherited: bool = True\n ) -> ContractFragmentStorage | None:\n return None\n\n @typing.override\n def state(self, *, include_inherited: bool = True) -> Iterator[ContractFragmentStorage]:\n yield from ()\n\n\nclass ARC4ClientASTVisitor(BaseMyPyStatementVisitor[ARC4ABIMethodData | None]):\n @classmethod\n def visit(cls, context: ASTConversionModuleContext, class_def: mypy.nodes.ClassDef) -> None:\n visitor = ARC4ClientASTVisitor(context)\n cref = ContractReference(class_def.info.fullname)\n fragment = _ARC4ClientFragment(id=cref)\n for stmt in class_def.defs.body:\n stmt_loc = context.node_location(stmt)\n with context.log_exceptions(fallback_location=stmt_loc):\n if (abi_method_data := stmt.accept(visitor)) is not None:\n fragment.add_method(abi_method_data, stmt_loc)\n context.add_contract_fragment(fragment)\n\n def empty_statement(self, _stmt: mypy.nodes.Statement) -> None:\n return None\n\n def visit_function(\n self,\n func_def: mypy.nodes.FuncDef,\n decorator: mypy.nodes.Decorator | None,\n ) -> ARC4ABIMethodData | None:\n func_loc = self._location(func_def)\n if decorator is not None:\n dec_by_fullname = get_decorators_by_fullname(self.context, decorator, original=True)\n abimethod_dec = dec_by_fullname.pop(constants.ABIMETHOD_DECORATOR, None)\n for dec_fullname, dec in dec_by_fullname.items():\n logger.error(\n f'unsupported decorator in ARC4Client: \"{dec_fullname}\"',\n location=self._location(dec),\n )\n if abimethod_dec is not None:\n return get_arc4_abimethod_data(self.context, abimethod_dec, func_def)\n logger.error(f\"expected an {constants.ABIMETHOD_DECORATOR} decorator\", location=func_loc)\n return None\n\n def visit_block(self, o: mypy.nodes.Block) -> None:\n raise InternalError(\"shouldn't get here\", self._location(o))\n\n def visit_return_stmt(self, stmt: mypy.nodes.ReturnStmt) -> None:\n self._error(\"illegal Python syntax, return in class body\", location=stmt)\n\n def visit_class_def(self, cdef: mypy.nodes.ClassDef) -> None:\n self._error(\"nested classes are not supported\", location=cdef)\n\n def _unsupported_stmt(self, kind: str, stmt: mypy.nodes.Statement) -> None:\n self._error(\n f\"{kind} statements are not supported in the class body of an ARC4Client\",\n location=stmt,\n )\n\n def visit_assignment_stmt(self, stmt: mypy.nodes.AssignmentStmt) -> None:\n self._unsupported_stmt(\"assignment\", stmt)\n\n def visit_operator_assignment_stmt(self, stmt: mypy.nodes.OperatorAssignmentStmt) -> None:\n self._unsupported_stmt(\"operator assignment\", stmt)\n\n def visit_expression_stmt(self, stmt: mypy.nodes.ExpressionStmt) -> None:\n if isinstance(stmt.expr, mypy.nodes.StrExpr):\n # ignore class docstring, already extracted\n # TODO: should we capture field \"docstrings\"?\n pass\n else:\n self._unsupported_stmt(\"expression statement\", stmt)\n\n def visit_if_stmt(self, stmt: mypy.nodes.IfStmt) -> None:\n self._unsupported_stmt(\"if\", stmt)\n\n def visit_while_stmt(self, stmt: mypy.nodes.WhileStmt) -> None:\n self._unsupported_stmt(\"while\", stmt)\n\n def visit_for_stmt(self, stmt: mypy.nodes.ForStmt) -> None:\n self._unsupported_stmt(\"for\", stmt)\n\n def visit_break_stmt(self, stmt: mypy.nodes.BreakStmt) -> None:\n self._unsupported_stmt(\"break\", stmt)\n\n def visit_continue_stmt(self, stmt: mypy.nodes.ContinueStmt) -> None:\n self._unsupported_stmt(\"continue\", stmt)\n\n def visit_assert_stmt(self, stmt: mypy.nodes.AssertStmt) -> None:\n self._unsupported_stmt(\"assert\", stmt)\n\n def visit_del_stmt(self, stmt: mypy.nodes.DelStmt) -> None:\n self._unsupported_stmt(\"del\", stmt)\n\n def visit_match_stmt(self, stmt: mypy.nodes.MatchStmt) -> None:\n self._unsupported_stmt(\"match\", stmt)\n\n def visit_type_alias_stmt(self, stmt: mypy.nodes.TypeAliasStmt) -> None:\n self._unsupported_stmt(\"type\", stmt)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/arc4_client.py","language":"Python","license":"NOASSERTION","size":6711} {"code":"import re\nimport textwrap\nfrom collections.abc import Iterable, Sequence\nfrom pathlib import Path\n\nfrom puya import (\n arc56_models as arc56,\n log,\n)\nfrom puya.avm import OnCompletionAction\nfrom puya.errors import CodeError\nfrom puya.utils import make_path_relative_to_cwd\nfrom puyapy.awst_build import constants\nfrom puyapy.awst_build.arc4_utils import arc4_to_pytype\n\nlogger = log.get_logger(__name__)\n\n_AUTO_GENERATED_COMMENT = \"# This file is auto-generated, do not modify\"\n_INDENT = \" \" * 4\n_NON_ALPHA_NUMERIC = re.compile(r\"\\W+\")\n\n\ndef write_arc4_client(contract: arc56.Contract, out_dir: Path) -> None:\n stub_path = out_dir \/ f\"client_{contract.name}.py\"\n if _can_overwrite_auto_generated_file(stub_path):\n logger.info(f\"writing {make_path_relative_to_cwd(stub_path)}\")\n stub_text = _ClientGenerator.generate(contract)\n stub_path.write_text(stub_text)\n else:\n logger.error(\n f\"Not outputting {make_path_relative_to_cwd(stub_path)} \"\n \"since content does not appear to be auto-generated\"\n )\n\n\ndef _can_overwrite_auto_generated_file(path: Path) -> bool:\n return not path.exists() or path.read_text().startswith(_AUTO_GENERATED_COMMENT)\n\n\nclass _ClientGenerator:\n def __init__(self, contract: arc56.Contract):\n self.contract = contract\n self.python_methods = set[str]()\n self.struct_to_class = dict[str, str]()\n self.reserved_class_names = set[str]()\n self.reserved_method_names = set[str]()\n self.class_decls = list[str]()\n\n @classmethod\n def generate(cls, contract: arc56.Contract) -> str:\n return cls(contract)._gen() # noqa: SLF001\n\n def _gen(self) -> str:\n # generate class definitions for any referenced structs in methods\n # don't generate from self.contract.structs as it may contain other struct definitions\n client_class = self._unique_class(self.contract.name)\n for method in self.contract.methods:\n for struct in filter(None, (method.returns.struct, *(a.struct for a in method.args))):\n if struct not in self.struct_to_class and (\n struct_def := self.contract.structs.get(struct)\n ):\n self._prepare_struct_class(struct, struct_def)\n return \"\\n\".join(\n (\n _AUTO_GENERATED_COMMENT,\n \"# flake8: noqa\", # this works for flake8 and ruff\n \"# fmt: off\", # disable formatting\"\n \"import typing\",\n \"\",\n \"import algopy\",\n \"\",\n *self.class_decls,\n \"\",\n f\"class {client_class}(algopy.arc4.ARC4Client, typing.Protocol):\",\n *_docstring(self.contract.desc),\n *self._gen_methods(),\n )\n )\n\n def _prepare_struct_class(self, name: str, fields: Sequence[arc56.StructField]) -> str:\n python_name = self._unique_class(name)\n self.struct_to_class[name] = python_name\n lines = [f\"class {python_name}(algopy.arc4.Struct):\"]\n for field in fields:\n if isinstance(field.type, str):\n typ = self._get_client_type(field.type)\n else:\n # generate anonymous struct type\n anon_struct = f\"{name}_{field.name}\"\n typ = self._prepare_struct_class(anon_struct, field.type)\n lines.append(_indent(f\"{field.name}: {typ}\"))\n if self.class_decls:\n self.class_decls.append(\"\")\n self.class_decls.extend(lines)\n return python_name\n\n def _get_client_type(self, typ: str) -> str:\n # map ABI \/ AVM type to algopy type\n if typ == arc56.AVMType.uint64:\n return \"algopy.UInt64\"\n elif typ == arc56.AVMType.bytes:\n return \"algopy.Bytes\"\n elif struct := self.contract.structs.get(typ):\n try:\n # use existing definition\n return self.struct_to_class[typ]\n except KeyError:\n # generate and return class name\n return self._prepare_struct_class(typ, struct)\n else:\n return str(arc4_to_pytype(typ, None))\n\n def _unique_class(self, name: str) -> str:\n base_name = name = _get_python_safe_name(name)\n seq = 1\n while name in self.reserved_class_names:\n seq += 1\n name = f\"{base_name}{seq}\"\n\n self.reserved_class_names.add(name)\n return name\n\n def _unique_method(self, name: str) -> str:\n base_name = name = _get_python_safe_name(name)\n seq = 1\n while name in self.reserved_method_names:\n seq += 1\n name = f\"{base_name}{seq}\"\n\n self.reserved_method_names.add(name)\n return name\n\n def _gen_methods(self) -> Iterable[str]:\n if not self.contract.methods:\n yield _indent(\"pass\")\n yield \"\"\n else:\n for method in self.contract.methods:\n yield self._gen_method(method)\n\n def _gen_method(self, method: arc56.Method) -> str:\n return_type = self._get_client_type(method.returns.struct or method.returns.type)\n python_method = self._unique_method(method.name)\n return _indent(\n (\n _arc4_method_to_decorator(python_method, method),\n f\"def {python_method}(\",\n _indent(\n (\n \"self,\",\n *(self._gen_arg(arg) for arg in method.args),\n )\n ),\n f\") -> {return_type}:\" + (\"\" if method.desc else \" ...\"),\n *_docstring(method.desc),\n \"\",\n )\n )\n\n def _gen_arg(self, arg: arc56.MethodArg) -> str:\n python_type = self._get_client_type(arg.struct or arg.type)\n return f\"{arg.name}: {python_type},\"\n\n\ndef _docstring(desc: str | None) -> list[str]:\n if desc is None:\n return []\n return _indent(\n [\n '\"\"\"',\n *desc.splitlines(),\n '\"\"\"',\n ]\n ).splitlines()\n\n\ndef _arc4_method_to_decorator(python_method: str, method: arc56.Method) -> str:\n abimethod_args = dict[str, object]()\n if method.name != python_method:\n abimethod_args[\"name\"] = method.name\n if method.readonly:\n abimethod_args[\"readonly\"] = True\n if not _compatible_actions(method.actions.create, method.actions.call):\n # TODO: support this, once decorators support it\n raise CodeError(\n f\"unsupported on completion combination for generating an ARC4 client\"\n f\" for method: {method.name}\"\n )\n actions = sorted(\n {*method.actions.create, *method.actions.call}, key=lambda a: OnCompletionAction[a]\n )\n if set(actions) != {OnCompletionAction.NoOp.name}:\n abimethod_args[\"allow_actions\"] = actions\n if method.actions.create and method.actions.call:\n abimethod_args[\"create\"] = \"allow\"\n elif method.actions.create:\n abimethod_args[\"create\"] = \"require\"\n else:\n # disallow is default\n pass\n kwargs = \", \".join(f\"{name}={value!r}\" for name, value in abimethod_args.items())\n decorator = f\"@{constants.ABIMETHOD_DECORATOR_ALIAS}\"\n if kwargs:\n decorator += f\"({kwargs})\"\n return decorator\n\n\ndef _compatible_actions(create: Sequence[str], call: Sequence[str]) -> bool:\n if not create:\n return True\n if not call:\n return True\n # if both collections are present, then they are compatible if everything in\n # create is also in call\n return all(a in call for a in create)\n\n\ndef _indent(lines: Iterable[str] | str) -> str:\n if not isinstance(lines, str):\n lines = \"\\n\".join(lines)\n return textwrap.indent(lines, _INDENT)\n\n\ndef _get_python_safe_name(name: str) -> str:\n return _NON_ALPHA_NUMERIC.sub(\"_\", name)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/arc4_client_gen.py","language":"Python","license":"NOASSERTION","size":7941} {"code":"import typing\n\nimport mypy.nodes\nimport mypy.visitor\nfrom immutabledict import immutabledict\n\nfrom puya import log\nfrom puya.avm import OnCompletionAction\nfrom puya.awst.nodes import (\n ABIMethodArgConstantDefault,\n ABIMethodArgDefault,\n ABIMethodArgMemberDefault,\n ARC4ABIMethodConfig,\n ARC4BareMethodConfig,\n ARC4CreateOption,\n Expression,\n)\nfrom puya.errors import CodeError, InternalError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.context import ASTConversionModuleContext\nfrom puyapy.awst_build.eb.interface import NodeBuilder\nfrom puyapy.awst_build.subroutine import ExpressionASTConverter, require_instance_builder\nfrom puyapy.awst_build.utils import extract_decorator_args, get_unaliased_fullname\nfrom puyapy.models import ARC4ABIMethodData, ARC4BareMethodData\n\nlogger = log.get_logger(__name__)\n\n\ndef get_arc4_baremethod_data(\n context: ASTConversionModuleContext,\n decorator: mypy.nodes.Expression,\n func_def: mypy.nodes.FuncDef,\n) -> ARC4BareMethodData:\n dec_loc = context.node_location(decorator, func_def.info)\n pytype, func_types = _get_func_types(context, func_def, dec_loc)\n if func_types != {\"output\": pytypes.NoneType}:\n logger.error(\"bare methods should have no arguments or return values\", location=dec_loc)\n\n named_args = _extract_decorator_named_args(context, decorator, dec_loc)\n evaluated_args = {n: _parse_decorator_arg(context, n, a) for n, a in named_args.items()}\n\n create = _extract_create_option(evaluated_args, dec_loc)\n allowed_completion_types = _extract_allow_actions_option(evaluated_args, dec_loc)\n if evaluated_args:\n logger.error(\n f\"unexpected parameters: {', '.join(map(str, evaluated_args))}\", location=dec_loc\n )\n\n return ARC4BareMethodData(\n member_name=func_def.name,\n pytype=pytype,\n config=ARC4BareMethodConfig(\n allowed_completion_types=allowed_completion_types,\n create=create,\n source_location=dec_loc,\n ),\n source_location=dec_loc,\n )\n\n\n_READONLY = \"readonly\"\n_CLIENT_DEFAULTS = \"default_args\"\n_ALLOWED_ACTIONS = \"allow_actions\"\n_CREATE_OPTIONS = \"create\"\n_NAME_OVERRIDE = \"name\"\n\n\ndef get_arc4_abimethod_data(\n context: ASTConversionModuleContext,\n decorator: mypy.nodes.Expression,\n func_def: mypy.nodes.FuncDef,\n) -> ARC4ABIMethodData:\n dec_loc = context.node_location(decorator, func_def.info)\n pytype, func_types = _get_func_types(context, func_def, dec_loc)\n\n named_args = _extract_decorator_named_args(context, decorator, dec_loc)\n evaluated_args = {n: _parse_decorator_arg(context, n, a) for n, a in named_args.items()}\n\n create = _extract_create_option(evaluated_args, dec_loc)\n allowed_completion_types = _extract_allow_actions_option(evaluated_args, dec_loc)\n # map \"name\" param\n name = func_def.name\n match evaluated_args.pop(_NAME_OVERRIDE, None):\n case None:\n pass\n case str(name):\n pass\n case invalid_name:\n context.error(f\"invalid name option: {invalid_name}\", dec_loc)\n\n # map \"readonly\" param\n default_readonly = False\n match evaluated_args.pop(_READONLY, default_readonly):\n case bool(readonly):\n pass\n case invalid_readonly_option:\n context.error(f\"invalid readonly option: {invalid_readonly_option}\", dec_loc)\n readonly = default_readonly\n\n # map \"default_args\" param\n default_args = dict[str, ABIMethodArgDefault]()\n match evaluated_args.pop(_CLIENT_DEFAULTS, {}):\n case {**options}:\n method_arg_names = func_types.keys() - {\"output\"}\n for parameter, value in options.items():\n if parameter not in method_arg_names:\n context.error(\n f\"{parameter!r} is not a parameter of {func_def.fullname}\",\n dec_loc,\n )\n else:\n # if it's in method_arg_names, it's a str\n assert isinstance(parameter, str)\n if isinstance(value, str):\n default_args[parameter] = ABIMethodArgMemberDefault(name=value)\n elif isinstance(value, Expression):\n default_args[parameter] = ABIMethodArgConstantDefault(value=value)\n else:\n context.error(f\"invalid default_args value: {value!r}\", dec_loc)\n case invalid_default_args_option:\n context.error(f\"invalid default_args option: {invalid_default_args_option}\", dec_loc)\n\n config = ARC4ABIMethodConfig(\n source_location=dec_loc,\n allowed_completion_types=allowed_completion_types,\n create=create,\n name=name,\n readonly=readonly,\n default_args=immutabledict(default_args),\n )\n return ARC4ABIMethodData(\n member_name=func_def.name,\n pytype=pytype,\n config=config,\n signature=func_types,\n source_location=dec_loc,\n )\n\n\ndef _get_func_types(\n context: ASTConversionModuleContext, func_def: mypy.nodes.FuncDef, location: SourceLocation\n) -> tuple[pytypes.FuncType, dict[str, pytypes.PyType]]:\n if func_def.type is None:\n raise CodeError(\"typing error\", location)\n func_type = context.type_to_pytype(\n func_def.type, source_location=context.node_location(func_def, module_src=func_def.info)\n )\n if not isinstance(func_type, pytypes.FuncType):\n raise InternalError(\n f\"unexpected type result for ABI function definition type: {type(func_type).__name__}\",\n location,\n )\n\n def require_arg_name(arg: pytypes.FuncArg) -> str:\n if arg.name is None:\n raise CodeError(\n \"positional only arguments are not supported with ARC-4 methods\", location\n )\n return arg.name\n\n result = {require_arg_name(arg): arg.type for arg in func_type.args}\n if \"output\" in result:\n # https:\/\/github.com\/algorandfoundation\/ARCs\/blob\/main\/assets\/arc-0032\/application.schema.json\n raise CodeError(\n \"for compatibility with ARC-32, ARC-4 methods cannot have an argument named output\",\n location,\n )\n result[\"output\"] = func_type.ret_type\n return func_type, result\n\n\ndef _extract_decorator_named_args(\n context: ASTConversionModuleContext, decorator: mypy.nodes.Expression, location: SourceLocation\n) -> dict[str, mypy.nodes.Expression]:\n result = {}\n for name, value in extract_decorator_args(decorator, location):\n if name is None:\n logger.error(\"unexpected positional argument\", location=context.node_location(value))\n elif name in result:\n logger.error(\"duplicate named argument\", location=context.node_location(value))\n else:\n result[name] = value\n return result\n\n\ndef _parse_decorator_arg(\n context: ASTConversionModuleContext, name: str, value: mypy.nodes.Expression\n) -> object:\n visitor = _ARC4DecoratorArgEvaluator(context, name)\n return value.accept(visitor)\n\n\nclass _ARC4DecoratorArgEvaluator(mypy.visitor.NodeVisitor[object]):\n def __init__(self, context: ASTConversionModuleContext, arg_name: str):\n self.context = context\n self.arg_name = arg_name\n\n def __getattribute__(self, name: str) -> object:\n attr = super().__getattribute__(name)\n if name.startswith(\"visit_\") and not attr.__module__.startswith(\"puyapy.\"):\n return self._not_supported\n return attr\n\n def _not_supported(self, o: mypy.nodes.Context) -> typing.Never:\n raise CodeError(\"unexpected argument type\", self.context.node_location(o))\n\n def _resolve_constant_reference(self, expr: mypy.nodes.RefExpr) -> object:\n try:\n return self.context.constants[expr.fullname]\n except KeyError:\n raise CodeError(\n f\"Unresolved module constant: {expr.fullname}\", self.context.node_location(expr)\n ) from None\n\n @typing.override\n def visit_call_expr(self, o: mypy.nodes.CallExpr) -> Expression:\n return _parse_expression(self.context, o)\n\n @typing.override\n def visit_str_expr(self, o: mypy.nodes.StrExpr) -> str:\n return o.value\n\n @typing.override\n def visit_name_expr(self, o: mypy.nodes.NameExpr) -> object:\n if self.arg_name == _READONLY:\n if o.fullname == \"builtins.True\":\n return True\n if o.fullname == \"builtins.False\":\n return False\n elif self.arg_name == _CLIENT_DEFAULTS:\n if isinstance(o.node, mypy.nodes.Decorator):\n return o.name # assume abimethod\n return self._resolve_constant_reference(o)\n\n @typing.override\n def visit_member_expr(self, o: mypy.nodes.MemberExpr) -> object:\n if self.arg_name == _ALLOWED_ACTIONS and isinstance(o.expr, mypy.nodes.RefExpr):\n unaliased_base_fullname = get_unaliased_fullname(o.expr)\n if unaliased_base_fullname == pytypes.OnCompleteActionType.name:\n try:\n OnCompletionAction[o.name]\n except KeyError:\n raise CodeError(\n f\"unable to resolve constant value for {unaliased_base_fullname}.{o.name}\",\n self.context.node_location(o),\n ) from None\n else:\n return o.name\n\n return self._resolve_constant_reference(o)\n\n @typing.override\n def visit_unary_expr(self, o: mypy.nodes.UnaryExpr) -> object:\n if self.arg_name == _READONLY:\n operand = o.expr.accept(self)\n if o.op == \"not\":\n return not operand\n elif self.arg_name == _CLIENT_DEFAULTS:\n return _parse_expression(self.context, o)\n self._not_supported(o)\n\n @typing.override\n def visit_list_expr(self, o: mypy.nodes.ListExpr) -> object:\n if self.arg_name == _ALLOWED_ACTIONS:\n return [item.accept(self) for item in o.items]\n self._not_supported(o)\n\n @typing.override\n def visit_tuple_expr(self, o: mypy.nodes.TupleExpr) -> object:\n if self.arg_name == _ALLOWED_ACTIONS:\n return tuple(item.accept(self) for item in o.items)\n elif self.arg_name == _CLIENT_DEFAULTS:\n return _parse_expression(self.context, o)\n self._not_supported(o)\n\n @typing.override\n def visit_dict_expr(self, o: mypy.nodes.DictExpr) -> dict[object, object]:\n return {key.accept(self) if key else None: value.accept(self) for key, value in o.items}\n\n\ndef _parse_expression(\n context: ASTConversionModuleContext, node: mypy.nodes.Expression\n) -> Expression:\n converter = _ConstantExpressionASTConverter(context)\n node_builder = node.accept(converter)\n instance_builder = require_instance_builder(node_builder)\n return instance_builder.resolve()\n\n\nclass _ConstantExpressionASTConverter(ExpressionASTConverter):\n @typing.override\n def resolve_local_type(self, var_name: str, expr_loc: SourceLocation) -> pytypes.PyType | None:\n raise CodeError(\"local variables not supported in decorators\", expr_loc)\n\n @typing.override\n def builder_for_self(self, expr_loc: SourceLocation) -> NodeBuilder:\n raise InternalError(\"self variable outside of method\", expr_loc)\n\n @typing.override\n def visit_super_expr(self, o: mypy.nodes.SuperExpr) -> typing.Never:\n raise CodeError(\"super expressions not supported in decorators\", self._location(o))\n\n @typing.override\n def visit_assignment_expr(self, o: mypy.nodes.AssignmentExpr) -> typing.Never:\n raise CodeError(\"assignment expressions not supported in decorators\", self._location(o))\n\n\ndef _extract_create_option(\n evaluated_args: dict[str, object], location: SourceLocation\n) -> ARC4CreateOption:\n default_value = ARC4CreateOption.disallow\n option_name = evaluated_args.pop(_CREATE_OPTIONS, default_value.name)\n try:\n return ARC4CreateOption[option_name] # type: ignore[misc]\n except KeyError:\n logger.error( # noqa: TRY400\n f\"invalid create option value: {option_name}\", location=location\n )\n return default_value\n\n\ndef _extract_allow_actions_option(\n evaluated_args: dict[str, object], location: SourceLocation\n) -> list[OnCompletionAction]:\n allowed_completion_types = []\n match evaluated_args.pop(_ALLOWED_ACTIONS, None):\n case None:\n pass\n case []:\n logger.error(\"empty allow_actions\", location=location)\n case [*allow_actions]:\n for a in allow_actions:\n oca = _allowed_oca(a)\n if oca is None:\n logger.error(f\"invalid allow action: {a}\", location=location)\n elif oca in allowed_completion_types:\n logger.error(f\"duplicate value in allow_actions: {a}\", location=location)\n else:\n allowed_completion_types.append(oca)\n case invalid_allow_actions_option:\n logger.error(\n f\"invalid allow_actions option: {invalid_allow_actions_option}\", location=location\n )\n # defaults set last in case of one or more errors above\n return allowed_completion_types or [OnCompletionAction.NoOp]\n\n\ndef _allowed_oca(name: object) -> OnCompletionAction | None:\n if not isinstance(name, str):\n return None\n try:\n result = OnCompletionAction[name]\n except KeyError:\n return None\n if result is OnCompletionAction.ClearState:\n return None\n return result\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/arc4_decorators.py","language":"Python","license":"NOASSERTION","size":13698} {"code":"import re\nimport typing\nfrom collections.abc import Callable, Iterable\n\nimport attrs\nimport mypy.nodes\nimport mypy.visitor\n\nfrom puya import log\nfrom puya.avm import TransactionType\nfrom puya.awst import wtypes\nfrom puya.errors import CodeError, InternalError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\n\n__all__ = [\n \"arc4_to_pytype\",\n \"pytype_to_arc4\",\n \"pytype_to_arc4_pytype\",\n]\n\nlogger = log.get_logger(__name__)\n\n\ndef _is_arc4_struct(typ: pytypes.PyType) -> typing.TypeGuard[pytypes.StructType]:\n if not (pytypes.ARC4StructBaseType < typ):\n return False\n if not isinstance(typ, pytypes.StructType):\n raise InternalError(\n f\"Type inherits from {pytypes.ARC4StructBaseType!r}\"\n f\" but structure type is {type(typ).__name__!r}\"\n )\n return True\n\n\n@attrs.frozen\nclass _DecoratorData:\n fullname: str\n args: list[tuple[str | None, mypy.nodes.Expression]]\n source_location: SourceLocation\n\n\ndef pytype_to_arc4_pytype(\n pytype: pytypes.PyType,\n on_error: Callable[[pytypes.PyType], pytypes.PyType],\n) -> pytypes.PyType:\n match pytype:\n case pytypes.BoolType:\n return pytypes.ARC4BoolType\n case pytypes.NamedTupleType():\n return pytypes.StructType(\n base=pytypes.ARC4StructBaseType,\n desc=pytype.desc,\n name=pytype.name,\n fields={\n name: pytype_to_arc4_pytype(t, on_error) for name, t in pytype.fields.items()\n },\n frozen=True,\n source_location=pytype.source_location,\n )\n case pytypes.TupleType():\n return pytypes.GenericARC4TupleType.parameterise(\n [pytype_to_arc4_pytype(t, on_error) for t in pytype.items], pytype.source_location\n )\n case pytypes.NoneType | pytypes.GroupTransactionType():\n return pytype\n\n if pytypes.UInt64Type <= pytype:\n return pytypes.ARC4UIntN_Aliases[64]\n elif pytypes.BigUIntType <= pytype:\n return pytypes.ARC4UIntN_Aliases[512]\n elif pytypes.BytesType <= pytype:\n return pytypes.ARC4DynamicBytesType\n elif pytypes.StringType <= pytype:\n return pytypes.ARC4StringType\n elif pytype.is_type_or_subtype(\n pytypes.ApplicationType, pytypes.AssetType, pytypes.AccountType\n ) or isinstance(pytype.wtype, wtypes.ARC4Type):\n return pytype\n else:\n return on_error(pytype)\n\n\n_UINT_REGEX = re.compile(r\"^uint(?P[0-9]+)$\")\n_UFIXED_REGEX = re.compile(r\"^ufixed(?P[0-9]+)x(?P[0-9]+)$\")\n_FIXED_ARRAY_REGEX = re.compile(r\"^(?P.+)\\[(?P[0-9]+)]$\")\n_DYNAMIC_ARRAY_REGEX = re.compile(r\"^(?P.+)\\[]$\")\n_TUPLE_REGEX = re.compile(r\"^\\((?P.+)\\)$\")\n_ARC4_PYTYPE_MAPPING = {\n \"bool\": pytypes.ARC4BoolType,\n \"string\": pytypes.ARC4StringType,\n \"account\": pytypes.AccountType,\n \"application\": pytypes.ApplicationType,\n \"asset\": pytypes.AssetType,\n \"void\": pytypes.NoneType,\n \"txn\": pytypes.GroupTransactionTypes[None],\n **{t.name: pytypes.GroupTransactionTypes[t] for t in TransactionType},\n \"address\": pytypes.ARC4AddressType,\n \"byte\": pytypes.ARC4ByteType,\n \"byte[]\": pytypes.ARC4DynamicBytesType,\n}\n\n\ndef arc4_to_pytype(typ: str, location: SourceLocation | None = None) -> pytypes.PyType:\n if known_typ := _ARC4_PYTYPE_MAPPING.get(typ):\n return known_typ\n if uint := _UINT_REGEX.match(typ):\n n = int(uint.group(\"n\"))\n n_typ = pytypes.TypingLiteralType(value=n, source_location=None)\n if n <= 64:\n return pytypes.GenericARC4UIntNType.parameterise([n_typ], location)\n else:\n return pytypes.GenericARC4BigUIntNType.parameterise([n_typ], location)\n if ufixed := _UFIXED_REGEX.match(typ):\n n, m = map(int, ufixed.group(\"n\", \"m\"))\n n_typ = pytypes.TypingLiteralType(value=n, source_location=None)\n m_typ = pytypes.TypingLiteralType(value=m, source_location=None)\n if n <= 64:\n return pytypes.GenericARC4UFixedNxMType.parameterise([n_typ, m_typ], location)\n else:\n return pytypes.GenericARC4BigUFixedNxMType.parameterise([n_typ, m_typ], location)\n if fixed_array := _FIXED_ARRAY_REGEX.match(typ):\n arr_type, size_str = fixed_array.group(\"type\", \"size\")\n size = int(size_str)\n size_typ = pytypes.TypingLiteralType(value=size, source_location=None)\n element_type = arc4_to_pytype(arr_type, location)\n return pytypes.GenericARC4StaticArrayType.parameterise([element_type, size_typ], location)\n if dynamic_array := _DYNAMIC_ARRAY_REGEX.match(typ):\n arr_type = dynamic_array.group(\"type\")\n element_type = arc4_to_pytype(arr_type, location)\n return pytypes.GenericARC4DynamicArrayType.parameterise([element_type], location)\n if tuple_match := _TUPLE_REGEX.match(typ):\n tuple_types = [\n arc4_to_pytype(x, location) for x in split_tuple_types(tuple_match.group(\"types\"))\n ]\n return pytypes.GenericARC4TupleType.parameterise(tuple_types, location)\n raise CodeError(f\"unknown ARC4 type '{typ}'\", location)\n\n\ndef pytype_to_arc4(typ: pytypes.PyType, loc: SourceLocation | None = None) -> str:\n def on_error(bad_type: pytypes.PyType) -> typing.Never:\n raise CodeError(\n f\"not an ARC4 type or native equivalent: {bad_type}\",\n loc or getattr(bad_type, \"source_location\", None),\n )\n\n arc4_pytype = pytype_to_arc4_pytype(typ, on_error)\n match arc4_pytype:\n case pytypes.NoneType:\n return \"void\"\n case pytypes.AssetType:\n return \"asset\"\n case pytypes.AccountType:\n return \"account\"\n case pytypes.ApplicationType:\n return \"application\"\n case pytypes.TransactionRelatedType(transaction_type=transaction_type):\n return transaction_type.name if transaction_type else \"txn\"\n wtype = arc4_pytype.wtype\n if not isinstance(wtype, wtypes.ARC4Type):\n raise CodeError(f\"not an ARC4 type or native equivalent: {wtype}\", loc)\n return wtype.arc4_name\n\n\ndef split_tuple_types(types: str) -> Iterable[str]:\n \"\"\"Splits inner tuple types into individual elements.\n\n e.g. \"uint64,(uint8,string),bool\" becomes [\"uint64\", \"(uint8,string)\", \"bool\"]\n \"\"\"\n tuple_level = 0\n last_idx = 0\n for idx, tok in enumerate(types):\n if tok == \"(\":\n tuple_level += 1\n elif tok == \")\":\n tuple_level -= 1\n if tok == \",\" and tuple_level == 0:\n yield types[last_idx:idx]\n last_idx = idx + 1\n yield types[last_idx:]\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/arc4_utils.py","language":"Python","license":"NOASSERTION","size":6689} {"code":"import abc\nimport typing\n\nimport mypy.checker\nimport mypy.nodes\nimport mypy.visitor\n\nfrom puya.errors import CodeError, InternalError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build.context import ASTConversionModuleContext\nfrom puyapy.awst_build.exceptions import UnsupportedASTError\nfrom puyapy.awst_build.utils import refers_to_fullname\n\n\nclass _BaseMyPyVisitor:\n def __init__(self, context: ASTConversionModuleContext):\n self.context = context\n\n def _location(self, node: mypy.nodes.Context) -> SourceLocation:\n return self.context.node_location(node)\n\n def _error(self, msg: str, location: mypy.nodes.Context | SourceLocation) -> None:\n self.context.error(msg, location)\n\n def _precondition(\n self,\n condition: bool, # noqa: FBT001\n \/,\n msg: str,\n location: mypy.nodes.Context | SourceLocation,\n ) -> None:\n if not condition:\n raise InternalError(\n msg,\n self._location(location) if isinstance(location, mypy.nodes.Context) else location,\n )\n\n def _unsupported_node(self, node: mypy.nodes.Context, details: str) -> typing.Never:\n raise UnsupportedASTError(node, self._location(node), details=details)\n\n\nclass BaseMyPyStatementVisitor[_TStatement](\n _BaseMyPyVisitor,\n mypy.visitor.StatementVisitor[_TStatement],\n abc.ABC,\n):\n # ~~~ things we can just ignore ~~~ #\n @typing.override\n def visit_pass_stmt(self, o: mypy.nodes.PassStmt) -> _TStatement:\n return self.empty_statement(o)\n\n @typing.override\n def visit_import(self, o: mypy.nodes.Import) -> _TStatement:\n return self.empty_statement(o)\n\n @typing.override\n def visit_import_from(self, o: mypy.nodes.ImportFrom) -> _TStatement:\n return self.empty_statement(o)\n\n @typing.override\n def visit_import_all(self, o: mypy.nodes.ImportAll) -> _TStatement:\n return self.empty_statement(o)\n\n @abc.abstractmethod\n def empty_statement(self, stmt: mypy.nodes.Statement) -> _TStatement: ...\n\n # ~~~ simplify function (decorated, overloaded, normal) visitation ~~~ #\n\n def check_fatal_decorators(self, exprs: list[mypy.nodes.Expression]) -> None:\n for dec_expr in exprs:\n if isinstance(dec_expr, mypy.nodes.CallExpr):\n dec_expr = dec_expr.callee\n if isinstance(dec_expr, mypy.nodes.RefExpr):\n if refers_to_fullname(\n dec_expr, \"typing.no_type_check\", \"typing_extensions.no_type_check\"\n ):\n raise CodeError(\n \"no_type_check is not supported -\"\n \" type checking is required for compilation\",\n self._location(dec_expr),\n )\n else:\n self.context.warning(\n \"Unable to determine full name of expression\", self._location(dec_expr)\n )\n\n @typing.final\n @typing.override\n def visit_func_def(self, fdef: mypy.nodes.FuncDef) -> _TStatement:\n self._precondition(\n not fdef.is_decorated,\n \"Decorated functions should have been visited via visit_decorator\",\n fdef,\n )\n self._precondition(not fdef.is_property, \"Property function that is not decorated??\", fdef)\n return self._do_function(fdef, decorator=None)\n\n @typing.final\n @typing.override\n def visit_decorator(self, dec: mypy.nodes.Decorator) -> _TStatement:\n self.check_fatal_decorators(dec.decorators)\n if mypy.checker.is_property(dec):\n self._unsupported_node(dec, \"property decorator\/descriptor not supported currently\")\n return self._do_function(dec.func, dec)\n\n @typing.final\n @typing.override\n def visit_overloaded_func_def(self, o: mypy.nodes.OverloadedFuncDef) -> _TStatement:\n # This could either be a @typing.overload, in which case o.impl will contain\n # the actual function, or it could be a @property with a setter and\/or a deleter,\n # in which case o.impl will be None\n if mypy.checker.is_property(o):\n self._unsupported_node(o, \"property decorator\/descriptor not supported currently\")\n if o.impl:\n self.context.warning(\n \"@typing.overload() should not be required, \"\n \"and may not function exactly as intended\",\n o,\n )\n return o.impl.accept(self)\n else:\n # typing.overload sequences should always have an implementation,\n # unless they're in a stub file - but we don't process those,\n # so we shouldn't get here\n raise CodeError(\n \"An overloaded function outside a stub file must have an implementation\",\n self._location(o),\n )\n\n def _do_function(\n self,\n fdef: mypy.nodes.FuncDef,\n decorator: mypy.nodes.Decorator | None,\n ) -> _TStatement:\n self._precondition(\n not fdef.is_mypy_only, \"function is defined in TYPE_CHECKING block\", fdef\n ) # we shouldn't get here\n if fdef.is_generator:\n self._unsupported_node(fdef, \"generator functions are not supported\")\n if fdef.is_coroutine or fdef.is_awaitable_coroutine or fdef.is_async_generator:\n self._unsupported_node(fdef, \"async functions are not supported\")\n if fdef.dataclass_transform_spec is not None:\n self._unsupported_node(fdef, \"data class transforms (PEP-681) are not supported \")\n return self.visit_function(fdef, decorator)\n\n @abc.abstractmethod\n def visit_function(\n self,\n fdef: mypy.nodes.FuncDef,\n decorator: mypy.nodes.Decorator | None,\n ) -> _TStatement: ...\n\n # ~~~ unsupported scope modifiers ~~~ #\n @typing.override\n def visit_global_decl(self, stmt: mypy.nodes.GlobalDecl) -> typing.Never:\n self._unsupported_node(stmt, \"global variables must be immutable\")\n\n # TODO: do we reject nonlocal here too? are nested functions in\/out?\n @typing.override\n def visit_nonlocal_decl(self, o: mypy.nodes.NonlocalDecl) -> typing.Never:\n self._unsupported_node(o, \"nested functions are not supported\")\n\n # ~~~ raising and handling exceptions unsupported ~~~ #\n @typing.override\n def visit_raise_stmt(self, stmt: mypy.nodes.RaiseStmt) -> typing.Never:\n self._unsupported_node(stmt, \"exception raising and exception handling not supported\")\n\n @typing.override\n def visit_try_stmt(self, stmt: mypy.nodes.TryStmt) -> typing.Never:\n self._unsupported_node(stmt, \"exception raising and exception handling not supported\")\n\n @typing.override\n def visit_with_stmt(self, stmt: mypy.nodes.WithStmt) -> typing.Never:\n self._unsupported_node(\n stmt,\n \"context managers are redundant due to a lack of exception support\",\n )\n\n\nclass BaseMyPyExpressionVisitor[_TExpression](\n _BaseMyPyVisitor,\n mypy.visitor.ExpressionVisitor[_TExpression],\n abc.ABC,\n):\n # ~~~ things that we support but shouldn't encounter via visitation ~~~ #\n @typing.override\n def visit_star_expr(self, expr: mypy.nodes.StarExpr) -> _TExpression:\n # star expression examples (non-exhaustive):\n # head, *tail = my_list\n # my_func(first, *rest)\n # [prepend, *existing]\n raise InternalError(\n \"star expressions should be handled at a higher level\", self._location(expr)\n )\n\n @typing.override\n def visit_dictionary_comprehension(\n self, expr: mypy.nodes.DictionaryComprehension\n ) -> typing.Never:\n self._unsupported_node(expr, \"dictionaries are not supported\")\n\n @typing.override\n def visit_set_expr(self, expr: mypy.nodes.SetExpr) -> typing.Never:\n self._unsupported_node(expr, \"sets are not supported\")\n\n @typing.override\n def visit_set_comprehension(self, expr: mypy.nodes.SetComprehension) -> typing.Never:\n self._unsupported_node(expr, \"sets are not supported\")\n\n # ~~~ math we don't support (yet?) ~~~ #\n @typing.override\n def visit_float_expr(self, expr: mypy.nodes.FloatExpr) -> typing.Never:\n self._unsupported_node(expr, \"floating point math is not supported\")\n\n @typing.override\n def visit_complex_expr(self, expr: mypy.nodes.ComplexExpr) -> typing.Never:\n self._unsupported_node(expr, \"complex math is not supported\")\n\n # ~~~ generator functions unsupported ~~~ #\n @typing.override\n def visit_generator_expr(self, expr: mypy.nodes.GeneratorExpr) -> typing.Never:\n self._unsupported_node(expr, \"generator functions are not supported\")\n\n @typing.override\n def visit_yield_expr(self, expr: mypy.nodes.YieldExpr) -> typing.Never:\n self._unsupported_node(expr, \"generator functions are not supported\")\n\n @typing.override\n def visit_yield_from_expr(self, o: mypy.nodes.YieldFromExpr) -> typing.Never:\n self._unsupported_node(o, \"generator functions are not supported\")\n\n # ~~~ async\/await functions unsupported ~~~ #\n @typing.override\n def visit_await_expr(self, o: mypy.nodes.AwaitExpr) -> typing.Never:\n self._unsupported_node(o, \"async\/await is not supported\")\n\n # ~~~ analysis-only expressions, should never show up ~~~ #\n @typing.override\n def visit_temp_node(self, expr: mypy.nodes.TempNode) -> _TExpression:\n # \"dummy node\"\n raise InternalError(\n \"Placeholder expression node encountered, should be handled at a higher level\",\n self._location(expr),\n )\n\n def __analysis_only(self, expr: mypy.nodes.Expression) -> typing.Never:\n raise InternalError(\n f\"Can't compile analysis-only expression of type {type(expr).__name__}\",\n self._location(expr),\n )\n\n @typing.override\n def visit_cast_expr(self, expr: mypy.nodes.CastExpr) -> _TExpression:\n # NOTE: only appears as CallExpr.analyzed\n return self.__analysis_only(expr)\n\n @typing.override\n def visit_assert_type_expr(self, expr: mypy.nodes.AssertTypeExpr) -> _TExpression:\n # NOTE: only appears as CallExpr.analyzed\n return self.__analysis_only(expr)\n\n @typing.override\n def visit_enum_call_expr(self, expr: mypy.nodes.EnumCallExpr) -> _TExpression:\n # NOTE: only appears as CallExpr.analyzed\n return self.__analysis_only(expr)\n\n @typing.override\n def visit__promote_expr(self, expr: mypy.nodes.PromoteExpr) -> _TExpression:\n # NOTE: only appears as CallExpr.analyzed\n return self.__analysis_only(expr)\n\n @typing.override\n def visit_namedtuple_expr(self, expr: mypy.nodes.NamedTupleExpr) -> _TExpression:\n # NOTE: only appears as (ClassDef|CallExpr).analyzed\n return self.__analysis_only(expr)\n\n @typing.override\n def visit_newtype_expr(self, expr: mypy.nodes.NewTypeExpr) -> _TExpression:\n # NOTE: only appears as CallExpr.analyzed\n return self.__analysis_only(expr)\n\n @typing.override\n def visit_type_alias_expr(self, expr: mypy.nodes.TypeAliasExpr) -> _TExpression:\n # NOTE: only appears as (IndexExpr|CallExpr|OpExpr).analyzed\n return self.__analysis_only(expr)\n\n @typing.override\n def visit_type_application(self, expr: mypy.nodes.TypeApplication) -> _TExpression:\n # NOTE: only appears as IndexExpr.analyzed\n return self.__analysis_only(expr)\n\n @typing.override\n def visit_type_var_expr(self, expr: mypy.nodes.TypeVarExpr) -> _TExpression:\n # NOTE: appears as CallExpr.analyzed OR as SymbolTableNode.node\n return self.__analysis_only(expr)\n\n @typing.override\n def visit_paramspec_expr(self, expr: mypy.nodes.ParamSpecExpr) -> _TExpression:\n # NOTE: only appears as CallExpr.analyzed\n return self.__analysis_only(expr)\n\n @typing.override\n def visit_type_var_tuple_expr(self, expr: mypy.nodes.TypeVarTupleExpr) -> _TExpression:\n # NOTE: only appears as CallExpr.analyzed\n return self.__analysis_only(expr)\n\n @typing.override\n def visit_typeddict_expr(self, expr: mypy.nodes.TypedDictExpr) -> _TExpression:\n # NOTE: only appears as (ClassDef|CallExpr).analyzed\n return self.__analysis_only(expr)\n\n @typing.override\n def visit_reveal_expr(self, expr: mypy.nodes.RevealExpr) -> _TExpression:\n # NOTE: only appears as CallExpr.analyzed\n return self.__analysis_only(expr)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/base_mypy_visitor.py","language":"Python","license":"NOASSERTION","size":12472} {"code":"ARC4_CONTRACT_BASE = \"algopy.arc4.ARC4Contract\"\nCONTRACT_BASE = \"algopy._contract.Contract\"\nSTRUCT_META = \"algopy._struct._StructMeta\"\nSUBROUTINE_HINT = \"algopy._hints.subroutine\"\nLOGICSIG_DECORATOR = \"algopy._logic_sig.logicsig\"\nLOGICSIG_DECORATOR_ALIAS = \"algopy.logicsig\"\nSUBROUTINE_HINT_ALIAS = \"algopy.subroutine\"\nABIMETHOD_DECORATOR = \"algopy.arc4.abimethod\"\nABIMETHOD_DECORATOR_ALIAS = ABIMETHOD_DECORATOR\nBAREMETHOD_DECORATOR = \"algopy.arc4.baremethod\"\nBAREMETHOD_DECORATOR_ALIAS = BAREMETHOD_DECORATOR\nAPPROVAL_METHOD = \"approval_program\"\nCLEAR_STATE_METHOD = \"clear_state_program\"\nALGOPY_OP_PREFIX = \"algopy.op.\"\nURANGE = \"algopy._unsigned_builtins.urange\"\nCLS_ARC4_STRUCT_META = \"algopy.arc4._StructMeta\"\nCLS_ARC4_ABI_CALL = \"algopy.arc4.abi_call\"\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/constants.py","language":"Python","license":"NOASSERTION","size":759} {"code":"import ast\nimport contextlib\nimport functools\nfrom collections.abc import Iterator, Mapping, Sequence\nfrom pathlib import Path\n\nimport attrs\nimport mypy.nodes\nimport mypy.options\nimport mypy.types\n\nfrom puya import log\nfrom puya.context import try_get_source\nfrom puya.errors import CodeError, InternalError, log_exceptions\nfrom puya.parse import SourceLocation\nfrom puya.program_refs import ContractReference\nfrom puya.utils import attrs_extend, unique\nfrom puyapy.awst_build import pytypes\nfrom puyapy.models import ConstantValue, ContractFragmentBase\nfrom puyapy.parse import ParseResult, source_location_from_mypy\n\nlogger = log.get_logger(__name__)\n\n\n@attrs.frozen(kw_only=True)\nclass ASTConversionContext:\n _parse_result: ParseResult\n constants: dict[str, ConstantValue] = attrs.field(factory=dict)\n _pytypes: dict[str, pytypes.PyType] = attrs.field(factory=pytypes.builtins_registry)\n _contract_fragments: dict[ContractReference, ContractFragmentBase] = attrs.field(factory=dict)\n\n @property\n def mypy_options(self) -> mypy.options.Options:\n return self._parse_result.mypy_options\n\n @property\n def contract_fragments(self) -> Mapping[ContractReference, ContractFragmentBase]:\n return self._contract_fragments\n\n def add_contract_fragment(self, fragment: ContractFragmentBase) -> None:\n assert (\n fragment.id not in self._contract_fragments\n ), \"attempted to add contract fragment twice\"\n self._contract_fragments[fragment.id] = fragment\n\n def for_module(self, module_path: Path) -> \"ASTConversionModuleContext\":\n return attrs_extend(ASTConversionModuleContext, self, module_path=module_path)\n\n def register_pytype(self, typ: pytypes.PyType, *, alias: str | None = None) -> None:\n name = alias or typ.name\n existing_entry = self._pytypes.get(name)\n\n if existing_entry is typ:\n logger.debug(f\"Duplicate registration of {typ}\")\n else:\n if existing_entry is not None:\n logger.error(f\"Redefinition of type {name}\")\n self._pytypes[name] = typ\n\n def lookup_pytype(self, name: str) -> pytypes.PyType | None:\n \"\"\"Lookup type by the canonical fully qualified name\"\"\"\n return self._pytypes.get(name)\n\n def require_ptype(self, name: str, source_location: SourceLocation) -> pytypes.PyType:\n try:\n return self._pytypes[name]\n except KeyError:\n raise CodeError(f\"Unknown type {name}\", source_location) from None\n\n\n@attrs.frozen(kw_only=True)\nclass ASTConversionModuleContext(ASTConversionContext):\n module_path: Path\n\n def node_location(\n self,\n node: mypy.nodes.Context,\n module_src: mypy.nodes.TypeInfo | None = None,\n ) -> SourceLocation:\n if not module_src:\n module_path = self.module_path\n else:\n module_name = module_src.module_name\n try:\n module_path = self._parse_result.ordered_modules[module_name].path\n except KeyError as ex:\n raise CodeError(f\"could not find module '{module_name}'\") from ex\n loc = source_location_from_mypy(file=module_path, node=node)\n # if not at start of file, try and expand to preceding comment lines,\n if loc.line > 1:\n prior_code = try_get_source(\n self._parse_result.sources_by_path,\n SourceLocation(file=module_path, line=1, end_line=loc.line - 1),\n )\n comment_lines_count = 0\n for line in reversed(prior_code or []):\n if not line.strip().startswith(\"#\"):\n break\n comment_lines_count += 1\n if comment_lines_count:\n loc = attrs.evolve(loc, comment_lines=comment_lines_count)\n # if multi-line, strip trailing blank\/comment lines\n if loc.end_line != loc.line:\n lines = try_get_source(self._parse_result.sources_by_path, loc)\n if lines is not None:\n chop = 0\n for line in reversed(lines):\n l_stripped = line.lstrip()\n if l_stripped and not l_stripped.startswith(\"#\"):\n break\n chop += 1\n if chop:\n loc = attrs.evolve(loc, end_line=loc.end_line - chop, end_column=None)\n return loc\n\n def _maybe_convert_location(\n self, location: mypy.nodes.Context | SourceLocation\n ) -> SourceLocation:\n if isinstance(location, mypy.nodes.Context):\n return self.node_location(location)\n return location\n\n def error(self, msg: str, location: mypy.nodes.Context | SourceLocation) -> None:\n logger.error(msg, location=self._maybe_convert_location(location))\n\n def info(self, msg: str, location: mypy.nodes.Context | SourceLocation) -> None:\n logger.info(msg, location=self._maybe_convert_location(location))\n\n def warning(self, msg: str, location: mypy.nodes.Context | SourceLocation) -> None:\n logger.warning(msg, location=self._maybe_convert_location(location))\n\n @contextlib.contextmanager\n def log_exceptions(\n self, fallback_location: mypy.nodes.Context | SourceLocation\n ) -> Iterator[None]:\n with log_exceptions(self._maybe_convert_location(fallback_location)):\n yield\n\n def type_to_pytype(\n self,\n mypy_type: mypy.types.Type,\n *,\n source_location: mypy.nodes.Context | SourceLocation,\n in_type_args: bool = False,\n ) -> pytypes.PyType:\n return type_to_pytype(\n self._pytypes,\n mypy_type,\n source_location=self._maybe_convert_location(source_location),\n in_type_args=in_type_args,\n )\n\n\ndef type_to_pytype(\n registry: Mapping[str, pytypes.PyType],\n mypy_type: mypy.types.Type,\n *,\n source_location: SourceLocation,\n in_type_args: bool = False,\n in_func_sig: bool = False,\n) -> pytypes.PyType:\n loc = source_location\n proper_type_or_alias: mypy.types.ProperType | mypy.types.TypeAliasType\n if isinstance(mypy_type, mypy.types.TypeAliasType):\n proper_type_or_alias = mypy_type\n else:\n proper_type_or_alias = mypy.types.get_proper_type(mypy_type)\n recurse = functools.partial(\n type_to_pytype,\n registry,\n source_location=loc,\n in_type_args=in_type_args,\n in_func_sig=in_func_sig,\n )\n match proper_type_or_alias:\n case mypy.types.TypeAliasType(alias=alias, args=args):\n if alias is None:\n raise InternalError(\"mypy type alias type missing alias reference\", loc)\n result = registry.get(alias.fullname)\n if result is None:\n return recurse(mypy.types.get_proper_type(proper_type_or_alias))\n return _maybe_parameterise_pytype(registry, result, args, loc)\n # this is how variadic tuples are represented in mypy types...\n case mypy.types.Instance(type=mypy.nodes.TypeInfo(fullname=\"builtins.tuple\"), args=args):\n try:\n (arg,) = args\n except ValueError:\n raise InternalError(\n f\"mypy tuple type as instance had unrecognised args: {args}\", loc\n ) from None\n if not in_func_sig:\n raise CodeError(\"variadic tuples are not supported\", loc)\n return pytypes.VariadicTupleType(items=recurse(arg))\n case mypy.types.Instance(args=args) as inst:\n fullname = inst.type.fullname\n result = registry.get(fullname)\n if result is None:\n if fullname.startswith(\"builtins.\"):\n msg = f\"Unsupported builtin type: {fullname.removeprefix('builtins.')}\"\n else:\n msg = f\"Unknown type: {fullname}\"\n raise CodeError(msg, loc)\n return _maybe_parameterise_pytype(registry, result, args, loc)\n case mypy.types.TupleType(items=items, partial_fallback=fallback):\n if not fallback.args:\n return recurse(fallback)\n generic = registry.get(fallback.type.fullname)\n if generic is None:\n raise CodeError(f\"unknown tuple base type: {fallback.type.fullname}\", loc)\n return _maybe_parameterise_pytype(registry, generic, items, loc)\n case mypy.types.LiteralType(fallback=fallback, value=literal_value) as mypy_literal_type:\n if not in_type_args:\n # this is a bit clumsy, but exists because for some reason, bool types\n # can be \"narrowed\" down to a typing.Literal. e.g. in the case of:\n # assert a\n # assert a or b\n # then the type of `a or b` becomes typing.Literal[True]\n return recurse(fallback)\n if mypy_literal_type.is_enum_literal():\n raise CodeError(\"typing literals of enum are not supported\", loc)\n our_literal_value: pytypes.TypingLiteralValue\n if fallback.type.fullname == \"builtins.bytes\": # WHY^2\n bytes_literal_value = ast.literal_eval(\"b\" + repr(literal_value))\n assert isinstance(bytes_literal_value, bytes)\n our_literal_value = bytes_literal_value\n elif isinstance(literal_value, float): # WHY\n raise CodeError(\"typing literals with float values are not supported\", loc)\n else:\n our_literal_value = literal_value\n return pytypes.TypingLiteralType(value=our_literal_value, source_location=loc)\n case mypy.types.UnionType(items=items):\n types = unique(recurse(it) for it in items)\n if not types:\n return pytypes.NeverType\n elif len(types) == 1:\n return types[0]\n else:\n return pytypes.UnionType(types, loc)\n case mypy.types.NoneType() | mypy.types.PartialType(type=None):\n return pytypes.NoneType\n case mypy.types.UninhabitedType():\n return pytypes.NeverType\n case mypy.types.AnyType(type_of_any=type_of_any):\n msg = _type_of_any_to_error_message(type_of_any, loc)\n raise CodeError(msg, loc)\n case mypy.types.TypeType(item=inner_type):\n inner_pytype = recurse(inner_type)\n return pytypes.TypeType(inner_pytype)\n case mypy.types.FunctionLike() as func_like:\n if func_like.is_type_obj():\n # note sure if this will always work for overloads, but the only overloaded\n # constructor we have is arc4.StaticArray, so...\n ret_type = func_like.items[0].ret_type\n cls_typ = recurse(ret_type)\n return pytypes.TypeType(cls_typ)\n else:\n if not isinstance(func_like, mypy.types.CallableType): # vs Overloaded\n raise CodeError(\"references to overloaded functions are not supported\", loc)\n ret_pytype = recurse(func_like.ret_type)\n func_args = []\n for at, name, kind in zip(\n func_like.arg_types, func_like.arg_names, func_like.arg_kinds, strict=True\n ):\n arg_pytype = type_to_pytype(\n registry,\n at,\n source_location=loc,\n in_type_args=in_type_args,\n in_func_sig=True,\n )\n func_args.append(pytypes.FuncArg(type=arg_pytype, kind=kind, name=name))\n if func_like.bound_args:\n logger.error(\"function type has bound arguments\", location=loc)\n if func_like.definition is not None:\n name = func_like.definition.fullname\n else:\n name = repr(func_like)\n if func_like.def_extras.get(\"first_arg\"):\n _self_arg, *func_args = func_args\n return pytypes.FuncType(\n name=name,\n args=func_args,\n ret_type=ret_pytype,\n )\n case _:\n raise CodeError(f\"Unable to resolve mypy type {mypy_type!r} to known algopy type\", loc)\n\n\ndef _maybe_parameterise_pytype(\n registry: Mapping[str, pytypes.PyType],\n maybe_generic: pytypes.PyType,\n mypy_type_args: Sequence[mypy.types.Type],\n loc: SourceLocation,\n) -> pytypes.PyType:\n if not mypy_type_args:\n return maybe_generic\n if all(isinstance(t, mypy.types.TypeVarType | mypy.types.UnpackType) for t in mypy_type_args):\n return maybe_generic\n type_args_resolved = [\n type_to_pytype(registry, mta, source_location=loc, in_type_args=True)\n for mta in mypy_type_args\n ]\n result = maybe_generic.parameterise(type_args_resolved, loc)\n return result\n\n\ndef _type_of_any_to_error_message(type_of_any: int, source_location: SourceLocation) -> str:\n from mypy.types import TypeOfAny\n\n match type_of_any:\n case TypeOfAny.unannotated:\n msg = \"type annotation is required at this location\"\n case TypeOfAny.explicit | TypeOfAny.from_another_any:\n msg = \"Any type is not supported\"\n case TypeOfAny.from_unimported_type:\n msg = \"unknown type from import\"\n case TypeOfAny.from_omitted_generics:\n msg = \"type parameters are required at this location\"\n case TypeOfAny.from_error:\n msg = \"typing error prevents type resolution\"\n case TypeOfAny.special_form:\n msg = \"unsupported type form\"\n case TypeOfAny.implementation_artifact | TypeOfAny.suggestion_engine:\n msg = \"mypy cannot handle this type form, try providing an explicit annotation\"\n case _:\n logger.debug(f\"Unknown TypeOfAny value: {type_of_any}\", location=source_location)\n msg = \"Any type is not supported\"\n return msg\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/context.py","language":"Python","license":"NOASSERTION","size":14065} {"code":"import abc\nimport contextlib\nimport typing\nfrom collections.abc import Callable, Iterator, Sequence, Set\n\nimport attrs\nimport mypy.nodes\nimport mypy.types\nimport mypy.visitor\n\nfrom puya import log\nfrom puya.avm import OnCompletionAction\nfrom puya.awst import (\n nodes as awst_nodes,\n wtypes,\n)\nfrom puya.errors import CodeError, InternalError\nfrom puya.parse import SourceLocation\nfrom puya.program_refs import ContractReference\nfrom puya.utils import StableSet, set_add, unique\nfrom puyapy.awst_build import constants, intrinsic_factory, pytypes\nfrom puyapy.awst_build.arc4_decorators import get_arc4_abimethod_data, get_arc4_baremethod_data\nfrom puyapy.awst_build.base_mypy_visitor import BaseMyPyStatementVisitor\nfrom puyapy.awst_build.context import ASTConversionModuleContext\nfrom puyapy.awst_build.subroutine import ContractMethodInfo, FunctionASTConverter\nfrom puyapy.awst_build.utils import get_decorators_by_fullname, get_subroutine_decorator_inline_arg\nfrom puyapy.models import (\n ARC4BareMethodData,\n ARC4MethodData,\n ContractClassOptions,\n ContractFragmentBase,\n ContractFragmentMethod,\n ContractFragmentStorage,\n)\n\nlogger = log.get_logger(__name__)\n\n_ContractMethodBuilder: typing.TypeAlias = Callable[\n [ASTConversionModuleContext], awst_nodes.ContractMethod\n]\n\n_INIT_METHOD = \"__init__\"\n_ARC4_CONTRACT_BASE_CREF = ContractReference(constants.ARC4_CONTRACT_BASE)\n_SYNTHETIC_LOCATION = SourceLocation(file=None, line=1)\n\n\nclass ContractASTConverter(BaseMyPyStatementVisitor[None]):\n def __init__(\n self,\n context: ASTConversionModuleContext,\n class_def: mypy.nodes.ClassDef,\n class_options: ContractClassOptions,\n typ: pytypes.ContractType,\n ):\n super().__init__(context=context)\n class_loc = self._location(class_def)\n fragment_mro = _build_resolved_mro(context, typ)\n if class_options.state_totals is None:\n base_with_defined = next(\n (b for b in fragment_mro if b.options and (b.options.state_totals is not None)),\n None,\n )\n if base_with_defined:\n logger.warning(\n f\"Contract extends base contract {base_with_defined.id} \"\n \"with explicit state_totals, but does not define its own state_totals. \"\n \"This could result in insufficient reserved state at run time.\",\n location=class_loc,\n )\n\n self.fragment: typing.Final = _ContractFragment(\n id=typ.name,\n source_location=class_loc,\n pytype=typ,\n mro=fragment_mro,\n is_abstract=_check_class_abstractness(context, class_def),\n options=class_options,\n docstring=class_def.docstring,\n )\n\n # TODO: validation for state proxies being non-conditional\n _build_symbols_and_state(context, self.fragment, class_def.info.names)\n\n self._deferred_methods = list[tuple[ContractFragmentMethod, _ContractMethodBuilder]]()\n # if the class has an __init__ method, we need to visit it first, so any storage\n # fields cane be resolved to a (static) key\n match class_def.info.names.get(_INIT_METHOD):\n case mypy.nodes.SymbolTableNode(node=mypy.nodes.Statement() as init_node):\n stmts = unique((init_node, *class_def.defs.body))\n case _:\n stmts = class_def.defs.body\n # note: we iterate directly and catch+log code errors here,\n # since each statement should be somewhat independent given\n # the constraints we place (e.g. if one function fails to convert,\n # we can still keep trying to convert other functions to produce more valid errors)\n for stmt in stmts:\n with context.log_exceptions(fallback_location=stmt):\n stmt.accept(self)\n\n if (\n self.fragment.is_arc4\n and not self.fragment.is_abstract\n and not any(self.fragment.find_arc4_method_metadata(can_create=True))\n ):\n self._insert_default_arc4_create(self.fragment)\n context.add_contract_fragment(self.fragment)\n\n @staticmethod\n def _insert_default_arc4_create(fragment: \"_ContractFragment\") -> None:\n if any(fragment.find_arc4_method_metadata(bare=True, oca=OnCompletionAction.NoOp)):\n logger.error(\n \"Non-abstract ARC4 contract has no methods that can be called\"\n \" to create the contract, but does have a NoOp bare method,\"\n \" so one couldn't be inserted.\"\n \" In order to allow creating the contract add either\"\n \" an @abimethod or @baremethod\"\n ' decorated method with create=\"require\" or create=\"allow\"',\n location=fragment.source_location,\n )\n else:\n default_create_name = \"__algopy_default_create\"\n while fragment.resolve_symbol(default_create_name): # ensure uniqueness\n default_create_name = f\"_{default_create_name}\"\n default_create_config = awst_nodes.ARC4BareMethodConfig(\n create=awst_nodes.ARC4CreateOption.require,\n source_location=_SYNTHETIC_LOCATION,\n )\n fragment.add_method(\n ContractFragmentMethod(\n member_name=default_create_name,\n source_location=_SYNTHETIC_LOCATION,\n metadata=ARC4BareMethodData(\n member_name=default_create_name,\n pytype=(\n pytypes.FuncType(\n name=\".\".join((fragment.id, default_create_name)),\n args=(),\n ret_type=pytypes.NoneType,\n )\n ),\n config=default_create_config,\n source_location=_SYNTHETIC_LOCATION,\n ),\n is_trivial=False,\n synthetic=True,\n inheritable=False,\n implementation=awst_nodes.ContractMethod(\n cref=fragment.id,\n member_name=default_create_name,\n args=[],\n return_type=wtypes.void_wtype,\n body=awst_nodes.Block(\n body=[],\n source_location=_SYNTHETIC_LOCATION,\n ),\n documentation=awst_nodes.MethodDocumentation(),\n arc4_method_config=default_create_config,\n source_location=_SYNTHETIC_LOCATION,\n inline=True,\n ),\n )\n )\n\n def build(self, context: ASTConversionModuleContext) -> awst_nodes.Contract | None:\n for method_fragment, method_builder in self._deferred_methods:\n with context.log_exceptions(fallback_location=method_fragment.source_location):\n method_fragment.implementation = method_builder(context)\n\n if self.fragment.is_abstract:\n return None\n\n approval_program = None\n approval_method = self.fragment.resolve_method(constants.APPROVAL_METHOD)\n if approval_method is None or approval_method.is_trivial:\n logger.error(\n \"non-abstract contract class missing approval program\",\n location=self.fragment.source_location,\n )\n elif approval_method.implementation is None:\n pass # error during method construction, already logged\n else:\n approval_program = approval_method.implementation\n if self.fragment.resolve_method(_INIT_METHOD) is not None:\n approval_program = _insert_init_call_on_create(\n self.fragment.id, approval_program.return_type\n )\n\n clear_method = self.fragment.resolve_method(constants.CLEAR_STATE_METHOD)\n if clear_method is None or clear_method.is_trivial:\n logger.error(\n \"non-abstract contract class missing clear-state program\",\n location=self.fragment.source_location,\n )\n clear_program = None\n else:\n clear_program = clear_method.implementation\n\n if approval_program is None or clear_program is None:\n return None\n\n return awst_nodes.Contract(\n id=self.fragment.id,\n name=self.fragment.options.name_override or self.fragment.pytype.class_name,\n method_resolution_order=[ancestor.id for ancestor in self.fragment.mro],\n approval_program=approval_program,\n clear_program=clear_program,\n methods=tuple(\n cm.implementation\n for cm in self.fragment.methods(include_overridden=True)\n if cm.implementation is not None\n ),\n app_state=tuple(\n state_decl.definition\n for state_decl in self.fragment.state()\n if state_decl.definition is not None\n ),\n description=self.fragment.docstring,\n source_location=self.fragment.source_location,\n reserved_scratch_space=self.fragment.reserved_scratch_space,\n state_totals=self.fragment.options.state_totals,\n avm_version=self.fragment.options.avm_version,\n )\n\n def empty_statement(self, _stmt: mypy.nodes.Statement) -> None:\n return None\n\n def visit_function(\n self, func_def: mypy.nodes.FuncDef, decorator: mypy.nodes.Decorator | None\n ) -> None:\n func_loc = self._location(func_def)\n method_name = func_def.name\n\n if func_def.is_class:\n raise CodeError(\"@classmethod not supported\", func_loc)\n if func_def.is_static:\n raise CodeError(\n \"@staticmethod not supported, use a module level function instead\", func_loc\n )\n if func_def.type is None:\n raise CodeError(\"function is untyped\", func_loc)\n if len(func_def.arguments) < 1:\n # since we checked we're only handling instance methods, should be at least one\n # argument to function - ie self\n logger.error(f\"{method_name} should take a self parameter\", location=func_loc)\n\n dec_by_fullname = get_decorators_by_fullname(self.context, decorator) if decorator else {}\n subroutine_dec = dec_by_fullname.pop(constants.SUBROUTINE_HINT, None)\n abimethod_dec = dec_by_fullname.pop(constants.ABIMETHOD_DECORATOR, None)\n baremethod_dec = dec_by_fullname.pop(constants.BAREMETHOD_DECORATOR, None)\n\n for unknown_dec_fullname, dec in dec_by_fullname.items():\n self._error(f'unsupported decorator \"{unknown_dec_fullname}\"', dec)\n\n # TODO: handle difference of subroutine vs abimethod and overrides???\n\n inline = None\n if subroutine_dec is not None:\n inline = get_subroutine_decorator_inline_arg(self.context, subroutine_dec)\n\n arc4_method_data: ARC4MethodData | None = None\n if method_name in (_INIT_METHOD, constants.APPROVAL_METHOD, constants.CLEAR_STATE_METHOD):\n for invalid_dec in (subroutine_dec, abimethod_dec, baremethod_dec):\n if invalid_dec is not None:\n self._error(\"method should not be decorated\", location=invalid_dec)\n elif method_name.startswith(\"__\") and method_name.endswith(\"__\"):\n raise CodeError(\n \"methods starting and ending with a double underscore\"\n ' (aka \"dunder\" methods) are reserved for the Python data model'\n \" (https:\/\/docs.python.org\/3\/reference\/datamodel.html).\"\n \" Of these methods, only __init__ is supported in contract classes\",\n func_loc,\n )\n elif not self.fragment.is_arc4:\n if subroutine_dec is None:\n logger.error(\n f\"missing @{constants.SUBROUTINE_HINT_ALIAS} decorator\", location=func_loc\n )\n for invalid_dec in (abimethod_dec, baremethod_dec):\n if invalid_dec is not None:\n self._error(\n f\"decorator is only valid in subclasses of {pytypes.ARC4ContractBaseType}\",\n invalid_dec,\n )\n else:\n if len(list(filter(None, (subroutine_dec, abimethod_dec, baremethod_dec)))) != 1:\n logger.error(\n f\"ARC-4 contract member functions\"\n f\" (other than __init__ or approval \/ clear program methods)\"\n f\" must be annotated with exactly one of\"\n f\" @{constants.SUBROUTINE_HINT_ALIAS},\"\n f\" @{constants.ABIMETHOD_DECORATOR_ALIAS},\"\n f\" or @{constants.BAREMETHOD_DECORATOR_ALIAS}\",\n location=func_loc,\n )\n\n if abimethod_dec:\n arc4_method_data = get_arc4_abimethod_data(self.context, abimethod_dec, func_def)\n elif baremethod_dec:\n arc4_method_data = get_arc4_baremethod_data(self.context, baremethod_dec, func_def)\n else:\n arc4_method_data = None\n # TODO: validate against super-class configs??\n\n source_location = self._location(decorator or func_def)\n obj = ContractFragmentMethod(\n member_name=method_name,\n source_location=source_location,\n metadata=arc4_method_data,\n is_trivial=func_def.is_trivial_body,\n synthetic=False,\n inheritable=True,\n implementation=None,\n )\n self.fragment.add_method(obj)\n if obj.is_trivial:\n logger.debug(f\"skipping trivial method {method_name}\", location=func_loc)\n else:\n self._deferred_methods.append(\n (\n obj,\n lambda ctx: FunctionASTConverter.convert(\n ctx,\n func_def=func_def,\n source_location=source_location,\n inline=inline,\n contract_method_info=ContractMethodInfo(\n fragment=self.fragment,\n contract_type=self.fragment.pytype,\n arc4_method_config=(\n arc4_method_data.config if arc4_method_data else None\n ),\n is_abstract=self.fragment.is_abstract,\n ),\n ),\n )\n )\n\n def visit_block(self, o: mypy.nodes.Block) -> None:\n raise InternalError(\"shouldn't get here\", self._location(o))\n\n def visit_return_stmt(self, stmt: mypy.nodes.ReturnStmt) -> None:\n self._error(\"illegal Python syntax, return in class body\", location=stmt)\n\n def visit_class_def(self, cdef: mypy.nodes.ClassDef) -> None:\n self._error(\"nested classes are not supported\", location=cdef)\n\n def _unsupported_stmt(self, kind: str, stmt: mypy.nodes.Statement) -> None:\n self._error(f\"{kind} statements are not supported in the class body\", location=stmt)\n\n def visit_assignment_stmt(self, stmt: mypy.nodes.AssignmentStmt) -> None:\n # just pass on state forward-declarations, these will be picked up by gather state\n # everything else (ie any _actual_ assignments) is unsupported\n if not isinstance(stmt.rvalue, mypy.nodes.TempNode):\n self._unsupported_stmt(\"assignment\", stmt)\n\n def visit_operator_assignment_stmt(self, stmt: mypy.nodes.OperatorAssignmentStmt) -> None:\n self._unsupported_stmt(\"operator assignment\", stmt)\n\n def visit_expression_stmt(self, stmt: mypy.nodes.ExpressionStmt) -> None:\n if isinstance(stmt.expr, mypy.nodes.StrExpr):\n # ignore class docstring, already extracted\n # TODO: should we capture field \"docstrings\"?\n pass\n else:\n self._unsupported_stmt(\"expression statement\", stmt)\n\n def visit_if_stmt(self, stmt: mypy.nodes.IfStmt) -> None:\n self._unsupported_stmt(\"if\", stmt)\n\n def visit_while_stmt(self, stmt: mypy.nodes.WhileStmt) -> None:\n self._unsupported_stmt(\"while\", stmt)\n\n def visit_for_stmt(self, stmt: mypy.nodes.ForStmt) -> None:\n self._unsupported_stmt(\"for\", stmt)\n\n def visit_break_stmt(self, stmt: mypy.nodes.BreakStmt) -> None:\n self._unsupported_stmt(\"break\", stmt)\n\n def visit_continue_stmt(self, stmt: mypy.nodes.ContinueStmt) -> None:\n self._unsupported_stmt(\"continue\", stmt)\n\n def visit_assert_stmt(self, stmt: mypy.nodes.AssertStmt) -> None:\n self._unsupported_stmt(\"assert\", stmt)\n\n def visit_del_stmt(self, stmt: mypy.nodes.DelStmt) -> None:\n self._unsupported_stmt(\"del\", stmt)\n\n def visit_match_stmt(self, stmt: mypy.nodes.MatchStmt) -> None:\n self._unsupported_stmt(\"match\", stmt)\n\n def visit_type_alias_stmt(self, stmt: mypy.nodes.TypeAliasStmt) -> None:\n self._unsupported_stmt(\"type\", stmt)\n\n\nclass _UserContractBase(ContractFragmentBase, abc.ABC):\n @property\n @abc.abstractmethod\n def options(self) -> ContractClassOptions | None: ...\n\n\n@attrs.frozen\nclass _StaticContractBase(_UserContractBase):\n id: ContractReference\n methods_: dict[str, ContractFragmentMethod]\n mro: Sequence[ContractFragmentBase]\n symbols: dict[str, pytypes.PyType]\n options: None = None\n\n @typing.override\n def resolve_method(\n self, name: str, *, include_inherited: bool = True\n ) -> ContractFragmentMethod | None:\n return self.methods_.get(name)\n\n @typing.override\n def methods(\n self, *, include_inherited: bool = True, include_overridden: bool = False\n ) -> Iterator[ContractFragmentMethod]:\n yield from self.methods_.values()\n\n @typing.override\n def resolve_storage(\n self, name: str, *, include_inherited: bool = True\n ) -> ContractFragmentStorage | None:\n return None\n\n @typing.override\n def state(self, *, include_inherited: bool = True) -> Iterator[ContractFragmentStorage]:\n yield from ()\n\n\n@attrs.frozen(kw_only=True)\nclass _ContractFragment(_UserContractBase):\n id: ContractReference\n source_location: SourceLocation\n pytype: pytypes.ContractType\n mro: Sequence[_UserContractBase]\n is_abstract: bool\n options: ContractClassOptions\n docstring: str | None\n _methods: dict[str, ContractFragmentMethod] = attrs.field(factory=dict, init=False)\n _state_defs: dict[str, ContractFragmentStorage] = attrs.field(factory=dict, init=False)\n symbols: dict[str, pytypes.PyType | None] = attrs.field(factory=dict, init=False)\n\n @property\n def is_arc4(self) -> bool:\n return pytypes.ARC4ContractBaseType in self.pytype.mro\n\n def add_method(self, method: ContractFragmentMethod) -> None:\n set_result = self._methods.setdefault(method.member_name, method)\n if set_result is not method:\n logger.info(\n f\"previous definition of {method.member_name} was here\",\n location=set_result.source_location,\n )\n logger.error(\n f\"redefinition of {method.member_name}\",\n location=method.source_location,\n )\n\n @typing.override\n def resolve_method(\n self, name: str, *, include_inherited: bool = True\n ) -> ContractFragmentMethod | None:\n with contextlib.suppress(KeyError):\n return self._methods[name]\n if include_inherited:\n for fragment in self.mro:\n method = fragment.resolve_method(name, include_inherited=False)\n if method and method.inheritable:\n return method\n return None\n\n @typing.override\n def methods(\n self, *, include_inherited: bool = True, include_overridden: bool = False\n ) -> Iterator[ContractFragmentMethod]:\n yield from self._methods.values()\n if include_inherited:\n seen_names = set(self._methods.keys())\n for fragment in self.mro:\n for method in fragment.methods(include_inherited=False):\n if method.inheritable and (\n include_overridden or set_add(seen_names, method.member_name)\n ):\n yield method\n\n @typing.override\n def resolve_storage(\n self, name: str, *, include_inherited: bool = True\n ) -> ContractFragmentStorage | None:\n with contextlib.suppress(KeyError):\n return self._state_defs[name]\n if include_inherited:\n for fragment in self.mro:\n result = fragment.resolve_storage(name, include_inherited=False)\n if result is not None:\n return result\n return None\n\n def add_state(self, decl: ContractFragmentStorage) -> None:\n existing = self.resolve_storage(decl.member_name)\n self._state_defs.setdefault(decl.member_name, decl)\n if existing is not None:\n logger.info(\n f\"previous definition of {decl.member_name} was here\",\n location=existing.source_location,\n )\n logger.error(\n f\"redefinition of {decl.member_name}\",\n location=decl.source_location,\n )\n\n @typing.override\n def state(self, *, include_inherited: bool = True) -> Iterator[ContractFragmentStorage]:\n result = self._state_defs\n if include_inherited:\n for ancestor in self.mro:\n result = {\n s.member_name: s for s in ancestor.state(include_inherited=False)\n } | result\n yield from result.values()\n\n @property\n def reserved_scratch_space(self) -> Set[int]:\n return StableSet[int].from_iter(\n num\n for c in (self, *self.mro)\n if c.options and c.options.scratch_slot_reservations\n for num in c.options.scratch_slot_reservations\n )\n\n\ndef _insert_init_call_on_create(\n current_contract: ContractReference, return_type: wtypes.WType\n) -> awst_nodes.ContractMethod:\n call_init = awst_nodes.Block(\n comment=\"call __init__\",\n body=[\n awst_nodes.ExpressionStatement(\n expr=awst_nodes.SubroutineCallExpression(\n target=awst_nodes.InstanceMethodTarget(member_name=_INIT_METHOD),\n args=[],\n wtype=wtypes.void_wtype,\n source_location=_SYNTHETIC_LOCATION,\n )\n )\n ],\n source_location=_SYNTHETIC_LOCATION,\n )\n call_init_on_create = awst_nodes.IfElse(\n condition=awst_nodes.Not(\n expr=intrinsic_factory.txn(\"ApplicationID\", wtypes.bool_wtype, _SYNTHETIC_LOCATION),\n source_location=_SYNTHETIC_LOCATION,\n ),\n if_branch=call_init,\n else_branch=None,\n source_location=_SYNTHETIC_LOCATION,\n )\n return awst_nodes.ContractMethod(\n cref=current_contract,\n member_name=\"__algopy_entrypoint_with_init\",\n args=[],\n arc4_method_config=None,\n return_type=return_type,\n documentation=awst_nodes.MethodDocumentation(),\n body=awst_nodes.Block(\n body=[\n call_init_on_create,\n awst_nodes.ReturnStatement(\n value=awst_nodes.SubroutineCallExpression(\n target=awst_nodes.InstanceMethodTarget(\n member_name=constants.APPROVAL_METHOD,\n ),\n args=[],\n wtype=return_type,\n source_location=_SYNTHETIC_LOCATION,\n ),\n source_location=_SYNTHETIC_LOCATION,\n ),\n ],\n source_location=_SYNTHETIC_LOCATION,\n ),\n source_location=_SYNTHETIC_LOCATION,\n )\n\n\ndef _build_resolved_mro(\n context: ASTConversionModuleContext, contract_type: pytypes.ContractType\n) -> list[_UserContractBase]:\n class_def_loc = contract_type.source_location\n contract_bases_mro = list[_UserContractBase]()\n for ancestor in contract_type.mro:\n if ancestor == pytypes.ContractBaseType:\n pass\n elif ancestor == pytypes.ARC4ContractBaseType:\n contract_bases_mro.append(_arc4_contract_fragment())\n elif isinstance(ancestor, pytypes.ContractType):\n ancestor_fragment = context.contract_fragments.get(ancestor.name)\n if isinstance(ancestor_fragment, _ContractFragment):\n contract_bases_mro.append(ancestor_fragment)\n else:\n raise CodeError(\n f\"contract type has non-contract base {ancestor.name}\", class_def_loc\n )\n else:\n raise CodeError(f\"base class {ancestor} is not a contract subclass\", class_def_loc)\n return contract_bases_mro\n\n\ndef _arc4_contract_fragment() -> _UserContractBase:\n result = _StaticContractBase(id=_ARC4_CONTRACT_BASE_CREF, mro=(), methods_={}, symbols={})\n\n def add_program_method(\n name: str,\n body: Sequence[awst_nodes.Statement],\n *,\n return_type: pytypes.RuntimeType = pytypes.BoolType,\n ) -> None:\n result.symbols[name] = pytypes.FuncType(\n name=\".\".join((_ARC4_CONTRACT_BASE_CREF, name)),\n args=(),\n ret_type=return_type,\n )\n implementation = awst_nodes.ContractMethod(\n cref=_ARC4_CONTRACT_BASE_CREF,\n member_name=name,\n source_location=_SYNTHETIC_LOCATION,\n args=[],\n arc4_method_config=None,\n return_type=return_type.wtype,\n documentation=awst_nodes.MethodDocumentation(),\n body=awst_nodes.Block(body=body, source_location=_SYNTHETIC_LOCATION),\n inline=None,\n )\n result.methods_[name] = ContractFragmentMethod(\n member_name=name,\n source_location=_SYNTHETIC_LOCATION,\n metadata=None,\n is_trivial=False,\n synthetic=True,\n inheritable=True,\n implementation=implementation,\n )\n\n add_program_method(\n name=constants.APPROVAL_METHOD,\n body=[\n awst_nodes.ReturnStatement(\n value=awst_nodes.ARC4Router(source_location=_SYNTHETIC_LOCATION),\n source_location=_SYNTHETIC_LOCATION,\n )\n ],\n )\n add_program_method(\n name=constants.CLEAR_STATE_METHOD,\n body=[\n awst_nodes.ReturnStatement(\n value=awst_nodes.BoolConstant(value=True, source_location=_SYNTHETIC_LOCATION),\n source_location=_SYNTHETIC_LOCATION,\n )\n ],\n )\n\n return result\n\n\ndef _build_symbols_and_state(\n context: ASTConversionModuleContext,\n fragment: _ContractFragment,\n symtable: mypy.nodes.SymbolTable,\n) -> None:\n cref = fragment.id\n for name, sym in symtable.items():\n node = sym.node\n assert node, f\"mypy cross reference remains unresolved: member {name!r} of {cref!r}\"\n node_loc = context.node_location(node)\n if isinstance(node, mypy.nodes.OverloadedFuncDef):\n node = node.impl\n if isinstance(node, mypy.nodes.Decorator):\n # we don't support any decorators that would change signature\n node = node.func\n pytyp = None\n if isinstance(node, mypy.nodes.Var | mypy.nodes.FuncDef) and node.type:\n with contextlib.suppress(CodeError):\n pytyp = context.type_to_pytype(node.type, source_location=node_loc)\n\n fragment.symbols[name] = pytyp\n if pytyp and not isinstance(pytyp, pytypes.FuncType):\n definition = None\n if isinstance(pytyp, pytypes.StorageProxyType):\n wtypes.validate_persistable(pytyp.content_wtype, node_loc)\n match pytyp.generic:\n case pytypes.GenericLocalStateType:\n kind = awst_nodes.AppStorageKind.account_local\n case pytypes.GenericGlobalStateType:\n kind = awst_nodes.AppStorageKind.app_global\n case pytypes.GenericBoxType:\n kind = awst_nodes.AppStorageKind.box\n case None if pytyp == pytypes.BoxRefType:\n kind = awst_nodes.AppStorageKind.box\n case _:\n raise InternalError(f\"unhandled StorageProxyType: {pytyp}\", node_loc)\n elif isinstance(pytyp, pytypes.StorageMapProxyType):\n wtypes.validate_persistable(pytyp.key_wtype, node_loc)\n wtypes.validate_persistable(pytyp.content_wtype, node_loc)\n if pytyp.generic != pytypes.GenericBoxMapType:\n raise InternalError(f\"unhandled StorageMapProxyType: {pytyp}\", node_loc)\n kind = awst_nodes.AppStorageKind.box\n else: # global state, direct\n wtype = pytyp.checked_wtype(node_loc)\n wtypes.validate_persistable(wtype, node_loc)\n key = awst_nodes.BytesConstant(\n value=name.encode(\"utf8\"),\n encoding=awst_nodes.BytesEncoding.utf8,\n source_location=node_loc,\n wtype=wtypes.state_key,\n )\n kind = awst_nodes.AppStorageKind.app_global\n definition = awst_nodes.AppStorageDefinition(\n source_location=node_loc,\n member_name=name,\n kind=kind,\n storage_wtype=wtype,\n key_wtype=None,\n key=key,\n description=None,\n )\n fragment.add_state(\n ContractFragmentStorage(\n member_name=name,\n kind=kind,\n definition=definition,\n source_location=node_loc,\n )\n )\n\n\ndef _check_class_abstractness(\n context: ASTConversionModuleContext, class_def: mypy.nodes.ClassDef\n) -> bool:\n is_abstract = class_def.info.is_abstract\n # note: we don't support the metaclass= option, so we only need to check for\n # inheritance of abc.ABC and not metaclass=abc.ABCMeta\n if is_abstract and not any(\n base.fullname == \"abc.ABC\" for base in class_def.info.direct_base_classes()\n ):\n context.warning(f\"Class {class_def.fullname} is implicitly abstract\", class_def)\n return is_abstract\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/contract.py","language":"Python","license":"NOASSERTION","size":30981} {"code":"","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"import abc\nimport typing\n\nimport typing_extensions\n\nfrom puya import log\nfrom puya.awst.nodes import (\n BinaryBooleanOperator,\n CompileTimeConstantExpression,\n Expression,\n Lvalue,\n SingleEvaluation,\n Statement,\n TupleExpression,\n VarExpression,\n)\nfrom puya.errors import CodeError, InternalError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import (\n BuilderBinaryOp,\n BuilderComparisonOp,\n BuilderUnaryOp,\n CallableBuilder,\n InstanceBuilder,\n NodeBuilder,\n TypeBuilder,\n)\n\n__all__ = [\n \"FunctionBuilder\",\n \"GenericTypeBuilder\",\n \"InstanceExpressionBuilder\",\n \"NotIterableInstanceExpressionBuilder\",\n]\n\n_TPyType_co = typing_extensions.TypeVar(\n \"_TPyType_co\", bound=pytypes.PyType, default=pytypes.PyType, covariant=True\n)\n_TExpression_co = typing_extensions.TypeVar(\n \"_TExpression_co\", bound=Expression, default=Expression, covariant=True\n)\n\nlogger = log.get_logger(__name__)\n\n\nclass FunctionBuilder(CallableBuilder, abc.ABC):\n @property\n @typing.final\n def pytype(self) -> None: # TODO: give function type\n return None\n\n @typing.override\n @typing.final\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n from puyapy.awst_build.eb._utils import constant_bool_and_error\n\n return constant_bool_and_error(value=True, location=location, negate=negate)\n\n @typing.override\n @typing.final\n def member_access(self, name: str, location: SourceLocation) -> typing.Never:\n raise CodeError(\"function attribute access is not supported\", location)\n\n\nclass GenericTypeBuilder(CallableBuilder, abc.ABC): # TODO: can we fold this with TypeBuilder?\n @typing.override\n @property\n def pytype(self) -> None: # TODO, take this as an init argument\n return None\n\n @typing.override\n @typing.final\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n raise CodeError(\"generic type requires parameters\", location)\n\n @typing.override\n @typing.final\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n from puyapy.awst_build.eb._utils import constant_bool_and_error\n\n return constant_bool_and_error(value=True, location=location, negate=negate)\n\n\nclass InstanceExpressionBuilder(\n InstanceBuilder[_TPyType_co], typing.Generic[_TPyType_co, _TExpression_co], abc.ABC\n):\n def __init__(self, pytype: _TPyType_co, expr: _TExpression_co):\n super().__init__(expr.source_location)\n if expr.wtype != pytype.wtype:\n raise InternalError(\n f\"invalid expression wtype {str(expr.wtype)!r} for Python type {str(pytype)!r}\",\n expr.source_location,\n )\n self._pytype = pytype\n self.__expr = expr\n\n @typing.override\n @typing.final\n @property\n def pytype(self) -> _TPyType_co:\n return self._pytype\n\n @typing.override\n def resolve_literal(self, converter: TypeBuilder) -> InstanceBuilder:\n return self.try_resolve_literal(converter)\n\n @typing.override\n def try_resolve_literal(self, converter: TypeBuilder) -> InstanceBuilder:\n return self\n\n @typing.override\n @typing.final\n def resolve_lvalue(self) -> Lvalue:\n resolved = self.resolve()\n return _validate_lvalue(self._pytype, resolved)\n\n @typing.override\n def resolve(self) -> _TExpression_co:\n return self.__expr\n\n @typing.override\n def delete(self, location: SourceLocation) -> Statement:\n from puyapy.awst_build.eb._utils import dummy_statement\n\n logger.error(f\"{self.pytype} is not valid as del target\", location=location)\n return dummy_statement(location)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n raise CodeError(f\"unrecognised member of {self.pytype}: {name}\", location)\n\n @typing.override\n def unary_op(self, op: BuilderUnaryOp, location: SourceLocation) -> InstanceBuilder:\n raise CodeError(f\"{self.pytype} does not support unary {op.value!r} operator\", location)\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n return NotImplemented\n\n @typing.override\n def binary_op(\n self,\n other: InstanceBuilder,\n op: BuilderBinaryOp,\n location: SourceLocation,\n *,\n reverse: bool,\n ) -> InstanceBuilder:\n return NotImplemented\n\n @typing.override\n def bool_binary_op(\n self, other: InstanceBuilder, op: BinaryBooleanOperator, location: SourceLocation\n ) -> InstanceBuilder:\n return super().bool_binary_op(other, op, location)\n\n @typing.override\n def augmented_assignment(\n self, op: BuilderBinaryOp, rhs: InstanceBuilder, location: SourceLocation\n ) -> Statement:\n from puyapy.awst_build.eb._utils import dummy_statement\n\n logger.error(f\"{self.pytype} does not support augmented assignment\", location=location)\n return dummy_statement(location)\n\n @typing.override\n def single_eval(self) -> InstanceBuilder:\n if not isinstance(\n self.__expr, VarExpression | CompileTimeConstantExpression | SingleEvaluation\n ):\n return builder_for_instance(self.pytype, SingleEvaluation(self.__expr))\n return self\n\n\nclass NotIterableInstanceExpressionBuilder(InstanceExpressionBuilder[_TPyType_co], abc.ABC):\n @typing.final\n @typing.override\n def contains(self, item: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n return super().contains(item, location)\n\n @typing.final\n @typing.override\n def iterate(self) -> Expression:\n return super().iterate()\n\n @typing.final\n @typing.override\n def iterable_item_type(self) -> pytypes.PyType:\n return super().iterable_item_type()\n\n @typing.final\n @typing.override\n def index(self, index: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n return super().index(index, location)\n\n @typing.final\n @typing.override\n def slice_index(\n self,\n begin_index: InstanceBuilder | None,\n end_index: InstanceBuilder | None,\n stride: InstanceBuilder | None,\n location: SourceLocation,\n ) -> InstanceBuilder:\n return super().slice_index(begin_index, end_index, stride, location)\n\n\ndef _validate_lvalue(typ: pytypes.PyType, resolved: Expression) -> Lvalue:\n if typ == pytypes.NoneType:\n raise CodeError(\n \"None indicates an empty return and cannot be assigned\",\n resolved.source_location,\n )\n if not isinstance(resolved, Lvalue):\n raise CodeError(\n \"expression is not valid as an assignment target\", resolved.source_location\n )\n if isinstance(resolved, TupleExpression):\n assert isinstance(typ, pytypes.TupleLikeType)\n for item_typ, item in zip(typ.items, resolved.items, strict=True):\n _validate_lvalue(item_typ, item)\n return resolved\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/_base.py","language":"Python","license":"NOASSERTION","size":7260} {"code":"import abc\nimport typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\nimport typing_extensions\n\nfrom puya.awst.nodes import Expression, ReinterpretCast\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder, InstanceExpressionBuilder\nfrom puyapy.awst_build.eb._utils import cast_to_bytes\nfrom puyapy.awst_build.eb.bytes import BytesExpressionBuilder\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import InstanceBuilder, NodeBuilder, TypeBuilder\n\n_TPyType_co = typing_extensions.TypeVar(\n \"_TPyType_co\", bound=pytypes.PyType, default=pytypes.PyType, covariant=True\n)\n\n\nclass BytesBackedTypeBuilder(TypeBuilder[_TPyType_co], abc.ABC):\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n typ = self.produces()\n match name:\n case \"from_bytes\":\n return _FromBytes(typ, location)\n case _:\n return super().member_access(name, location)\n\n\nclass _FromBytes(FunctionBuilder):\n def __init__(self, result_type: pytypes.PyType, location: SourceLocation):\n super().__init__(location)\n self.result_type = result_type\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.exactly_one_arg_of_type_else_dummy(\n args, pytypes.BytesType, location, resolve_literal=True\n )\n result_expr = ReinterpretCast(\n expr=arg.resolve(),\n wtype=self.result_type.checked_wtype(location),\n source_location=location,\n )\n return builder_for_instance(self.result_type, result_expr)\n\n\nclass BytesBackedInstanceExpressionBuilder(InstanceExpressionBuilder[_TPyType_co], abc.ABC):\n _bytes_member: typing.ClassVar[str]\n\n def __init_subclass__(cls, *, bytes_member: str = \"bytes\", **kwargs: object):\n super().__init_subclass__(**kwargs)\n cls._bytes_member = bytes_member\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n if name == self._bytes_member:\n return self.bytes(location)\n else:\n return super().member_access(name, location)\n\n def bytes(self, location: SourceLocation) -> BytesExpressionBuilder:\n return BytesExpressionBuilder(self.to_bytes(location))\n\n @typing.override\n def to_bytes(self, location: SourceLocation) -> Expression:\n return cast_to_bytes(self.resolve(), location)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/_bytes_backed.py","language":"Python","license":"NOASSERTION","size":2775} {"code":"import typing\nfrom collections.abc import Callable, Sequence\nfrom itertools import zip_longest\n\nfrom puya import log\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb._utils import dummy_value\nfrom puyapy.awst_build.eb.interface import InstanceBuilder, NodeBuilder\nfrom puyapy.awst_build.utils import maybe_resolve_literal\n\n_T = typing.TypeVar(\"_T\")\n_TBuilder = typing.TypeVar(\"_TBuilder\", bound=NodeBuilder)\n\nlogger = log.get_logger(__name__)\n\n\ndef at_most_one_arg(\n args: Sequence[NodeBuilder], location: SourceLocation\n) -> InstanceBuilder | None:\n if not args:\n return None\n first, *rest = args\n if rest:\n logger.error(f\"expected at most 1 argument, got {len(args)}\", location=location)\n return instance_builder(first, default=default_none)\n\n\ndef at_most_one_arg_of_type(\n args: Sequence[NodeBuilder], valid_types: Sequence[pytypes.PyType], location: SourceLocation\n) -> InstanceBuilder | None:\n if not args:\n return None\n first, *rest = args\n if rest:\n logger.error(f\"expected at most 1 argument, got {len(args)}\", location=location)\n if isinstance(first, InstanceBuilder) and first.pytype.is_type_or_subtype(*valid_types):\n return first\n return not_this_type(first, default=default_none)\n\n\ndef default_raise(msg: str, location: SourceLocation) -> typing.Never:\n from puya.errors import CodeError\n\n raise CodeError(msg, location)\n\n\ndef default_fixed_value(value: _T) -> Callable[[str, SourceLocation], _T]:\n def defaulter(msg: str, location: SourceLocation) -> _T: # noqa: ARG001\n return value\n\n return defaulter\n\n\ndefault_none: typing.Final = default_fixed_value(None)\n\n\ndef default_dummy_value(\n pytype: pytypes.PyType,\n) -> Callable[[str, SourceLocation], InstanceBuilder]:\n def defaulter(msg: str, location: SourceLocation) -> InstanceBuilder: # noqa: ARG001\n return dummy_value(pytype, location)\n\n return defaulter\n\n\ndef not_this_type(node: NodeBuilder, default: Callable[[str, SourceLocation], _T]) -> _T:\n \"\"\"Provide consistent error messages for unexpected types.\"\"\"\n if isinstance(node.pytype, pytypes.UnionType):\n msg = \"type unions are unsupported at this location\"\n else:\n msg = \"unexpected argument type\"\n result = default(msg, node.source_location)\n logger.error(msg, location=node.source_location)\n return result\n\n\ndef at_least_one_arg(\n args: Sequence[_TBuilder],\n location: SourceLocation,\n *,\n default: Callable[[str, SourceLocation], _T],\n) -> tuple[InstanceBuilder | _T, Sequence[_TBuilder]]:\n if not args:\n msg = \"expected at least 1 argument, got 0\"\n result = default(msg, location)\n logger.error(msg, location=location)\n return result, []\n first, *rest = args\n return instance_builder(first, default=default), rest\n\n\ndef exactly_one_arg(\n args: Sequence[NodeBuilder],\n location: SourceLocation,\n *,\n default: Callable[[str, SourceLocation], _T],\n) -> InstanceBuilder | _T:\n if not args:\n msg = \"expected 1 argument, got 0\"\n result = default(msg, location)\n logger.error(msg, location=location)\n return result\n first, *rest = args\n if rest:\n logger.error(f\"expected 1 argument, got {len(args)}\", location=location)\n return instance_builder(first, default=default)\n\n\ndef exactly_one_arg_of_type(\n args: Sequence[NodeBuilder],\n expected: pytypes.PyType,\n location: SourceLocation,\n *,\n default: Callable[[str, SourceLocation], _T],\n resolve_literal: bool = False,\n) -> InstanceBuilder | _T:\n if not args:\n msg = \"expected 1 argument, got 0\"\n result = default(msg, location)\n logger.error(msg, location=location)\n return result\n first, *rest = args\n if rest:\n logger.error(f\"expected 1 argument, got {len(args)}\", location=location)\n if resolve_literal:\n first = maybe_resolve_literal(first, expected)\n if isinstance(first, InstanceBuilder) and expected <= first.pytype:\n return first\n return not_this_type(first, default=default)\n\n\ndef exactly_one_arg_of_type_else_dummy(\n args: Sequence[NodeBuilder],\n pytype: pytypes.PyType,\n location: SourceLocation,\n *,\n resolve_literal: bool = False,\n) -> InstanceBuilder:\n return exactly_one_arg_of_type(\n args,\n pytype,\n location,\n default=default_dummy_value(pytype),\n resolve_literal=resolve_literal,\n )\n\n\ndef no_args(args: Sequence[NodeBuilder], location: SourceLocation) -> None:\n if args:\n logger.error(f\"expected 0 arguments, got {len(args)}\", location=location)\n\n\ndef exactly_n_args_of_type_else_dummy(\n args: Sequence[NodeBuilder], pytype: pytypes.PyType, location: SourceLocation, num_args: int\n) -> Sequence[InstanceBuilder]:\n if not exactly_n_args(args, location, num_args):\n dummy_args = [dummy_value(pytype, location)] * num_args\n args = [arg or default for arg, default in zip_longest(args, dummy_args)]\n arg_ebs = [argument_of_type_else_dummy(arg, pytype) for arg in args]\n return arg_ebs[:num_args]\n\n\ndef exactly_n_args(args: Sequence[NodeBuilder], location: SourceLocation, num_args: int) -> bool:\n if len(args) == num_args:\n return True\n logger.error(\n f\"expected {num_args} argument{'' if num_args == 1 else 's'}, got {len(args)}\",\n location=location,\n )\n return False\n\n\ndef argument_of_type(\n builder: NodeBuilder,\n target_type: pytypes.PyType,\n *additional_types: pytypes.PyType,\n resolve_literal: bool = False,\n default: Callable[[str, SourceLocation], _T],\n) -> InstanceBuilder | _T:\n if resolve_literal:\n builder = maybe_resolve_literal(builder, target_type)\n\n if isinstance(builder, InstanceBuilder) and builder.pytype.is_type_or_subtype(\n target_type, *additional_types\n ):\n return builder\n return not_this_type(builder, default=default)\n\n\ndef argument_of_type_else_dummy(\n builder: NodeBuilder,\n target_type: pytypes.PyType,\n *additional_types: pytypes.PyType,\n resolve_literal: bool = False,\n) -> InstanceBuilder:\n return argument_of_type(\n builder,\n target_type,\n *additional_types,\n resolve_literal=resolve_literal,\n default=default_dummy_value(target_type),\n )\n\n\ndef simple_string_literal(\n builder: NodeBuilder,\n *,\n default: Callable[[str, SourceLocation], _T],\n) -> str | _T:\n from puyapy.awst_build.eb.interface import LiteralBuilder\n\n match builder:\n case LiteralBuilder(value=str(value)):\n return value\n case InstanceBuilder(pytype=pytypes.StrLiteralType):\n msg = \"argument must be a simple str literal\"\n result = default(msg, builder.source_location)\n logger.error(msg, location=builder.source_location)\n return result\n case other:\n return not_this_type(other, default=default)\n\n\ndef instance_builder(\n builder: NodeBuilder, *, default: Callable[[str, SourceLocation], _T]\n) -> InstanceBuilder | _T:\n if isinstance(builder, InstanceBuilder):\n return builder\n msg = \"expression is not a value\"\n result = default(msg, builder.source_location)\n logger.error(msg, location=builder.source_location)\n return result\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/_expect.py","language":"Python","license":"NOASSERTION","size":7348} {"code":"import typing\n\nfrom puya import log\nfrom puya.awst.nodes import (\n BinaryBooleanOperator,\n BoolConstant,\n BytesConstant,\n BytesEncoding,\n Expression,\n Lvalue,\n Statement,\n)\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import intrinsic_factory, pytypes\nfrom puyapy.awst_build.eb.interface import (\n BuilderBinaryOp,\n BuilderComparisonOp,\n BuilderUnaryOp,\n InstanceBuilder,\n LiteralBuilder,\n TypeBuilder,\n)\nfrom puyapy.awst_build.utils import fold_binary_expr, fold_unary_expr\nfrom puyapy.models import ConstantValue\n\nlogger = log.get_logger(__name__)\n\n\nclass LiteralBuilderImpl(LiteralBuilder):\n def __init__(self, value: ConstantValue, source_location: SourceLocation):\n super().__init__(source_location)\n self._value = value\n match value:\n case bool():\n typ: pytypes.PyType = pytypes.BoolType\n case int():\n typ = pytypes.IntLiteralType\n case str():\n typ = pytypes.StrLiteralType\n case bytes():\n typ = pytypes.BytesLiteralType\n case _:\n typing.assert_never(value)\n self._pytype = typ\n\n @property\n def value(self) -> ConstantValue:\n return self._value\n\n @property\n @typing.override\n def pytype(self) -> pytypes.PyType:\n return self._pytype\n\n @typing.override\n def resolve(self) -> Expression:\n if isinstance(self.value, bool):\n return BoolConstant(value=self.value, source_location=self.source_location)\n raise CodeError(\"a Python literal is not valid at this location\", self.source_location)\n\n @typing.override\n def resolve_literal(self, converter: TypeBuilder) -> InstanceBuilder:\n return converter.convert_literal(literal=self, location=converter.source_location)\n\n @typing.override\n def try_resolve_literal(self, converter: TypeBuilder) -> InstanceBuilder | None:\n return converter.try_convert_literal(literal=self, location=converter.source_location)\n\n @typing.override\n def resolve_lvalue(self) -> Lvalue:\n raise CodeError(\"cannot assign to literal\", self.source_location)\n\n @typing.override\n def to_bytes(self, location: SourceLocation) -> Expression:\n match self.value:\n case str(str_value):\n return BytesConstant(\n value=str_value.encode(), encoding=BytesEncoding.utf8, source_location=location\n )\n case bytes(bytes_value):\n return BytesConstant(\n value=bytes_value, encoding=BytesEncoding.unknown, source_location=location\n )\n case bool():\n return intrinsic_factory.itob(self.resolve(), location)\n raise CodeError(f\"cannot serialize literal of type {self.pytype}\", location)\n\n @typing.override\n def delete(self, location: SourceLocation) -> Statement:\n raise CodeError(\"cannot delete literal\", location)\n\n @typing.override\n def unary_op(self, op: BuilderUnaryOp, location: SourceLocation) -> LiteralBuilder:\n folded = fold_unary_expr(location, op.value, self.value)\n return LiteralBuilderImpl(value=folded, source_location=location)\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> LiteralBuilder:\n if not isinstance(other, LiteralBuilder):\n return NotImplemented\n folded = fold_binary_expr(location, op.value, self.value, other.value)\n return LiteralBuilderImpl(value=folded, source_location=location)\n\n @typing.override\n def binary_op(\n self,\n other: InstanceBuilder,\n op: BuilderBinaryOp,\n location: SourceLocation,\n *,\n reverse: bool,\n ) -> LiteralBuilder:\n if not isinstance(other, LiteralBuilder):\n return NotImplemented\n lhs, rhs = self.value, other.value\n if reverse:\n lhs, rhs = rhs, lhs\n folded = fold_binary_expr(location, op.value, lhs, rhs)\n return LiteralBuilderImpl(value=folded, source_location=location)\n\n @typing.override\n def bool_binary_op(\n self, other: InstanceBuilder, op: BinaryBooleanOperator, location: SourceLocation\n ) -> InstanceBuilder:\n if not isinstance(other, LiteralBuilder):\n return super().bool_binary_op(other, op, location)\n folded = fold_binary_expr(location, op.value, self.value, other.value)\n return LiteralBuilderImpl(value=folded, source_location=location)\n\n @typing.override\n def augmented_assignment(\n self, op: BuilderBinaryOp, rhs: InstanceBuilder, location: SourceLocation\n ) -> Statement:\n raise CodeError(\"cannot assign to literal\", location)\n\n @typing.override\n def contains(self, item: InstanceBuilder, location: SourceLocation) -> LiteralBuilder:\n if not isinstance(item, LiteralBuilder):\n raise CodeError(\"cannot perform containment check with non-constant value\", location)\n try:\n folded = item.value in self.value # type: ignore[operator]\n except Exception as ex:\n raise CodeError(str(ex), location) from ex\n return LiteralBuilderImpl(value=folded, source_location=location)\n\n @typing.override\n def iterate(self) -> typing.Never:\n raise CodeError(\"cannot iterate literal\")\n\n @typing.override\n def iterable_item_type(self) -> typing.Never:\n self.iterate()\n\n @typing.override\n def index(self, index: InstanceBuilder, location: SourceLocation) -> LiteralBuilder:\n if not isinstance(index, LiteralBuilder):\n raise CodeError(\"cannot index literal with non-constant value\", location)\n try:\n folded = self.value[index.value] # type: ignore[index]\n except Exception as ex:\n raise CodeError(str(ex), location) from ex\n return LiteralBuilderImpl(value=folded, source_location=location)\n\n @typing.override\n def slice_index(\n self,\n begin_index: InstanceBuilder | None,\n end_index: InstanceBuilder | None,\n stride: InstanceBuilder | None,\n location: SourceLocation,\n ) -> LiteralBuilder:\n def _constant_slice_arg(index: InstanceBuilder | None) -> ConstantValue | None:\n if index is None:\n return None\n if not isinstance(index, LiteralBuilder):\n raise CodeError(\"cannot slice literal with non-constant value\", location)\n return index.value\n\n begin = _constant_slice_arg(begin_index)\n end = _constant_slice_arg(end_index)\n stride_ = _constant_slice_arg(stride)\n try:\n folded = self.value[begin:end:stride_] # type: ignore[index,misc]\n except Exception as ex:\n raise CodeError(str(ex), location) from ex\n return LiteralBuilderImpl(value=folded, source_location=location)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> LiteralBuilder:\n # TODO: support stuff like int.from_bytes etc\n raise CodeError(\"unsupported member access from literal\", location)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n if isinstance(self.value, bool):\n value = self.value\n warn = False\n else:\n value = bool(self.value)\n warn = True\n if negate:\n value = not value\n if warn:\n logger.warning(f\"expression is always {value}\", location=location)\n return LiteralBuilderImpl(value=value, source_location=location)\n\n @typing.override\n def single_eval(self) -> InstanceBuilder:\n return self\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/_literals.py","language":"Python","license":"NOASSERTION","size":7840} {"code":"import functools\nfrom collections.abc import Callable\n\nfrom puya.awst.nodes import Expression\nfrom puya.errors import CodeError, InternalError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import constants, intrinsic_data, pytypes\nfrom puyapy.awst_build.eb import (\n arc4,\n array,\n biguint,\n bool as bool_,\n bytes as bytes_,\n compiled,\n ensure_budget,\n intrinsics,\n log,\n none,\n storage,\n string,\n struct,\n template_variables,\n transaction,\n tuple as tuple_,\n uint64,\n uint64_enums,\n unsigned_builtins,\n)\nfrom puyapy.awst_build.eb.interface import CallableBuilder, InstanceBuilder\nfrom puyapy.awst_build.eb.reference_types import account, application, asset\n\n__all__ = [\n \"builder_for_instance\",\n \"builder_for_type\",\n]\n\nCallableBuilderFromSourceFactory = Callable[[SourceLocation], CallableBuilder]\n\nFUNC_NAME_TO_BUILDER: dict[str, CallableBuilderFromSourceFactory] = {\n \"algopy.arc4.arc4_signature\": intrinsics.Arc4SignatureBuilder,\n \"algopy._util.ensure_budget\": ensure_budget.EnsureBudgetBuilder,\n \"algopy._util.log\": log.LogBuilder,\n \"algopy.arc4.emit\": arc4.EmitBuilder,\n \"algopy.itxn.submit_txns\": transaction.SubmitInnerTransactionExpressionBuilder,\n \"algopy._compiled.compile_contract\": compiled.CompileContractFunctionBuilder,\n \"algopy._compiled.compile_logicsig\": compiled.CompileLogicSigFunctionBuilder,\n \"algopy.arc4.arc4_create\": arc4.ARC4CreateFunctionBuilder,\n \"algopy.arc4.arc4_update\": arc4.ARC4UpdateFunctionBuilder,\n constants.CLS_ARC4_ABI_CALL: arc4.ABICallGenericTypeBuilder,\n \"algopy._template_variables.TemplateVar\": (\n template_variables.GenericTemplateVariableExpressionBuilder\n ),\n **{\n (fullname := \"\".join((constants.ALGOPY_OP_PREFIX, name))): functools.partial(\n intrinsics.IntrinsicFunctionExpressionBuilder, fullname, mappings\n )\n for name, mappings in intrinsic_data.FUNC_TO_AST_MAPPER.items()\n },\n}\n\nPYTYPE_TO_TYPE_BUILDER: dict[pytypes.PyType, CallableBuilderFromSourceFactory] = {\n pytypes.NoneType: none.NoneTypeBuilder,\n pytypes.BoolType: bool_.BoolTypeBuilder,\n pytypes.GenericTupleType: tuple_.GenericTupleTypeBuilder,\n pytypes.reversedGenericType: unsigned_builtins.ReversedFunctionExpressionBuilder,\n pytypes.urangeType: unsigned_builtins.UnsignedRangeBuilder,\n pytypes.uenumerateGenericType: unsigned_builtins.UnsignedEnumerateBuilder,\n pytypes.OpUpFeeSourceType: uint64_enums.OpUpFeeSourceTypeBuilder,\n pytypes.GenericBoxType: storage.BoxGenericTypeExpressionBuilder,\n pytypes.BoxRefType: storage.BoxRefTypeBuilder,\n pytypes.GenericBoxMapType: storage.BoxMapGenericTypeExpressionBuilder,\n pytypes.GenericLocalStateType: storage.LocalStateGenericTypeBuilder,\n pytypes.GenericGlobalStateType: storage.GlobalStateGenericTypeBuilder,\n pytypes.ARC4AddressType: arc4.AddressTypeBuilder,\n pytypes.ARC4BoolType: arc4.ARC4BoolTypeBuilder,\n pytypes.ARC4ByteType: functools.partial(arc4.UIntNTypeBuilder, pytypes.ARC4ByteType),\n pytypes.GenericARC4DynamicArrayType: arc4.DynamicArrayGenericTypeBuilder,\n pytypes.GenericARC4StaticArrayType: arc4.StaticArrayGenericTypeBuilder,\n pytypes.ARC4StringType: arc4.ARC4StringTypeBuilder,\n pytypes.GenericARC4TupleType: arc4.ARC4TupleGenericTypeBuilder,\n pytypes.ARC4DynamicBytesType: arc4.DynamicBytesTypeBuilder,\n pytypes.AccountType: account.AccountTypeBuilder,\n pytypes.GenericArrayType: array.ArrayGenericTypeBuilder,\n pytypes.AssetType: asset.AssetTypeBuilder,\n pytypes.ApplicationType: application.ApplicationTypeBuilder,\n pytypes.BigUIntType: biguint.BigUIntTypeBuilder,\n pytypes.BytesType: bytes_.BytesTypeBuilder,\n pytypes.StringType: string.StringTypeBuilder,\n pytypes.UInt64Type: uint64.UInt64TypeBuilder,\n pytypes.TransactionTypeType: uint64_enums.TransactionTypeTypeBuilder,\n pytypes.OnCompleteActionType: uint64_enums.OnCompletionActionTypeBuilder,\n **{\n op_enum_typ: functools.partial(intrinsics.IntrinsicEnumTypeBuilder, op_enum_typ)\n for op_enum_typ in pytypes.OpEnumTypes\n },\n **{\n op_namespace_typ: functools.partial(\n intrinsics.IntrinsicNamespaceTypeBuilder, op_namespace_typ\n )\n for op_namespace_typ in pytypes.OpNamespaceTypes\n },\n **{\n gtxn_pytyp: functools.partial(transaction.GroupTransactionTypeBuilder, gtxn_pytyp)\n for gtxn_pytyp in (\n pytypes.GroupTransactionBaseType,\n *pytypes.GroupTransactionTypes.values(),\n )\n },\n **{\n itxn_fieldset_pytyp: functools.partial(\n transaction.InnerTxnParamsTypeBuilder, itxn_fieldset_pytyp\n )\n for itxn_fieldset_pytyp in pytypes.InnerTransactionFieldsetTypes.values()\n },\n **{\n itxn_result_pytyp: functools.partial(\n transaction.InnerTransactionTypeBuilder, itxn_result_pytyp\n )\n for itxn_result_pytyp in pytypes.InnerTransactionResultTypes.values()\n },\n}\n\nCallableBuilderFromPyTypeAndSourceFactory = Callable[\n [pytypes.PyType, SourceLocation], CallableBuilder\n]\n\nPYTYPE_GENERIC_TO_TYPE_BUILDER: dict[\n pytypes.PyType | None, CallableBuilderFromPyTypeAndSourceFactory\n] = {\n pytypes.uenumerateGenericType: (\n # TODO: fixme, should accept type\n lambda _, loc: unsigned_builtins.UnsignedEnumerateBuilder(loc)\n ),\n pytypes.reversedGenericType: (\n # TODO: fixme, should accept type\n lambda _, loc: unsigned_builtins.ReversedFunctionExpressionBuilder(loc)\n ),\n pytypes.GenericTemplateVarType: template_variables.TemplateVariableExpressionBuilder,\n pytypes.GenericABICallWithReturnType: arc4.ABICallTypeBuilder,\n pytypes.GenericLocalStateType: storage.LocalStateTypeBuilder,\n pytypes.GenericGlobalStateType: storage.GlobalStateTypeBuilder,\n pytypes.GenericBoxType: storage.BoxTypeBuilder,\n pytypes.GenericBoxMapType: storage.BoxMapTypeBuilder,\n pytypes.GenericARC4TupleType: arc4.ARC4TupleTypeBuilder,\n pytypes.GenericTupleType: tuple_.TupleTypeBuilder,\n pytypes.GenericArrayType: array.ArrayTypeBuilder,\n pytypes.GenericARC4UFixedNxMType: arc4.UFixedNxMTypeBuilder,\n pytypes.GenericARC4BigUFixedNxMType: arc4.UFixedNxMTypeBuilder,\n pytypes.GenericARC4UIntNType: arc4.UIntNTypeBuilder,\n pytypes.GenericARC4BigUIntNType: arc4.UIntNTypeBuilder,\n pytypes.GenericARC4DynamicArrayType: arc4.DynamicArrayTypeBuilder,\n pytypes.GenericARC4StaticArrayType: arc4.StaticArrayTypeBuilder,\n}\n\nPYTYPE_BASE_TO_TYPE_BUILDER: dict[pytypes.PyType, CallableBuilderFromPyTypeAndSourceFactory] = {\n pytypes.ARC4StructBaseType: arc4.ARC4StructTypeBuilder,\n pytypes.StructBaseType: struct.StructSubclassExpressionBuilder,\n pytypes.NamedTupleBaseType: tuple_.NamedTupleTypeBuilder,\n}\n\nPYTYPE_TO_BUILDER: dict[pytypes.PyType, Callable[[Expression], InstanceBuilder]] = {\n pytypes.ARC4BoolType: arc4.ARC4BoolExpressionBuilder,\n pytypes.ARC4StringType: arc4.ARC4StringExpressionBuilder,\n pytypes.ARC4DynamicBytesType: arc4.DynamicBytesExpressionBuilder,\n pytypes.ARC4ByteType: functools.partial(arc4.UIntNExpressionBuilder, typ=pytypes.ARC4ByteType),\n pytypes.ARC4AddressType: arc4.AddressExpressionBuilder,\n pytypes.AccountType: account.AccountExpressionBuilder,\n pytypes.ApplicationType: application.ApplicationExpressionBuilder,\n pytypes.AssetType: asset.AssetExpressionBuilder,\n pytypes.BigUIntType: biguint.BigUIntExpressionBuilder,\n pytypes.BoolType: bool_.BoolExpressionBuilder,\n pytypes.BytesType: bytes_.BytesExpressionBuilder,\n pytypes.CompiledContractType: compiled.CompiledContractExpressionBuilder,\n pytypes.CompiledLogicSigType: compiled.CompiledLogicSigExpressionBuilder,\n pytypes.StringType: string.StringExpressionBuilder,\n pytypes.UInt64Type: uint64.UInt64ExpressionBuilder,\n pytypes.NoneType: none.NoneExpressionBuilder,\n pytypes.NeverType: none.NoneExpressionBuilder, # we treat Never as None\/void synonym for now\n pytypes.BoxRefType: storage.BoxRefProxyExpressionBuilder,\n # bound\n **{\n uint64_enum_typ: functools.partial(\n uint64.UInt64ExpressionBuilder, enum_type=uint64_enum_typ\n )\n for uint64_enum_typ in (\n pytypes.OpUpFeeSourceType,\n pytypes.TransactionTypeType,\n pytypes.OnCompleteActionType,\n )\n },\n **{\n gtxn_pytyp: functools.partial(\n transaction.GroupTransactionExpressionBuilder, typ=gtxn_pytyp\n )\n for gtxn_pytyp in (\n pytypes.GroupTransactionBaseType,\n *pytypes.GroupTransactionTypes.values(),\n )\n },\n **{\n itxn_fieldset_pytyp: functools.partial(\n transaction.InnerTxnParamsExpressionBuilder, itxn_fieldset_pytyp\n )\n for itxn_fieldset_pytyp in pytypes.InnerTransactionFieldsetTypes.values()\n },\n **{\n itxn_result_pytyp: functools.partial(\n transaction.InnerTransactionExpressionBuilder, typ=itxn_result_pytyp\n )\n for itxn_result_pytyp in pytypes.InnerTransactionResultTypes.values()\n },\n}\n\nInstanceBuilderFromExpressionAndPyTypeFactory = Callable[\n [Expression, pytypes.PyType], InstanceBuilder\n]\n\nPYTYPE_GENERIC_TO_BUILDER: dict[\n pytypes.PyType | None, InstanceBuilderFromExpressionAndPyTypeFactory\n] = {\n pytypes.GenericTupleType: tuple_.TupleExpressionBuilder,\n pytypes.GenericBoxType: storage.BoxProxyExpressionBuilder,\n pytypes.GenericBoxMapType: storage.BoxMapProxyExpressionBuilder,\n pytypes.GenericArrayType: array.ArrayExpressionBuilder,\n pytypes.GenericARC4DynamicArrayType: arc4.DynamicArrayExpressionBuilder,\n pytypes.GenericARC4StaticArrayType: arc4.StaticArrayExpressionBuilder,\n pytypes.GenericARC4TupleType: arc4.ARC4TupleExpressionBuilder,\n pytypes.GenericARC4UFixedNxMType: arc4.UFixedNxMExpressionBuilder,\n pytypes.GenericARC4BigUFixedNxMType: arc4.UFixedNxMExpressionBuilder,\n pytypes.GenericARC4UIntNType: arc4.UIntNExpressionBuilder,\n pytypes.GenericARC4BigUIntNType: arc4.UIntNExpressionBuilder,\n pytypes.GenericGlobalStateType: storage.GlobalStateExpressionBuilder,\n pytypes.GenericLocalStateType: storage.LocalStateExpressionBuilder,\n}\n\nPYTYPE_BASE_TO_BUILDER: dict[pytypes.PyType, InstanceBuilderFromExpressionAndPyTypeFactory] = {\n pytypes.ARC4StructBaseType: arc4.ARC4StructExpressionBuilder,\n pytypes.StructBaseType: struct.StructExpressionBuilder,\n pytypes.NamedTupleBaseType: tuple_.TupleExpressionBuilder,\n}\n\n\ndef builder_for_instance(pytyp: pytypes.PyType, expr: Expression) -> InstanceBuilder:\n if eb := PYTYPE_TO_BUILDER.get(pytyp):\n return eb(expr)\n if eb_param_generic := PYTYPE_GENERIC_TO_BUILDER.get(pytyp.generic):\n return eb_param_generic(expr, pytyp)\n for base in pytyp.mro:\n if eb_base := PYTYPE_BASE_TO_BUILDER.get(base):\n return eb_base(expr, pytyp)\n if isinstance(pytyp, pytypes.UnionType):\n raise CodeError(\"type unions are unsupported at this location\", expr.source_location)\n raise InternalError(f\"no builder for instance: {pytyp}\", expr.source_location)\n\n\ndef builder_for_type(pytyp: pytypes.PyType, expr_loc: SourceLocation) -> CallableBuilder:\n if tb := PYTYPE_TO_TYPE_BUILDER.get(pytyp):\n return tb(expr_loc)\n if tb_param_generic := PYTYPE_GENERIC_TO_TYPE_BUILDER.get(pytyp.generic):\n return tb_param_generic(pytyp, expr_loc)\n for base in pytyp.mro:\n if tb_base := PYTYPE_BASE_TO_TYPE_BUILDER.get(base):\n return tb_base(pytyp, expr_loc)\n if isinstance(pytyp, pytypes.UnionType):\n raise CodeError(\"type unions are unsupported at this location\", expr_loc)\n raise InternalError(f\"no builder for type: {pytyp}\", expr_loc)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/_type_registry.py","language":"Python","license":"NOASSERTION","size":11785} {"code":"from puya import log\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import (\n BytesComparisonExpression,\n EqualityComparison,\n Expression,\n ExpressionStatement,\n ReinterpretCast,\n Statement,\n VarExpression,\n)\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import (\n BuilderBinaryOp,\n BuilderComparisonOp,\n BuilderUnaryOp,\n InstanceBuilder,\n LiteralBuilder,\n)\n\nlogger = log.get_logger(__name__)\n\n\ndef dummy_value(pytype: pytypes.PyType, location: SourceLocation) -> InstanceBuilder:\n if isinstance(pytype, pytypes.LiteralOnlyType):\n from puyapy.awst_build.eb._literals import LiteralBuilderImpl\n\n return LiteralBuilderImpl(pytype.python_type(), location)\n expr = VarExpression(name=\"\", wtype=pytype.checked_wtype(location), source_location=location)\n return builder_for_instance(pytype, expr)\n\n\ndef dummy_statement(location: SourceLocation) -> Statement:\n return ExpressionStatement(\n VarExpression(\n name=\"\",\n wtype=wtypes.void_wtype,\n source_location=location,\n )\n )\n\n\ndef resolve_negative_literal_index(\n index: InstanceBuilder, length: InstanceBuilder, location: SourceLocation\n) -> InstanceBuilder:\n match index:\n case LiteralBuilder(value=int(int_index)) if int_index < 0:\n return length.binary_op(\n index.unary_op(BuilderUnaryOp.negative, location),\n BuilderBinaryOp.sub,\n location,\n reverse=False,\n )\n case _:\n from puyapy.awst_build.eb.uint64 import UInt64TypeBuilder\n\n return index.resolve_literal(UInt64TypeBuilder(index.source_location))\n\n\ndef constant_bool_and_error(\n *, value: bool, location: SourceLocation, negate: bool = False\n) -> InstanceBuilder:\n \"\"\"\n Returns a constant bool instance builder for the specified value and negate combination.\n\n Always emits an error as either allowing the expression would result in a semantic\n compatability issue, or indicates the user has most likely made a mistake\n \"\"\"\n from puyapy.awst_build.eb._literals import LiteralBuilderImpl\n\n if negate:\n value = not value\n logger.error(f\"expression is always {value}\", location=location)\n return LiteralBuilderImpl(value=value, source_location=location)\n\n\ndef compare_bytes(\n *,\n self: InstanceBuilder,\n op: BuilderComparisonOp,\n other: InstanceBuilder,\n source_location: SourceLocation,\n) -> InstanceBuilder:\n # defer to most derived type if not equal\n if not (other.pytype <= self.pytype):\n return NotImplemented\n return _compare_expr_bytes_unchecked(self.resolve(), op, other.resolve(), source_location)\n\n\ndef compare_expr_bytes(\n *,\n lhs: Expression,\n op: BuilderComparisonOp,\n rhs: Expression,\n source_location: SourceLocation,\n) -> InstanceBuilder:\n if rhs.wtype != lhs.wtype:\n return NotImplemented\n return _compare_expr_bytes_unchecked(lhs, op, rhs, source_location)\n\n\ndef _compare_expr_bytes_unchecked(\n lhs: Expression,\n op: BuilderComparisonOp,\n rhs: Expression,\n location: SourceLocation,\n) -> InstanceBuilder:\n from puyapy.awst_build.eb.bool import BoolExpressionBuilder\n\n try:\n eq_op = EqualityComparison(op.value)\n except ValueError:\n return NotImplemented\n cmp_expr = BytesComparisonExpression(\n lhs=lhs,\n operator=eq_op,\n rhs=rhs,\n source_location=location,\n )\n return BoolExpressionBuilder(cmp_expr)\n\n\ndef cast_to_bytes(expr: Expression, location: SourceLocation | None = None) -> ReinterpretCast:\n return ReinterpretCast(\n expr=expr, wtype=wtypes.bytes_wtype, source_location=location or expr.source_location\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/_utils.py","language":"Python","license":"NOASSERTION","size":3879} {"code":"# ruff: noqa: F403\nfrom puyapy.awst_build.eb.arc4.abi_call import *\nfrom puyapy.awst_build.eb.arc4.address import *\nfrom puyapy.awst_build.eb.arc4.bool import *\nfrom puyapy.awst_build.eb.arc4.dynamic_array import *\nfrom puyapy.awst_build.eb.arc4.dynamic_bytes import *\nfrom puyapy.awst_build.eb.arc4.emit import *\nfrom puyapy.awst_build.eb.arc4.static_array import *\nfrom puyapy.awst_build.eb.arc4.string import *\nfrom puyapy.awst_build.eb.arc4.struct import *\nfrom puyapy.awst_build.eb.arc4.tuple import *\nfrom puyapy.awst_build.eb.arc4.ufixed import *\nfrom puyapy.awst_build.eb.arc4.uint import *\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/arc4\/__init__.py","language":"Python","license":"NOASSERTION","size":599} {"code":"import abc\nimport typing\nfrom abc import ABC\nfrom collections.abc import Sequence\n\nimport mypy.nodes\nimport typing_extensions\n\nfrom puya import log\nfrom puya.awst.nodes import (\n BytesConstant,\n BytesEncoding,\n CheckedMaybe,\n Copy,\n Expression,\n IndexExpression,\n)\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import intrinsic_factory, pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder\nfrom puyapy.awst_build.eb._bytes_backed import (\n BytesBackedInstanceExpressionBuilder,\n BytesBackedTypeBuilder,\n)\nfrom puyapy.awst_build.eb._utils import (\n compare_bytes,\n compare_expr_bytes,\n dummy_value,\n resolve_negative_literal_index,\n)\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import BuilderComparisonOp, InstanceBuilder, NodeBuilder\n\nlogger = log.get_logger(__name__)\n\n\n_TPyType_co = typing_extensions.TypeVar(\n \"_TPyType_co\", bound=pytypes.PyType, default=pytypes.PyType, covariant=True\n)\n\n\nclass ARC4TypeBuilder(BytesBackedTypeBuilder[_TPyType_co], abc.ABC):\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n match name:\n case \"from_log\":\n return ARC4FromLogBuilder(location, self.produces())\n case _:\n return super().member_access(name, location)\n\n\nclass ARC4FromLogBuilder(FunctionBuilder):\n def __init__(self, location: SourceLocation, typ: pytypes.PyType):\n super().__init__(location=location)\n self.typ = typ\n\n @classmethod\n def abi_expr_from_log(\n cls, typ: pytypes.PyType, value: InstanceBuilder, location: SourceLocation\n ) -> Expression:\n tmp_value = value.single_eval().resolve()\n arc4_value = intrinsic_factory.extract(\n tmp_value, start=4, loc=location, result_type=typ.checked_wtype(location)\n )\n arc4_prefix = intrinsic_factory.extract(tmp_value, start=0, length=4, loc=location)\n arc4_prefix_is_valid = compare_expr_bytes(\n lhs=arc4_prefix,\n rhs=BytesConstant(\n value=b\"\\x15\\x1f\\x7c\\x75\",\n source_location=location,\n encoding=BytesEncoding.base16,\n ),\n op=BuilderComparisonOp.eq,\n source_location=location,\n )\n return CheckedMaybe.from_tuple_items(\n expr=arc4_value,\n check=arc4_prefix_is_valid.resolve(),\n source_location=location,\n comment=\"ARC4 prefix is valid\",\n )\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.exactly_one_arg_of_type_else_dummy(args, pytypes.BytesType, location)\n result_expr = self.abi_expr_from_log(self.typ, arg, location)\n return builder_for_instance(self.typ, result_expr)\n\n\nclass CopyBuilder(FunctionBuilder):\n def __init__(self, expr: Expression, location: SourceLocation, typ: pytypes.PyType):\n super().__init__(location)\n self._typ = typ\n self.expr = expr\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n expect.no_args(args, location)\n expr_result = Copy(value=self.expr, source_location=location)\n return builder_for_instance(self._typ, expr_result)\n\n\ndef arc4_bool_bytes(\n builder: InstanceBuilder, false_bytes: bytes, location: SourceLocation, *, negate: bool\n) -> InstanceBuilder:\n lhs = builder.resolve()\n false_value = BytesConstant(\n value=false_bytes,\n encoding=BytesEncoding.base16,\n wtype=lhs.wtype,\n source_location=location,\n )\n return compare_expr_bytes(\n op=BuilderComparisonOp.eq if negate else BuilderComparisonOp.ne,\n lhs=lhs,\n rhs=false_value,\n source_location=location,\n )\n\n\nclass _ARC4ArrayExpressionBuilder(BytesBackedInstanceExpressionBuilder[pytypes.ArrayType], ABC):\n @typing.override\n def iterate(self) -> Expression:\n if not self.pytype.items_wtype.immutable:\n # this case is an error raised during AWST validation\n # adding a front end specific message here to compliment the error message\n # raise across all front ends\n logger.info(\n \"use `algopy.urange(.length)` to iterate by index\",\n location=self.source_location,\n )\n return self.resolve()\n\n @typing.override\n def iterable_item_type(self) -> pytypes.PyType:\n return self.pytype.items\n\n @typing.override\n def index(self, index: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n array_length = self.length(index.source_location)\n index = resolve_negative_literal_index(index, array_length, location)\n result_expr = IndexExpression(\n base=self.resolve(),\n index=index.resolve(),\n wtype=self.pytype.items_wtype,\n source_location=location,\n )\n return builder_for_instance(self.pytype.items, result_expr)\n\n @abc.abstractmethod\n def length(self, location: SourceLocation) -> InstanceBuilder: ...\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n match name:\n case \"length\":\n return self.length(location)\n case \"copy\":\n return CopyBuilder(self.resolve(), location, self.pytype)\n case _:\n return super().member_access(name, location)\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n return compare_bytes(self=self, op=op, other=other, source_location=location)\n\n @typing.override\n @typing.final\n def contains(self, item: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n logger.error(\n \"item containment with ARC4 arrays is currently unsupported\", location=location\n )\n return dummy_value(pytypes.BoolType, location)\n\n @typing.override\n @typing.final\n def slice_index(\n self,\n begin_index: InstanceBuilder | None,\n end_index: InstanceBuilder | None,\n stride: InstanceBuilder | None,\n location: SourceLocation,\n ) -> InstanceBuilder:\n raise CodeError(\"slicing ARC4 arrays is currently unsupported\", location)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/arc4\/_base.py","language":"Python","license":"NOASSERTION","size":6780} {"code":"import re\nimport typing\nfrom collections.abc import Sequence\n\nimport attrs\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.errors import CodeError, InternalError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import arc4_utils, pytypes\nfrom puyapy.awst_build.arc4_utils import pytype_to_arc4_pytype, split_tuple_types\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._utils import dummy_value\nfrom puyapy.awst_build.eb.factories import builder_for_type\nfrom puyapy.awst_build.eb.interface import (\n InstanceBuilder,\n NodeBuilder,\n StaticSizedCollectionBuilder,\n)\nfrom puyapy.awst_build.utils import maybe_resolve_literal\n\nlogger = log.get_logger(__name__)\n\n_VALID_NAME_PATTERN = re.compile(\"^[_A-Za-z][A-Za-z0-9_]*$\")\n\n\ndef _pytype_to_arc4_pytype(typ: pytypes.PyType, sig: attrs.AttrsInstance) -> pytypes.PyType:\n assert isinstance(sig, ARC4Signature)\n\n def on_error(bad_type: pytypes.PyType) -> typing.Never:\n raise CodeError(f\"invalid return type for an ARC4 method: {bad_type}\", sig.source_location)\n\n return arc4_utils.pytype_to_arc4_pytype(typ, on_error)\n\n\ndef _pytypes_to_arc4_pytypes(\n types: Sequence[pytypes.PyType], sig: attrs.AttrsInstance\n) -> Sequence[pytypes.PyType]:\n return tuple(_pytype_to_arc4_pytype(t, sig) for t in types)\n\n\n@attrs.frozen(kw_only=True)\nclass ARC4Signature:\n source_location: SourceLocation | None\n method_name: str\n arg_types: Sequence[pytypes.PyType] = attrs.field(\n converter=attrs.Converter(_pytypes_to_arc4_pytypes, takes_self=True) # type: ignore[misc]\n )\n return_type: pytypes.PyType = attrs.field(\n converter=attrs.Converter(_pytype_to_arc4_pytype, takes_self=True) # type: ignore[misc]\n )\n\n @property\n def method_selector(self) -> str:\n args = \",\".join(map(arc4_utils.pytype_to_arc4, self.arg_types))\n return_type = arc4_utils.pytype_to_arc4(self.return_type)\n return f\"{self.method_name}({args}){return_type}\"\n\n def convert_args(\n self,\n native_args: Sequence[NodeBuilder],\n *,\n expect_itxn_args: bool = False,\n ) -> Sequence[InstanceBuilder]:\n num_args = len(native_args)\n num_sig_args = len(self.arg_types)\n if num_sig_args != num_args:\n logger.error(\n f\"expected {num_sig_args} ABI argument{'' if num_sig_args == 1 else 's'},\"\n f\" got {num_args}\",\n location=self.source_location,\n )\n arg_types = (\n list(map(_gtxn_to_itxn, self.arg_types)) if expect_itxn_args else self.arg_types\n )\n arc4_args = [\n _implicit_arc4_conversion(arg, pt)\n for arg, pt in zip(native_args, arg_types, strict=False)\n ]\n return arc4_args\n\n\ndef _gtxn_to_itxn(pytype: pytypes.PyType) -> pytypes.PyType:\n if isinstance(pytype, pytypes.GroupTransactionType):\n return pytypes.InnerTransactionFieldsetTypes[pytype.transaction_type]\n return pytype\n\n\ndef get_arc4_signature(\n method: NodeBuilder, native_args: Sequence[NodeBuilder], loc: SourceLocation\n) -> tuple[str, ARC4Signature]:\n method_sig = expect.simple_string_literal(method, default=expect.default_raise)\n method_name, maybe_args, maybe_returns = _split_signature(method_sig, method.source_location)\n if maybe_args is None:\n arg_types = [\n _implicit_arc4_type_conversion(\n expect.instance_builder(na, default=expect.default_raise).pytype, loc\n )\n for na in native_args\n ]\n elif maybe_args:\n arg_types = [arc4_utils.arc4_to_pytype(a, loc) for a in split_tuple_types(maybe_args)]\n else: # args are specified but empty\n arg_types = []\n return_type = (\n arc4_utils.arc4_to_pytype(maybe_returns, loc) if maybe_returns else pytypes.NoneType\n )\n return method_sig, ARC4Signature(\n method_name=method_name, arg_types=arg_types, return_type=return_type, source_location=loc\n )\n\n\ndef _implicit_arc4_type_conversion(typ: pytypes.PyType, loc: SourceLocation) -> pytypes.PyType:\n match typ:\n case pytypes.StrLiteralType:\n return pytypes.ARC4StringType\n case pytypes.BytesLiteralType:\n return pytypes.ARC4DynamicBytesType\n case pytypes.IntLiteralType:\n return pytypes.ARC4UIntN_Aliases[64]\n # convert an inner txn type to the equivalent group txn type\n case pytypes.InnerTransactionFieldsetType(transaction_type=txn_type):\n return pytypes.GroupTransactionTypes[txn_type]\n\n def on_error(invalid_pytype: pytypes.PyType) -> typing.Never:\n raise CodeError(\n f\"{invalid_pytype} is not an ARC4 type and no implicit ARC4 conversion possible\", loc\n )\n\n return pytype_to_arc4_pytype(typ, on_error)\n\n\ndef _inner_transaction_type_matches(instance: pytypes.PyType, target: pytypes.PyType) -> bool:\n if not isinstance(instance, pytypes.InnerTransactionFieldsetType):\n return False\n if not isinstance(target, pytypes.InnerTransactionFieldsetType):\n return False\n return (\n instance.transaction_type == target.transaction_type\n or instance.transaction_type is None\n or target.transaction_type is None\n )\n\n\ndef _implicit_arc4_conversion(\n operand: NodeBuilder, target_type: pytypes.PyType\n) -> InstanceBuilder:\n from puya.awst.wtypes import ARC4Type\n\n instance = expect.instance_builder(operand, default=expect.default_dummy_value(target_type))\n instance = _maybe_resolve_arc4_literal(instance, target_type)\n if target_type <= instance.pytype:\n return instance\n target_wtype = target_type.wtype\n if isinstance(target_type, pytypes.TransactionRelatedType):\n if _inner_transaction_type_matches(instance.pytype, target_type):\n return instance\n else:\n logger.error(\n f\"expected type {target_type}, got type {instance.pytype}\",\n location=instance.source_location,\n )\n return dummy_value(target_type, instance.source_location)\n if not isinstance(target_wtype, ARC4Type):\n raise InternalError(\n \"implicit_operand_conversion expected target_type to be an ARC-4 type,\"\n f\" got {target_type}\",\n instance.source_location,\n )\n if isinstance(instance.pytype.wtype, ARC4Type):\n logger.error(\n f\"expected type {target_type}, got type {instance.pytype}\",\n location=instance.source_location,\n )\n return dummy_value(target_type, instance.source_location)\n if not target_wtype.can_encode_type(instance.pytype.checked_wtype(instance.source_location)):\n logger.error(\n f\"cannot encode {instance.pytype} to {target_type}\", location=instance.source_location\n )\n return dummy_value(target_type, instance.source_location)\n if (\n isinstance(target_type, pytypes.StructType)\n and isinstance(instance.pytype, pytypes.TupleType)\n and len(target_type.types) == len(instance.pytype.items)\n ):\n # Special handling to map tuples (named and unnamed) to arc4 structs\n # instance builder for TupleType should be a StaticSizedCollectionBuilder\n assert isinstance(instance, StaticSizedCollectionBuilder)\n conversion_args = [\n _implicit_arc4_conversion(item, item_target_typ)\n for item, item_target_typ in zip(\n instance.iterate_static(), target_type.types, strict=True\n )\n ]\n else:\n conversion_args = [instance]\n target_type_builder = builder_for_type(target_type, instance.source_location)\n return target_type_builder.call(\n args=conversion_args,\n arg_names=[None] * len(conversion_args),\n arg_kinds=[mypy.nodes.ARG_POS] * len(conversion_args),\n location=instance.source_location,\n )\n\n\ndef _maybe_resolve_arc4_literal(\n operand: InstanceBuilder, target_type: pytypes.PyType\n) -> InstanceBuilder:\n \"\"\"Handles special case of resolving a literal tuple into an arc4 tuple\"\"\"\n from puyapy.awst_build.eb.tuple import TupleLiteralBuilder\n\n if isinstance(operand, TupleLiteralBuilder) and isinstance(target_type, pytypes.ARC4TupleType):\n resolved_items = [\n _maybe_resolve_arc4_literal(item, item_type)\n for item, item_type in zip(operand.iterate_static(), target_type.items, strict=True)\n ]\n return TupleLiteralBuilder(resolved_items, operand.source_location)\n return maybe_resolve_literal(operand, target_type)\n\n\ndef _split_signature(\n signature: str, location: SourceLocation\n) -> tuple[str, str | None, str | None]:\n \"\"\"Splits signature into name, args and returns\"\"\"\n level = 0\n last_idx = 0\n name: str = \"\"\n args: str | None = None\n returns: str | None = None\n for idx, tok in enumerate(signature):\n if tok == \"(\":\n level += 1\n if level == 1:\n if not name:\n name = signature[:idx]\n last_idx = idx + 1\n elif tok == \")\":\n level -= 1\n if level == 0:\n if args is None:\n args = signature[last_idx:idx]\n elif returns is None:\n returns = signature[last_idx - 1 : idx + 1]\n last_idx = idx + 1\n if last_idx < len(signature):\n remaining = signature[last_idx:]\n if remaining:\n if not name:\n name = remaining\n elif args is None:\n raise CodeError(\n f\"invalid signature, args not well defined: {name=}, {remaining=}\", location\n )\n elif returns:\n raise CodeError(\n f\"invalid signature, text after returns:\"\n f\" {name=}, {args=}, {returns=}, {remaining=}\",\n location,\n )\n else:\n returns = remaining\n if not name or not _VALID_NAME_PATTERN.match(name):\n logger.error(f\"invalid signature: {name=}\", location=location)\n return name, args, returns\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/arc4\/_utils.py","language":"Python","license":"NOASSERTION","size":10173} {"code":"import typing\nfrom collections.abc import Iterable, Mapping, Sequence, Set\n\nimport attrs\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.avm import OnCompletionAction, TransactionType\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import (\n ARC4CreateOption,\n ARC4Decode,\n ARC4Encode,\n ARC4MethodConfig,\n BytesConstant,\n BytesEncoding,\n CompiledContract,\n CreateInnerTransaction,\n Expression,\n IntegerConstant,\n MethodConstant,\n SubmitInnerTransaction,\n TupleExpression,\n TupleItemExpression,\n UInt64Constant,\n)\nfrom puya.awst.txn_fields import TxnField\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation, sequential_source_locations_merge\nfrom puya.program_refs import ContractReference\nfrom puya.utils import StableSet\nfrom puyapy.awst_build import constants, pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder\nfrom puyapy.awst_build.eb.arc4._base import ARC4FromLogBuilder\nfrom puyapy.awst_build.eb.arc4._utils import ARC4Signature, get_arc4_signature\nfrom puyapy.awst_build.eb.bytes import BytesExpressionBuilder\nfrom puyapy.awst_build.eb.compiled import (\n APP_ALLOCATION_FIELDS,\n PROGRAM_FIELDS,\n CompiledContractExpressionBuilder,\n)\nfrom puyapy.awst_build.eb.contracts import ContractTypeExpressionBuilder\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import (\n InstanceBuilder,\n LiteralBuilder,\n NodeBuilder,\n TypeBuilder,\n)\nfrom puyapy.awst_build.eb.subroutine import BaseClassSubroutineInvokerExpressionBuilder\nfrom puyapy.awst_build.eb.transaction import InnerTransactionExpressionBuilder\nfrom puyapy.awst_build.eb.transaction.itxn_args import PYTHON_ITXN_ARGUMENTS\nfrom puyapy.awst_build.eb.tuple import TupleExpressionBuilder, TupleLiteralBuilder\nfrom puyapy.awst_build.eb.uint64 import UInt64ExpressionBuilder\nfrom puyapy.models import (\n ARC4ABIMethodData,\n ARC4BareMethodData,\n ARC4MethodData,\n ContractFragmentBase,\n ContractFragmentMethod,\n)\n\nlogger = log.get_logger(__name__)\n\n_FIELD_TO_ITXN_ARGUMENT = {arg.field: arg for arg in PYTHON_ITXN_ARGUMENTS.values()}\n_ABI_CALL_TRANSACTION_FIELDS = [\n TxnField.ApplicationID,\n TxnField.OnCompletion,\n TxnField.ApprovalProgramPages,\n TxnField.ClearStateProgramPages,\n TxnField.GlobalNumUint,\n TxnField.GlobalNumByteSlice,\n TxnField.LocalNumUint,\n TxnField.LocalNumByteSlice,\n TxnField.ExtraProgramPages,\n TxnField.Fee,\n TxnField.Sender,\n TxnField.Note,\n TxnField.RekeyTo,\n]\n_ARC4_CREATE_TRANSACTION_FIELDS = [\n TxnField.OnCompletion,\n TxnField.Fee,\n TxnField.Sender,\n TxnField.Note,\n TxnField.RekeyTo,\n]\n_ARC4_UPDATE_TRANSACTION_FIELDS = [\n TxnField.ApplicationID,\n TxnField.Fee,\n TxnField.Sender,\n TxnField.Note,\n TxnField.RekeyTo,\n]\n_COMPILED_KWARG = \"compiled\"\n\n\nclass ARC4ClientTypeBuilder(TypeBuilder):\n def __init__(\n self, typ: pytypes.PyType, source_location: SourceLocation, fragment: ContractFragmentBase\n ):\n assert pytypes.ARC4ClientBaseType in typ.bases\n super().__init__(typ, source_location)\n self.fragment: typing.Final = fragment\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n raise CodeError(\"ARC4Client subclasses cannot be instantiated\", location)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n method = self.fragment.resolve_method(name)\n if method is None:\n return super().member_access(name, location)\n return ARC4ClientMethodExpressionBuilder(method, location)\n\n\nclass ARC4ClientMethodExpressionBuilder(FunctionBuilder):\n def __init__(\n self,\n method: ContractFragmentMethod,\n location: SourceLocation,\n ):\n super().__init__(location)\n self.method: typing.Final = method\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n raise CodeError(\n f\"can't invoke client methods directly, use {constants.CLS_ARC4_ABI_CALL}\", location\n )\n\n\nclass ABICallGenericTypeBuilder(FunctionBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n return _abi_call(args, arg_names, location, return_type_annotation=pytypes.NoneType)\n\n\nclass ABICallTypeBuilder(FunctionBuilder):\n def __init__(self, typ: pytypes.PyType, location: SourceLocation):\n assert isinstance(typ, pytypes.PseudoGenericFunctionType)\n self._return_type_annotation = typ.return_type\n super().__init__(location)\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n return _abi_call(\n args, arg_names, location, return_type_annotation=self._return_type_annotation\n )\n\n\ndef _get_python_kwargs(fields: Sequence[TxnField]) -> Set[str]:\n return StableSet.from_iter(\n arg for arg, param in PYTHON_ITXN_ARGUMENTS.items() if param.field in fields\n )\n\n\nclass _ARC4CompilationFunctionBuilder(FunctionBuilder):\n allowed_fields: Sequence[TxnField]\n\n @property\n def allowed_kwargs(self) -> Set[str]:\n return {_COMPILED_KWARG, *_get_python_kwargs(self.allowed_fields)}\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n # if on_completion not allowed, it must be an update\n is_update = TxnField.OnCompletion not in self.allowed_fields\n method_or_type, abi_args, kwargs = _get_method_abi_args_and_kwargs(\n args, arg_names, self.allowed_kwargs\n )\n compiled = None\n if compiled_node := kwargs.pop(_COMPILED_KWARG, None):\n compiled = expect.argument_of_type_else_dummy(\n compiled_node, pytypes.CompiledContractType\n )\n\n match method_or_type:\n case None:\n raise CodeError(\"missing required positional argument 'method'\", location)\n case BaseClassSubroutineInvokerExpressionBuilder(method=fmethod, cref=contract_ref):\n method_call = _get_arc4_method_call(fmethod, abi_args, location)\n case ContractTypeExpressionBuilder(\n fragment=fragment, pytype=pytypes.TypeType(typ=typ)\n ) if pytypes.ARC4ContractBaseType < typ:\n contract_ref = fragment.id\n method_call = _get_lifecycle_method_call(\n fragment,\n abi_args,\n kind=\"update\" if is_update else \"create\",\n location=method_or_type.source_location,\n )\n case other:\n expect.not_this_type(other, default=expect.default_raise)\n if compiled is None:\n compiled = CompiledContractExpressionBuilder(\n CompiledContract(\n contract=contract_ref,\n wtype=pytypes.CompiledContractType.wtype,\n source_location=location,\n )\n )\n else:\n _warn_if_different_contract(\n compiled, contract_ref, related_location=method_or_type.source_location\n )\n field_nodes = {PYTHON_ITXN_ARGUMENTS[kwarg].field: node for kwarg, node in kwargs.items()}\n if is_update:\n _add_on_completion(field_nodes, OnCompletionAction.UpdateApplication, location)\n # if on_completion is not set but can be inferred from config then use that\n elif (\n TxnField.OnCompletion not in field_nodes\n and (on_completion := _get_singular_on_complete(method_call.config)) is not None\n ):\n _add_on_completion(field_nodes, on_completion, location)\n\n compiled = compiled.single_eval()\n for member_name, field in PROGRAM_FIELDS.items():\n field_nodes[field] = compiled.member_access(member_name, location)\n # is creating\n if not is_update:\n # add all app allocation fields\n for member_name, field in APP_ALLOCATION_FIELDS.items():\n field_nodes[field] = compiled.member_access(member_name, location)\n _validate_transaction_kwargs(\n field_nodes,\n method_call.config,\n method_location=method_or_type.source_location,\n call_location=location,\n )\n return _create_abi_call_expr(\n abi_args=method_call.arc4_args,\n arc4_return_type=method_call.arc4_return_type,\n declared_result_type=method_call.method_return_type,\n field_nodes=field_nodes,\n location=location,\n )\n\n\ndef _warn_if_different_contract(\n compiled: InstanceBuilder, contract: ContractReference, *, related_location: SourceLocation\n) -> None:\n # naive check for mismatch between method and compiled parameters\n expr = compiled.resolve()\n if isinstance(expr, CompiledContract) and expr.contract != contract:\n logger.warning(\n \"compiled parameter is for a different contract\",\n location=compiled.source_location,\n )\n logger.info(\"other contract reference\", location=related_location)\n\n\nclass ARC4CreateFunctionBuilder(_ARC4CompilationFunctionBuilder):\n allowed_fields: Sequence[TxnField] = _ARC4_CREATE_TRANSACTION_FIELDS\n\n\nclass ARC4UpdateFunctionBuilder(_ARC4CompilationFunctionBuilder):\n allowed_fields: Sequence[TxnField] = _ARC4_UPDATE_TRANSACTION_FIELDS\n\n\ndef _abi_call(\n args: Sequence[NodeBuilder],\n arg_names: list[str | None],\n location: SourceLocation,\n *,\n return_type_annotation: pytypes.PyType,\n) -> InstanceBuilder:\n method, abi_args, kwargs = _get_method_abi_args_and_kwargs(\n args, arg_names, _get_python_kwargs(_ABI_CALL_TRANSACTION_FIELDS)\n )\n declared_result_type: pytypes.PyType\n arc4_config = None\n match method:\n case None:\n raise CodeError(\"missing required positional argument 'method'\", location)\n case (\n ARC4ClientMethodExpressionBuilder(method=fmethod)\n | BaseClassSubroutineInvokerExpressionBuilder(method=fmethod)\n ):\n # in this case the arc4 signature and declared return type are inferred\n method_call = _get_arc4_method_call(fmethod, abi_args, location)\n arc4_args = method_call.arc4_args\n arc4_return_type = method_call.arc4_return_type\n arc4_config = method_call.config\n declared_result_type = method_call.method_return_type\n if return_type_annotation not in (declared_result_type, pytypes.NoneType):\n logger.error(\n \"mismatch between return type of method and generic parameter\",\n location=location,\n )\n case _:\n method_str, signature = get_arc4_signature(method, abi_args, location)\n declared_result_type = return_type_annotation\n if declared_result_type != pytypes.NoneType:\n # this will be validated against signature below, by comparing\n # the generated method_selector against the supplied method_str\n signature = attrs.evolve(signature, return_type=declared_result_type)\n if not signature.method_selector.startswith(method_str):\n logger.error(\n f\"method selector from args '{signature.method_selector}' \"\n f\"does not match provided method selector: '{method_str}'\",\n location=method.source_location,\n )\n arc4_args = _method_selector_and_arc4_args(signature, abi_args, location)\n arc4_return_type = signature.return_type\n\n field_nodes = {PYTHON_ITXN_ARGUMENTS[kwarg].field: node for kwarg, node in kwargs.items()}\n # set on_completion if it can be inferred from config\n if (\n TxnField.OnCompletion not in field_nodes\n and (on_completion := _get_singular_on_complete(arc4_config)) is not None\n ):\n _add_on_completion(field_nodes, on_completion, location)\n\n _validate_transaction_kwargs(\n field_nodes,\n arc4_config,\n method_location=method.source_location,\n call_location=location,\n )\n return _create_abi_call_expr(\n arc4_return_type=arc4_return_type,\n abi_args=arc4_args,\n declared_result_type=declared_result_type,\n field_nodes=field_nodes,\n location=location,\n )\n\n\ndef _get_method_abi_args_and_kwargs(\n args: Sequence[NodeBuilder], arg_names: list[str | None], allowed_kwargs: Set[str]\n) -> tuple[NodeBuilder | None, Sequence[NodeBuilder], dict[str, NodeBuilder]]:\n method: NodeBuilder | None = None\n abi_args = list[NodeBuilder]()\n kwargs = dict[str, NodeBuilder]()\n for idx, (arg_name, arg) in enumerate(zip(arg_names, args, strict=True)):\n if arg_name is None:\n if idx == 0:\n method = arg\n else:\n abi_args.append(arg)\n elif arg_name in allowed_kwargs:\n kwargs[arg_name] = arg\n else:\n logger.error(\"unrecognised keyword argument\", location=arg.source_location)\n return method, abi_args, kwargs\n\n\n@attrs.frozen\nclass _ARC4MethodCall:\n config: ARC4MethodConfig | None\n arc4_args: Sequence[InstanceBuilder]\n method_return_type: pytypes.PyType\n \"\"\"\n Return type as declared on the method, this may not be an ARC4 type due to automatic\n type conversion\n \"\"\"\n arc4_return_type: pytypes.PyType\n \"\"\"\n ARC4 return type\n \"\"\"\n\n\ndef _get_arc4_method_call(\n data: ContractFragmentMethod, abi_args: Sequence[NodeBuilder], location: SourceLocation\n) -> _ARC4MethodCall:\n if data.metadata is None:\n raise CodeError(\"not a valid ARC4 method\", location)\n return _map_arc4_method_data_to_call(data.metadata, abi_args, location)\n\n\ndef _map_arc4_method_data_to_call(\n data: ARC4MethodData,\n abi_args: Sequence[NodeBuilder],\n location: SourceLocation,\n) -> _ARC4MethodCall:\n match data:\n case ARC4ABIMethodData() as abi_method_data:\n signature = ARC4Signature(\n method_name=abi_method_data.config.name,\n arg_types=abi_method_data.arc4_argument_types,\n return_type=abi_method_data.arc4_return_type,\n source_location=location,\n )\n return _ARC4MethodCall(\n config=abi_method_data.config,\n arc4_args=_method_selector_and_arc4_args(signature, abi_args, location),\n method_return_type=abi_method_data.return_type,\n arc4_return_type=abi_method_data.arc4_return_type,\n )\n case ARC4BareMethodData() as bare_method_data:\n _expect_bare_method_args(abi_args)\n return _ARC4MethodCall(\n config=bare_method_data.config,\n arc4_args=[],\n method_return_type=pytypes.NoneType,\n arc4_return_type=pytypes.NoneType,\n )\n case other:\n typing.assert_never(other)\n\n\ndef _get_lifecycle_method_call(\n fragment: ContractFragmentBase,\n abi_args: Sequence[NodeBuilder],\n kind: typing.Literal[\"create\", \"update\"],\n location: SourceLocation,\n) -> _ARC4MethodCall:\n if kind == \"create\":\n possible_methods = list(fragment.find_arc4_method_metadata(can_create=True))\n elif kind == \"update\":\n possible_methods = list(\n fragment.find_arc4_method_metadata(oca=OnCompletionAction.UpdateApplication)\n )\n\n try:\n single_method, *others = possible_methods\n except ValueError:\n raise CodeError(f\"could not find {kind} method on {fragment.id}\", location) from None\n if others:\n raise CodeError(\n f\"found multiple {kind} methods on {fragment.id}, please specify which one to use\",\n location,\n )\n method_call = _map_arc4_method_data_to_call(single_method, abi_args, location)\n # remove method_return_type from result\n # so _create_abi_call_expr does not attempt to include any decoded ARC4 result\n # as per the stubs overload for arc4_create\/arc4_update with a Contract type\n return attrs.evolve(method_call, method_return_type=pytypes.NoneType)\n\n\ndef _method_selector_and_arc4_args(\n signature: ARC4Signature, abi_args: Sequence[NodeBuilder], location: SourceLocation\n) -> Sequence[InstanceBuilder]:\n return [\n BytesExpressionBuilder(\n MethodConstant(value=signature.method_selector, source_location=location)\n ),\n *signature.convert_args(abi_args, expect_itxn_args=True),\n ]\n\n\ndef _create_abi_call_expr(\n *,\n abi_args: Sequence[InstanceBuilder],\n arc4_return_type: pytypes.PyType,\n declared_result_type: pytypes.PyType,\n field_nodes: dict[TxnField, NodeBuilder],\n location: SourceLocation,\n) -> InstanceBuilder:\n group = []\n array_fields: dict[TxnField, list[Expression]] = {\n TxnField.ApplicationArgs: [],\n TxnField.Accounts: [],\n TxnField.Applications: [],\n TxnField.Assets: [],\n }\n\n def ref_to_arg(ref_field: TxnField, arg: InstanceBuilder) -> Expression:\n # TODO: what about references that are used more than once?\n implicit_offset = 1 if ref_field in (TxnField.Accounts, TxnField.Applications) else 0\n ref_list = array_fields[ref_field]\n ref_index = len(ref_list)\n ref_list.append(arg.resolve())\n return BytesConstant(\n value=(ref_index + implicit_offset).to_bytes(length=1),\n encoding=BytesEncoding.base16,\n source_location=arg.source_location,\n )\n\n for arg_b in abi_args:\n arg_expr = None\n match arg_b.pytype:\n case pytypes.InnerTransactionFieldsetType():\n group.append(arg_b.resolve())\n # no arg_expr as txn aren't part of the app args\n case pytypes.TransactionRelatedType():\n logger.error(\n \"only inner transaction types can be used to call another contract\",\n location=arg_b.source_location,\n )\n case pytypes.AssetType:\n arg_expr = ref_to_arg(TxnField.Assets, arg_b)\n case pytypes.AccountType:\n arg_expr = ref_to_arg(TxnField.Accounts, arg_b)\n case pytypes.ApplicationType:\n arg_expr = ref_to_arg(TxnField.Applications, arg_b)\n case _:\n arg_expr = arg_b.resolve()\n if arg_expr is not None:\n array_fields[TxnField.ApplicationArgs].append(arg_expr)\n\n txn_type_appl = TransactionType.appl\n fields: dict[TxnField, Expression] = {\n TxnField.Fee: UInt64Constant(value=0, source_location=location),\n TxnField.TypeEnum: UInt64Constant(\n value=txn_type_appl.value, teal_alias=txn_type_appl.name, source_location=location\n ),\n }\n for arr_field, arr_field_values in array_fields.items():\n if arr_field_values:\n if arr_field == TxnField.ApplicationArgs and len(arr_field_values) > 16:\n args_to_pack = arr_field_values[15:]\n arr_field_values[15:] = [\n _arc4_tuple_from_items(args_to_pack, _combine_locs(args_to_pack))\n ]\n fields[arr_field] = TupleExpression.from_items(\n arr_field_values, _combine_locs(arr_field_values)\n )\n\n for field, field_node in field_nodes.items():\n params = _FIELD_TO_ITXN_ARGUMENT[field]\n if params is None:\n logger.error(\"unrecognised keyword argument\", location=field_node.source_location)\n else:\n fields[field] = params.validate_and_convert(field_node).resolve()\n\n itxn_result_pytype = pytypes.InnerTransactionResultTypes[txn_type_appl]\n create_itxn = CreateInnerTransaction(\n fields=fields,\n wtype=pytypes.InnerTransactionFieldsetTypes[txn_type_appl].wtype,\n source_location=location,\n )\n group.append(create_itxn)\n if len(group) == 1:\n itxn_builder: InstanceBuilder = InnerTransactionExpressionBuilder(\n SubmitInnerTransaction(itxns=group, source_location=location), itxn_result_pytype\n )\n else:\n itxn_types = []\n for itxn in group:\n assert isinstance(itxn.wtype, wtypes.WInnerTransactionFields)\n itxn_types.append(pytypes.InnerTransactionResultTypes[itxn.wtype.transaction_type])\n itxn_tuple_result_pytype = pytypes.GenericTupleType.parameterise(\n itxn_types,\n location,\n )\n itxn_tuple_builder = TupleExpressionBuilder(\n SubmitInnerTransaction(itxns=group, source_location=location),\n itxn_tuple_result_pytype,\n ).single_eval()\n itxn_builder = InnerTransactionExpressionBuilder(\n TupleItemExpression(\n base=itxn_tuple_builder.resolve(),\n index=-1,\n source_location=location,\n ),\n itxn_result_pytype,\n )\n\n if declared_result_type == pytypes.NoneType:\n return itxn_builder\n itxn_builder = itxn_builder.single_eval()\n assert isinstance(itxn_builder, InnerTransactionExpressionBuilder)\n last_log = itxn_builder.get_field_value(TxnField.LastLog, pytypes.BytesType, location)\n abi_result = ARC4FromLogBuilder.abi_expr_from_log(arc4_return_type, last_log, location)\n # the declared result type may be different to the arc4 signature return type\n # due to automatic conversion of ARC4 -> native types\n if declared_result_type != arc4_return_type:\n abi_result = ARC4Decode(\n value=abi_result,\n wtype=declared_result_type.checked_wtype(location),\n source_location=location,\n )\n\n abi_result_builder = builder_for_instance(declared_result_type, abi_result)\n return TupleLiteralBuilder((abi_result_builder, itxn_builder), location)\n\n\ndef _combine_locs(exprs: Sequence[Expression | NodeBuilder]) -> SourceLocation:\n return sequential_source_locations_merge(a.source_location for a in exprs)\n\n\ndef _arc4_tuple_from_items(\n items: Sequence[Expression], source_location: SourceLocation\n) -> ARC4Encode:\n # TODO: should we just allow TupleExpression to have an ARCTuple wtype?\n args_tuple = TupleExpression.from_items(items, source_location)\n return ARC4Encode(\n value=args_tuple,\n wtype=wtypes.ARC4Tuple(types=args_tuple.wtype.types, source_location=source_location),\n source_location=source_location,\n )\n\n\ndef _expect_bare_method_args(abi_args: Sequence[NodeBuilder]) -> None:\n if abi_args:\n logger.error(\"unexpected args for bare method\", location=_combine_locs(abi_args))\n\n\ndef _validate_transaction_kwargs(\n field_nodes: Mapping[TxnField, NodeBuilder],\n arc4_config: ARC4MethodConfig | None,\n *,\n method_location: SourceLocation,\n call_location: SourceLocation,\n) -> None:\n # note these values may be None which indicates their value is unknown at compile time\n on_completion = _get_on_completion(field_nodes)\n is_update = on_completion == OnCompletionAction.UpdateApplication\n is_create = _is_creating(field_nodes)\n\n if is_create:\n # app_id not provided but method doesn't support creating\n if arc4_config and arc4_config.create == ARC4CreateOption.disallow:\n logger.error(\"method cannot be used to create application\", location=method_location)\n # required args for creation missing\n else:\n _check_program_fields_are_present(\n \"missing required arguments to create app\", field_nodes, call_location\n )\n if is_update:\n if arc4_config and (\n OnCompletionAction.UpdateApplication not in arc4_config.allowed_completion_types\n ):\n logger.error(\"method cannot be used to update application\", location=method_location)\n else:\n _check_program_fields_are_present(\n \"missing required arguments to update app\", field_nodes, call_location\n )\n # on_completion not valid for arc4_config\n elif (\n on_completion is not None\n and arc4_config\n and on_completion not in arc4_config.allowed_completion_types\n ):\n arg = field_nodes[TxnField.OnCompletion]\n logger.error(\n \"on completion action is not supported by ARC4 method being called\",\n location=arg.source_location,\n )\n logger.info(\"method ARC4 configuration\", location=arc4_config.source_location)\n\n # programs provided when known not to be creating or updating\n if is_create is False and is_update is False:\n _check_fields_not_present(\n \"provided argument is only valid when creating or updating an application\",\n PROGRAM_FIELDS.values(),\n field_nodes,\n )\n if is_create is False:\n _check_fields_not_present(\n \"provided argument is only valid when creating an application\",\n APP_ALLOCATION_FIELDS.values(),\n field_nodes,\n )\n\n\ndef _check_program_fields_are_present(\n error_message: str, field_nodes: Mapping[TxnField, NodeBuilder], location: SourceLocation\n) -> None:\n if missing_fields := [field for field in PROGRAM_FIELDS.values() if field not in field_nodes]:\n logger.error(\n f\"{error_message}: {', '.join(_get_python_kwargs(missing_fields))}\",\n location=location,\n )\n\n\ndef _check_fields_not_present(\n error_message: str,\n fields_to_omit: Iterable[TxnField],\n field_nodes: Mapping[TxnField, NodeBuilder],\n) -> None:\n for field in fields_to_omit:\n if node := field_nodes.get(field):\n logger.error(error_message, location=node.source_location)\n\n\ndef _get_singular_on_complete(config: ARC4MethodConfig | None) -> OnCompletionAction | None:\n if config:\n try:\n (on_complete,) = config.allowed_completion_types\n except ValueError:\n pass\n else:\n return on_complete\n return None\n\n\ndef _get_on_completion(field_nodes: Mapping[TxnField, NodeBuilder]) -> OnCompletionAction | None:\n \"\"\"\n Returns OnCompletionAction if it is statically known, otherwise returns None\n \"\"\"\n match field_nodes.get(TxnField.OnCompletion):\n case None:\n return OnCompletionAction.NoOp\n case InstanceBuilder(pytype=pytypes.OnCompleteActionType) as eb:\n value = eb.resolve()\n if isinstance(value, IntegerConstant):\n return OnCompletionAction(value.value)\n return None\n\n\ndef _is_creating(field_nodes: Mapping[TxnField, NodeBuilder]) -> bool | None:\n \"\"\"\n Returns app_id == 0 if app_id is statically known, otherwise returns None\n \"\"\"\n match field_nodes.get(TxnField.ApplicationID):\n case None:\n return True\n case LiteralBuilder(value=int(app_id)):\n return app_id == 0\n return None\n\n\ndef _add_on_completion(\n field_nodes: dict[TxnField, NodeBuilder],\n on_complete: OnCompletionAction,\n location: SourceLocation,\n) -> None:\n # if NoOp can just omit\n if on_complete == OnCompletionAction.NoOp:\n return\n field_nodes[TxnField.OnCompletion] = UInt64ExpressionBuilder(\n UInt64Constant(\n source_location=location, value=on_complete.value, teal_alias=on_complete.name\n ),\n enum_type=pytypes.OnCompleteActionType,\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/arc4\/abi_call.py","language":"Python","license":"NOASSERTION","size":28228} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log, utils\nfrom puya.algo_constants import ENCODED_ADDRESS_LENGTH\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import (\n AddressConstant,\n CheckedMaybe,\n Expression,\n NumericComparison,\n NumericComparisonExpression,\n ReinterpretCast,\n UInt64Constant,\n)\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import intrinsic_factory, pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._bytes_backed import BytesBackedTypeBuilder\nfrom puyapy.awst_build.eb._utils import compare_expr_bytes\nfrom puyapy.awst_build.eb.arc4.static_array import StaticArrayExpressionBuilder\nfrom puyapy.awst_build.eb.interface import (\n BuilderComparisonOp,\n InstanceBuilder,\n LiteralBuilder,\n NodeBuilder,\n)\nfrom puyapy.awst_build.eb.reference_types.account import AccountExpressionBuilder\n\nlogger = log.get_logger(__name__)\n\n\nclass AddressTypeBuilder(BytesBackedTypeBuilder[pytypes.ArrayType]):\n def __init__(self, location: SourceLocation):\n super().__init__(pytypes.ARC4AddressType, location)\n\n @typing.override\n def try_convert_literal(\n self, literal: LiteralBuilder, location: SourceLocation\n ) -> InstanceBuilder | None:\n match literal.value:\n case str(str_value):\n if not utils.valid_address(str_value):\n logger.error(\n f\"Invalid address value. Address literals should be\"\n f\" {ENCODED_ADDRESS_LENGTH} characters and not include base32 padding\",\n location=literal.source_location,\n )\n expr = AddressConstant(\n value=str_value,\n wtype=wtypes.arc4_address_alias,\n source_location=location,\n )\n return AddressExpressionBuilder(expr)\n return None\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.at_most_one_arg(args, location)\n if arg is None:\n result = _zero_address(location)\n elif arg.pytype == pytypes.StrLiteralType:\n return arg.resolve_literal(converter=AddressTypeBuilder(location))\n elif arg.pytype == pytypes.AccountType: # Account is a final type\n result = _address_from_native(arg)\n else:\n arg = expect.argument_of_type_else_dummy(arg, pytypes.BytesType)\n arg = arg.single_eval()\n is_correct_length = NumericComparisonExpression(\n operator=NumericComparison.eq,\n source_location=location,\n lhs=UInt64Constant(value=32, source_location=location),\n rhs=intrinsic_factory.bytes_len(arg.resolve(), location),\n )\n result = CheckedMaybe.from_tuple_items(\n expr=_address_from_native(arg),\n check=is_correct_length,\n source_location=location,\n comment=\"Address length is 32 bytes\",\n )\n return AddressExpressionBuilder(result)\n\n\nclass AddressExpressionBuilder(StaticArrayExpressionBuilder):\n def __init__(self, expr: Expression):\n super().__init__(expr, pytypes.ARC4AddressType)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n return compare_expr_bytes(\n lhs=self.resolve(),\n op=BuilderComparisonOp.eq if negate else BuilderComparisonOp.ne,\n rhs=_zero_address(location),\n source_location=location,\n )\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n if other.pytype == pytypes.StrLiteralType:\n rhs = other.resolve_literal(AddressTypeBuilder(other.source_location)).resolve()\n elif other.pytype == pytypes.AccountType: # Account is a final type\n rhs = _address_from_native(other)\n elif pytypes.ARC4AddressType <= other.pytype:\n rhs = other.resolve()\n else:\n return NotImplemented\n return compare_expr_bytes(lhs=self.resolve(), op=op, rhs=rhs, source_location=location)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n match name:\n case \"native\":\n return AccountExpressionBuilder(_address_to_native(self))\n case _:\n return super().member_access(name, location)\n\n\ndef _zero_address(location: SourceLocation) -> Expression:\n return intrinsic_factory.zero_address(location, as_type=wtypes.arc4_address_alias)\n\n\ndef _address_to_native(builder: InstanceBuilder) -> Expression:\n assert pytypes.ARC4AddressType <= builder.pytype\n return ReinterpretCast(\n expr=builder.resolve(),\n wtype=wtypes.account_wtype,\n source_location=builder.source_location,\n )\n\n\ndef _address_from_native(builder: InstanceBuilder) -> Expression:\n assert builder.pytype.is_type_or_subtype(pytypes.AccountType, pytypes.BytesType)\n return ReinterpretCast(\n expr=builder.resolve(),\n wtype=wtypes.arc4_address_alias,\n source_location=builder.source_location,\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/arc4\/address.py","language":"Python","license":"NOASSERTION","size":5505} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import ARC4Decode, ARC4Encode, BoolConstant, Expression\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import NotIterableInstanceExpressionBuilder\nfrom puyapy.awst_build.eb._bytes_backed import BytesBackedInstanceExpressionBuilder\nfrom puyapy.awst_build.eb._utils import compare_bytes\nfrom puyapy.awst_build.eb.arc4._base import ARC4TypeBuilder, arc4_bool_bytes\nfrom puyapy.awst_build.eb.bool import BoolExpressionBuilder\nfrom puyapy.awst_build.eb.interface import (\n BuilderComparisonOp,\n InstanceBuilder,\n LiteralBuilder,\n NodeBuilder,\n)\n\nlogger = log.get_logger(__name__)\n\n\nclass ARC4BoolTypeBuilder(ARC4TypeBuilder):\n def __init__(self, location: SourceLocation):\n super().__init__(pytypes.ARC4BoolType, location)\n\n @typing.override\n def try_convert_literal(\n self, literal: LiteralBuilder, location: SourceLocation\n ) -> InstanceBuilder | None:\n match literal.value:\n case bool(bool_literal):\n return ARC4BoolExpressionBuilder(\n BoolConstant(\n value=bool_literal, source_location=location, wtype=wtypes.arc4_bool_wtype\n ),\n )\n return None\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.at_most_one_arg(args, location)\n match arg:\n case None:\n expr: Expression = BoolConstant(\n value=False, source_location=location, wtype=wtypes.arc4_bool_wtype\n )\n case _:\n arg = expect.argument_of_type_else_dummy(arg, pytypes.BoolType)\n native_bool = arg.resolve()\n expr = ARC4Encode(\n value=native_bool, wtype=wtypes.arc4_bool_wtype, source_location=location\n )\n return ARC4BoolExpressionBuilder(expr)\n\n\nclass ARC4BoolExpressionBuilder(\n NotIterableInstanceExpressionBuilder, BytesBackedInstanceExpressionBuilder\n):\n def __init__(self, expr: Expression):\n super().__init__(pytypes.ARC4BoolType, expr)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n return arc4_bool_bytes(\n self,\n false_bytes=b\"\\x00\",\n negate=negate,\n location=location,\n )\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n match name:\n case \"native\":\n return self._native(location)\n case _:\n return super().member_access(name, location)\n\n def _native(self, location: SourceLocation) -> BoolExpressionBuilder:\n result_expr: Expression = ARC4Decode(\n value=self.resolve(),\n wtype=pytypes.BoolType.wtype,\n source_location=location,\n )\n return BoolExpressionBuilder(result_expr)\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n if other.pytype == pytypes.BoolType:\n lhs = self._native(self.source_location)\n return lhs.compare(other, op, location)\n return compare_bytes(self=self, op=op, other=other, source_location=location)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/arc4\/bool.py","language":"Python","license":"NOASSERTION","size":3710} {"code":"import abc\nimport typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import (\n ArrayConcat,\n ArrayExtend,\n ArrayPop,\n Expression,\n ExpressionStatement,\n IntrinsicCall,\n NewArray,\n Statement,\n TupleExpression,\n UInt64Constant,\n)\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder, GenericTypeBuilder\nfrom puyapy.awst_build.eb._bytes_backed import BytesBackedTypeBuilder\nfrom puyapy.awst_build.eb._utils import (\n dummy_statement,\n dummy_value,\n)\nfrom puyapy.awst_build.eb.arc4._base import _ARC4ArrayExpressionBuilder, arc4_bool_bytes\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import BuilderBinaryOp, InstanceBuilder, NodeBuilder\nfrom puyapy.awst_build.eb.none import NoneExpressionBuilder\nfrom puyapy.awst_build.eb.uint64 import UInt64ExpressionBuilder\n\n__all__ = [\n \"DynamicArrayGenericTypeBuilder\",\n \"DynamicArrayTypeBuilder\",\n \"DynamicArrayExpressionBuilder\",\n]\n\nlogger = log.get_logger(__name__)\n\n\nclass DynamicArrayGenericTypeBuilder(GenericTypeBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n if not args:\n raise CodeError(\"empty arrays require a type annotation to be instantiated\", location)\n element_type = expect.instance_builder(args[0], default=expect.default_raise).pytype\n typ = pytypes.GenericARC4DynamicArrayType.parameterise([element_type], location)\n values = tuple(expect.argument_of_type_else_dummy(a, element_type).resolve() for a in args)\n wtype = typ.wtype\n assert isinstance(wtype, wtypes.ARC4DynamicArray)\n return DynamicArrayExpressionBuilder(\n NewArray(values=values, wtype=wtype, source_location=location), typ\n )\n\n\nclass DynamicArrayTypeBuilder(BytesBackedTypeBuilder[pytypes.ArrayType]):\n def __init__(self, typ: pytypes.PyType, location: SourceLocation):\n assert isinstance(typ, pytypes.ArrayType)\n assert typ.generic == pytypes.GenericARC4DynamicArrayType\n assert typ.size is None\n super().__init__(typ, location)\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n typ = self.produces()\n values = tuple(expect.argument_of_type_else_dummy(a, typ.items).resolve() for a in args)\n wtype = typ.wtype\n assert isinstance(wtype, wtypes.ARC4DynamicArray)\n return DynamicArrayExpressionBuilder(\n NewArray(values=values, wtype=wtype, source_location=location), self._pytype\n )\n\n\nclass DynamicArrayExpressionBuilder(_ARC4ArrayExpressionBuilder):\n def __init__(self, expr: Expression, typ: pytypes.PyType):\n assert isinstance(typ, pytypes.ArrayType)\n super().__init__(typ, expr)\n\n @typing.override\n def length(self, location: SourceLocation) -> InstanceBuilder:\n length = IntrinsicCall(\n op_code=\"extract_uint16\",\n stack_args=[self.resolve(), UInt64Constant(value=0, source_location=location)],\n wtype=wtypes.uint64_wtype,\n source_location=location,\n )\n return UInt64ExpressionBuilder(length)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n match name:\n case \"append\":\n return _Append(self.resolve(), self.pytype, location)\n case \"extend\":\n return _Extend(self.resolve(), self.pytype, location)\n case \"pop\":\n return _Pop(self.resolve(), self.pytype, location)\n case _:\n return super().member_access(name, location)\n\n @typing.override\n def augmented_assignment(\n self, op: BuilderBinaryOp, rhs: InstanceBuilder, location: SourceLocation\n ) -> Statement:\n if op != BuilderBinaryOp.add:\n logger.error(f\"unsupported operator for type: {op.value!r}\", location=location)\n return dummy_statement(location)\n rhs = _match_array_concat_arg(rhs, self.pytype)\n extend = ArrayExtend(\n base=self.resolve(),\n other=rhs.resolve(),\n wtype=wtypes.void_wtype,\n source_location=location,\n )\n return ExpressionStatement(expr=extend)\n\n @typing.override\n def binary_op(\n self,\n other: InstanceBuilder,\n op: BuilderBinaryOp,\n location: SourceLocation,\n *,\n reverse: bool,\n ) -> InstanceBuilder:\n # only __add__ is implemented, not __radd__\n if op != BuilderBinaryOp.add or reverse:\n return NotImplemented\n\n other = _match_array_concat_arg(other, self.pytype)\n return DynamicArrayExpressionBuilder(\n ArrayConcat(\n left=self.resolve(),\n right=other.resolve(),\n wtype=self.pytype.wtype,\n source_location=location,\n ),\n self.pytype,\n )\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n return arc4_bool_bytes(\n self,\n false_bytes=b\"\\x00\\x00\",\n negate=negate,\n location=location,\n )\n\n\nclass _ArrayFunc(FunctionBuilder, abc.ABC):\n def __init__(self, expr: Expression, typ: pytypes.ArrayType, location: SourceLocation):\n super().__init__(location)\n self.expr = expr\n self.typ = typ\n\n\nclass _Append(_ArrayFunc):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.exactly_one_arg_of_type_else_dummy(args, self.typ.items, location)\n args_expr = arg.resolve()\n args_tuple = TupleExpression.from_items([args_expr], arg.source_location)\n return NoneExpressionBuilder(\n ArrayExtend(\n base=self.expr, other=args_tuple, wtype=wtypes.void_wtype, source_location=location\n )\n )\n\n\nclass _Pop(_ArrayFunc):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n expect.no_args(args, location)\n result_expr = ArrayPop(\n base=self.expr, wtype=self.typ.items_wtype, source_location=location\n )\n return builder_for_instance(self.typ.items, result_expr)\n\n\nclass _Extend(_ArrayFunc):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.exactly_one_arg(args, location, default=expect.default_none)\n if arg is None:\n other = dummy_value(self.typ, location)\n else:\n other = _match_array_concat_arg(arg, self.typ)\n return NoneExpressionBuilder(\n ArrayExtend(\n base=self.expr,\n other=other.resolve(),\n wtype=wtypes.void_wtype,\n source_location=location,\n )\n )\n\n\ndef _match_array_concat_arg(arg: InstanceBuilder, arr_type: pytypes.ArrayType) -> InstanceBuilder:\n expected_item_type = arr_type.items\n match arg.pytype:\n case pytypes.SequenceType(items=array_items):\n okay = expected_item_type <= array_items\n case pytypes.TupleLikeType(items=tuple_items):\n okay = all(expected_item_type <= ti for ti in tuple_items)\n case _:\n okay = False\n if okay:\n return arg\n logger.error(\n \"expected an array or tuple of the same element type\", location=arg.source_location\n )\n return dummy_value(arr_type, arg.source_location)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/arc4\/dynamic_array.py","language":"Python","license":"NOASSERTION","size":8463} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import algo_constants, log\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import (\n ARC4Decode,\n ARC4Encode,\n BytesConstant,\n BytesEncoding,\n Expression,\n NewArray,\n)\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._bytes_backed import BytesBackedTypeBuilder\nfrom puyapy.awst_build.eb._utils import dummy_value\nfrom puyapy.awst_build.eb.arc4.dynamic_array import DynamicArrayExpressionBuilder\nfrom puyapy.awst_build.eb.arc4.uint import UIntNTypeBuilder\nfrom puyapy.awst_build.eb.bytes import BytesExpressionBuilder\nfrom puyapy.awst_build.eb.interface import InstanceBuilder, LiteralBuilder, NodeBuilder\n\nlogger = log.get_logger(__name__)\n\n\nclass DynamicBytesTypeBuilder(BytesBackedTypeBuilder[pytypes.ArrayType]):\n def __init__(self, location: SourceLocation):\n super().__init__(pytypes.ARC4DynamicBytesType, location)\n\n @typing.override\n def try_convert_literal(\n self, literal: LiteralBuilder, location: SourceLocation\n ) -> InstanceBuilder | None:\n match literal.value:\n case bytes(bytes_literal):\n if len(bytes_literal) > (algo_constants.MAX_BYTES_LENGTH - 2):\n logger.error(\n \"encoded bytes exceed max length\", location=literal.source_location\n )\n\n bytes_expr = BytesConstant(\n value=bytes_literal, encoding=BytesEncoding.unknown, source_location=location\n )\n return self._from_bytes_expr(bytes_expr, location)\n return None\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n match args:\n case [InstanceBuilder(pytype=pytypes.BytesLiteralType) as lit]:\n return lit.resolve_literal(DynamicBytesTypeBuilder(location))\n case []:\n bytes_expr: Expression = BytesConstant(\n value=b\"\", encoding=BytesEncoding.unknown, source_location=location\n )\n case [\n InstanceBuilder(pytype=single_arg_pytype) as eb\n ] if pytypes.BytesType <= single_arg_pytype:\n bytes_expr = eb.resolve()\n case _:\n non_literal_args = tuple(_coerce_to_byte(a).resolve() for a in args)\n return DynamicBytesExpressionBuilder(\n NewArray(\n values=non_literal_args, wtype=self._arc4_type, source_location=location\n )\n )\n return self._from_bytes_expr(bytes_expr, location)\n\n @property\n def _arc4_type(self) -> wtypes.ARC4DynamicArray:\n typ = self.produces()\n wtype = typ.wtype\n assert isinstance(wtype, wtypes.ARC4DynamicArray)\n return wtype\n\n def _from_bytes_expr(self, expr: Expression, location: SourceLocation) -> InstanceBuilder:\n encode_expr = ARC4Encode(value=expr, wtype=self._arc4_type, source_location=location)\n return DynamicBytesExpressionBuilder(encode_expr)\n\n\ndef _coerce_to_byte(builder: NodeBuilder) -> InstanceBuilder:\n arg = expect.instance_builder(\n builder, default=expect.default_dummy_value(pytypes.ARC4ByteType)\n )\n arg = arg.resolve_literal(UIntNTypeBuilder(pytypes.ARC4ByteType, arg.source_location))\n match arg:\n # can't use expect.argument_of_type here, we need a match statement\n case InstanceBuilder(pytype=pytypes.ARC4UIntNType(bits=8)):\n return arg\n case _:\n logger.error(\"invalid argument type\", location=arg.source_location)\n return dummy_value(pytypes.ARC4ByteType, arg.source_location)\n\n\nclass DynamicBytesExpressionBuilder(DynamicArrayExpressionBuilder):\n def __init__(self, expr: Expression):\n super().__init__(expr, pytypes.ARC4DynamicBytesType)\n\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n match name:\n case \"native\":\n return BytesExpressionBuilder(\n ARC4Decode(\n value=self.resolve(), wtype=wtypes.bytes_wtype, source_location=location\n )\n )\n case _:\n return super().member_access(name, location)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/arc4\/dynamic_bytes.py","language":"Python","license":"NOASSERTION","size":4552} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst.nodes import Emit\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.arc4_utils import pytype_to_arc4\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder\nfrom puyapy.awst_build.eb.arc4._utils import get_arc4_signature\nfrom puyapy.awst_build.eb.arc4.struct import ARC4StructTypeBuilder\nfrom puyapy.awst_build.eb.interface import InstanceBuilder, NodeBuilder\nfrom puyapy.awst_build.eb.none import NoneExpressionBuilder\n\nlogger = log.get_logger(__name__)\n\n\nclass EmitBuilder(FunctionBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n first, rest = expect.at_least_one_arg(args, location, default=expect.default_raise)\n match first:\n case (\n InstanceBuilder(pytype=pytypes.StructType() as struct_type) as event_arg_eb\n ) if pytypes.ARC4StructBaseType < struct_type:\n if rest:\n logger.error(\n \"unexpected additional arguments\", location=rest[0].source_location\n )\n case _:\n method_sig, signature = get_arc4_signature(first, rest, location)\n if signature.return_type != pytypes.NoneType or method_sig.endswith(\")void\"):\n logger.error(\n \"event signatures cannot include return types\",\n location=first.source_location,\n )\n arc4_args = signature.convert_args(rest)\n # emit requires a struct type, so generate one based on args\n struct_type = pytypes.StructType(\n base=pytypes.ARC4StructBaseType,\n name=signature.method_name,\n desc=None,\n fields={\n f\"field{idx}\": arg.pytype for idx, arg in enumerate(arc4_args, start=1)\n },\n frozen=True,\n source_location=location,\n )\n event_arg_eb = ARC4StructTypeBuilder(struct_type, location).call(\n args=arc4_args,\n arg_names=[None] * len(arc4_args),\n arg_kinds=[mypy.nodes.ARG_POS] * len(arc4_args),\n location=location,\n )\n event_name = struct_type.name.split(\".\")[-1]\n event_sig = f\"{event_name}{pytype_to_arc4(event_arg_eb.pytype, location)}\"\n emit = Emit(\n signature=event_sig,\n value=event_arg_eb.resolve(),\n source_location=location,\n )\n return NoneExpressionBuilder(emit)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/arc4\/emit.py","language":"Python","license":"NOASSERTION","size":2946} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import Expression, IndexExpression, NewArray, UInt64Constant\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import GenericTypeBuilder\nfrom puyapy.awst_build.eb._bytes_backed import BytesBackedTypeBuilder\nfrom puyapy.awst_build.eb._utils import constant_bool_and_error\nfrom puyapy.awst_build.eb.arc4._base import _ARC4ArrayExpressionBuilder\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import (\n InstanceBuilder,\n NodeBuilder,\n StaticSizedCollectionBuilder,\n)\nfrom puyapy.awst_build.eb.uint64 import UInt64ExpressionBuilder\n\n__all__ = [\n \"StaticArrayGenericTypeBuilder\",\n \"StaticArrayTypeBuilder\",\n \"StaticArrayExpressionBuilder\",\n]\n\nlogger = log.get_logger(__name__)\n\n\nclass StaticArrayGenericTypeBuilder(GenericTypeBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n if not args:\n raise CodeError(\"empty arrays require a type annotation to be instantiated\", location)\n element_type = expect.instance_builder(args[0], default=expect.default_raise).pytype\n array_size = len(args)\n typ = pytypes.GenericARC4StaticArrayType.parameterise(\n [element_type, pytypes.TypingLiteralType(value=array_size, source_location=None)],\n location,\n )\n values = tuple(expect.argument_of_type_else_dummy(a, element_type).resolve() for a in args)\n wtype = typ.wtype\n assert isinstance(wtype, wtypes.ARC4StaticArray)\n return StaticArrayExpressionBuilder(\n NewArray(values=values, wtype=wtype, source_location=location), typ\n )\n\n\nclass StaticArrayTypeBuilder(BytesBackedTypeBuilder[pytypes.ArrayType]):\n def __init__(self, typ: pytypes.PyType, location: SourceLocation):\n assert isinstance(typ, pytypes.ArrayType)\n assert typ.generic == pytypes.GenericARC4StaticArrayType\n assert typ.size is not None\n self._size = typ.size\n super().__init__(typ, location)\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n typ = self.produces()\n n_args = expect.exactly_n_args_of_type_else_dummy(args, typ.items, location, self._size)\n wtype = typ.wtype\n assert isinstance(wtype, wtypes.ARC4StaticArray)\n return StaticArrayExpressionBuilder(\n NewArray(\n values=tuple(arg.resolve() for arg in n_args),\n wtype=wtype,\n source_location=location,\n ),\n typ,\n )\n\n\nclass StaticArrayExpressionBuilder(_ARC4ArrayExpressionBuilder, StaticSizedCollectionBuilder):\n def __init__(self, expr: Expression, typ: pytypes.PyType):\n assert isinstance(typ, pytypes.ArrayType)\n size = typ.size\n assert size is not None\n self._size = size\n super().__init__(typ, expr)\n\n @typing.override\n def length(self, location: SourceLocation) -> InstanceBuilder:\n return UInt64ExpressionBuilder(UInt64Constant(value=self._size, source_location=location))\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n return constant_bool_and_error(value=self._size > 0, location=location, negate=negate)\n\n @typing.override\n def iterate_static(self) -> Sequence[InstanceBuilder]:\n base = self.single_eval().resolve()\n return [\n builder_for_instance(\n self.pytype.items,\n IndexExpression(\n base=base,\n index=UInt64Constant(value=idx, source_location=self.source_location),\n wtype=self.pytype.items_wtype,\n source_location=self.source_location,\n ),\n )\n for idx in range(self._size)\n ]\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/arc4\/static_array.py","language":"Python","license":"NOASSERTION","size":4403} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import algo_constants, log\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import (\n ARC4Decode,\n ARC4Encode,\n ArrayConcat,\n BytesAugmentedAssignment,\n BytesBinaryOperator,\n Expression,\n Statement,\n StringConstant,\n)\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import NotIterableInstanceExpressionBuilder\nfrom puyapy.awst_build.eb._bytes_backed import BytesBackedInstanceExpressionBuilder\nfrom puyapy.awst_build.eb._utils import compare_expr_bytes, dummy_statement\nfrom puyapy.awst_build.eb.arc4._base import ARC4TypeBuilder, arc4_bool_bytes\nfrom puyapy.awst_build.eb.interface import (\n BuilderBinaryOp,\n BuilderComparisonOp,\n InstanceBuilder,\n LiteralBuilder,\n NodeBuilder,\n)\nfrom puyapy.awst_build.eb.string import StringExpressionBuilder\n\n__all__ = [\n \"ARC4StringTypeBuilder\",\n \"ARC4StringExpressionBuilder\",\n]\n\nlogger = log.get_logger(__name__)\n\n\nclass ARC4StringTypeBuilder(ARC4TypeBuilder):\n def __init__(self, location: SourceLocation):\n super().__init__(pytypes.ARC4StringType, location)\n\n @typing.override\n def try_convert_literal(\n self, literal: LiteralBuilder, location: SourceLocation\n ) -> InstanceBuilder | None:\n match literal.value:\n case str(literal_value):\n try:\n bytes_value = literal_value.encode(\"utf8\")\n except UnicodeEncodeError as ex:\n logger.error( # noqa: TRY400\n f\"invalid UTF-8 string (encoding error: {ex})\",\n location=literal.source_location,\n )\n else:\n if len(bytes_value) > (algo_constants.MAX_BYTES_LENGTH - 2):\n logger.error(\n \"encoded string exceeds max byte array length\",\n location=literal.source_location,\n )\n return _arc4_str_literal(literal_value, location)\n return None\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.at_most_one_arg(args, location)\n match arg:\n case InstanceBuilder(pytype=pytypes.StrLiteralType):\n return arg.resolve_literal(ARC4StringTypeBuilder(location))\n case None:\n return _arc4_str_literal(\"\", location)\n case _:\n arg = expect.argument_of_type_else_dummy(arg, pytypes.StringType)\n return _from_native(arg, location)\n\n\nclass ARC4StringExpressionBuilder(\n NotIterableInstanceExpressionBuilder, BytesBackedInstanceExpressionBuilder\n):\n def __init__(self, expr: Expression):\n super().__init__(pytypes.ARC4StringType, expr)\n\n @typing.override\n def augmented_assignment(\n self, op: BuilderBinaryOp, rhs: InstanceBuilder, location: SourceLocation\n ) -> Statement:\n if op != BuilderBinaryOp.add:\n logger.error(f\"unsupported operator for type: {op.value!r}\", location=location)\n return dummy_statement(location)\n\n rhs = rhs.resolve_literal(ARC4StringTypeBuilder(rhs.source_location))\n if pytypes.StringType <= rhs.pytype:\n value = _from_native(rhs, rhs.source_location).resolve()\n else:\n value = expect.argument_of_type_else_dummy(rhs, self.pytype).resolve()\n\n return BytesAugmentedAssignment(\n target=self.resolve_lvalue(),\n op=BytesBinaryOperator.add,\n value=value,\n source_location=location,\n )\n\n @typing.override\n def binary_op(\n self,\n other: InstanceBuilder,\n op: BuilderBinaryOp,\n location: SourceLocation,\n *,\n reverse: bool,\n ) -> InstanceBuilder:\n if op != BuilderBinaryOp.add:\n return NotImplemented\n\n other = other.resolve_literal(ARC4StringTypeBuilder(other.source_location))\n if pytypes.ARC4StringType <= other.pytype:\n other_expr = other.resolve()\n elif pytypes.StringType <= other.pytype:\n other_expr = _from_native(other, other.source_location).resolve()\n else:\n return NotImplemented\n\n lhs = self.resolve()\n rhs = other_expr\n if reverse:\n (lhs, rhs) = (rhs, lhs)\n\n return ARC4StringExpressionBuilder(\n ArrayConcat(\n left=lhs,\n right=rhs,\n wtype=wtypes.arc4_string_alias,\n source_location=location,\n )\n )\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n other = other.resolve_literal(ARC4StringTypeBuilder(other.source_location))\n if pytypes.ARC4StringType <= other.pytype:\n lhs: InstanceBuilder = self\n elif pytypes.StringType <= other.pytype:\n # when comparing arc4 to native, easier to convert by stripping length prefix\n lhs = _string_to_native(self, self.source_location)\n else:\n return NotImplemented\n return compare_expr_bytes(\n lhs=lhs.resolve(),\n op=op,\n rhs=other.resolve(),\n source_location=location,\n )\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n return arc4_bool_bytes(\n self,\n false_bytes=b\"\\x00\\x00\",\n negate=negate,\n location=location,\n )\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n match name:\n case \"native\":\n return _string_to_native(self, location)\n case _:\n return super().member_access(name, location)\n\n\ndef _string_to_native(\n builder: InstanceBuilder, location: SourceLocation\n) -> StringExpressionBuilder:\n assert pytypes.ARC4StringType <= builder.pytype\n return StringExpressionBuilder(\n ARC4Decode(\n value=builder.resolve(),\n wtype=pytypes.StringType.wtype,\n source_location=location,\n )\n )\n\n\ndef _arc4_str_literal(value: str, location: SourceLocation) -> InstanceBuilder:\n return ARC4StringExpressionBuilder(\n StringConstant(value=value, source_location=location, wtype=wtypes.arc4_string_alias)\n )\n\n\ndef _from_native(eb: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n assert pytypes.StringType <= eb.pytype\n return ARC4StringExpressionBuilder(\n ARC4Encode(\n value=eb.resolve(),\n wtype=wtypes.arc4_string_alias,\n source_location=location,\n )\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/arc4\/string.py","language":"Python","license":"NOASSERTION","size":7076} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import Copy, Expression, FieldExpression, NewStruct\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder, NotIterableInstanceExpressionBuilder\nfrom puyapy.awst_build.eb._bytes_backed import (\n BytesBackedInstanceExpressionBuilder,\n BytesBackedTypeBuilder,\n)\nfrom puyapy.awst_build.eb._utils import compare_bytes, constant_bool_and_error, dummy_value\nfrom puyapy.awst_build.eb.arc4._base import CopyBuilder\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import BuilderComparisonOp, InstanceBuilder, NodeBuilder\nfrom puyapy.awst_build.utils import get_arg_mapping\n\nlogger = log.get_logger(__name__)\n\n\nclass ARC4StructTypeBuilder(BytesBackedTypeBuilder[pytypes.StructType]):\n def __init__(self, typ: pytypes.PyType, location: SourceLocation):\n assert isinstance(typ, pytypes.StructType)\n assert pytypes.ARC4StructBaseType < typ\n super().__init__(typ, location)\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n pytype = self.produces()\n field_mapping, any_missing = get_arg_mapping(\n required_positional_names=list(pytype.fields),\n args=args,\n arg_names=arg_names,\n call_location=location,\n raise_on_missing=False,\n )\n if any_missing:\n return dummy_value(pytype, location)\n\n values = {\n field_name: expect.argument_of_type_else_dummy(\n field_mapping[field_name], field_type\n ).resolve()\n for field_name, field_type in pytype.fields.items()\n }\n assert isinstance(pytype.wtype, wtypes.ARC4Struct)\n expr = NewStruct(wtype=pytype.wtype, values=values, source_location=location)\n return ARC4StructExpressionBuilder(expr, pytype)\n\n\nclass ARC4StructExpressionBuilder(\n NotIterableInstanceExpressionBuilder[pytypes.StructType],\n BytesBackedInstanceExpressionBuilder[pytypes.StructType],\n):\n def __init__(self, expr: Expression, typ: pytypes.PyType):\n assert isinstance(typ, pytypes.StructType)\n super().__init__(typ, expr)\n\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n match name:\n case field_name if field := self.pytype.fields.get(field_name):\n result_expr = FieldExpression(\n base=self.resolve(),\n name=field_name,\n source_location=location,\n )\n return builder_for_instance(field, result_expr)\n case \"copy\":\n return CopyBuilder(self.resolve(), location, self.pytype)\n case \"_replace\":\n return _Replace(self, self.pytype, location)\n case _:\n return super().member_access(name, location)\n\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n return compare_bytes(self=self, op=op, other=other, source_location=location)\n\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n return constant_bool_and_error(value=True, location=location, negate=negate)\n\n\nclass _Replace(FunctionBuilder):\n def __init__(\n self,\n instance: ARC4StructExpressionBuilder,\n struct_type: pytypes.StructType,\n location: SourceLocation,\n ):\n super().__init__(location)\n self.instance = instance\n self.struct_type = struct_type\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n pytype = self.struct_type\n field_mapping, _ = get_arg_mapping(\n optional_kw_only=list(pytype.fields),\n args=args,\n arg_names=arg_names,\n call_location=location,\n raise_on_missing=False,\n )\n base_expr = self.instance.single_eval().resolve()\n values = dict[str, Expression]()\n for field_name, field_pytype in pytype.fields.items():\n new_value = field_mapping.get(field_name)\n if new_value is not None:\n item_builder = expect.argument_of_type_else_dummy(new_value, field_pytype)\n item = item_builder.resolve()\n else:\n field_wtype = field_pytype.checked_wtype(location)\n item = FieldExpression(base=base_expr, name=field_name, source_location=location)\n if not field_wtype.immutable:\n logger.error(\n f\"mutable field {field_name!r} requires explicit copy\", location=location\n )\n # implicitly create a copy node so that there is only one error\n item = Copy(value=item, source_location=location)\n values[field_name] = item\n new_tuple = NewStruct(values=values, wtype=pytype.wtype, source_location=location)\n return ARC4StructExpressionBuilder(new_tuple, pytype)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/arc4\/struct.py","language":"Python","license":"NOASSERTION","size":5563} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst.nodes import ARC4Decode, ARC4Encode, Expression, TupleItemExpression\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import GenericTypeBuilder\nfrom puyapy.awst_build.eb._bytes_backed import BytesBackedInstanceExpressionBuilder\nfrom puyapy.awst_build.eb._utils import compare_bytes, constant_bool_and_error, dummy_value\nfrom puyapy.awst_build.eb.arc4._base import ARC4TypeBuilder, CopyBuilder\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import (\n BuilderComparisonOp,\n InstanceBuilder,\n LiteralBuilder,\n NodeBuilder,\n StaticSizedCollectionBuilder,\n)\nfrom puyapy.awst_build.eb.tuple import TupleExpressionBuilder\n\nlogger = log.get_logger(__name__)\n\n\nclass ARC4TupleGenericTypeBuilder(GenericTypeBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.exactly_one_arg(args, location, default=expect.default_raise)\n match arg:\n case InstanceBuilder(pytype=pytypes.TupleType(items=items)):\n typ = pytypes.GenericARC4TupleType.parameterise(items, location)\n return ARC4TupleExpressionBuilder(\n ARC4Encode(value=arg.resolve(), wtype=typ.wtype, source_location=location), typ\n )\n case _:\n # don't know expected type, so raise\n expect.not_this_type(arg, default=expect.default_raise)\n\n\nclass ARC4TupleTypeBuilder(ARC4TypeBuilder[pytypes.ARC4TupleType]):\n def __init__(self, typ: pytypes.PyType, location: SourceLocation):\n assert isinstance(typ, pytypes.ARC4TupleType)\n super().__init__(typ, location)\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n typ = self.produces()\n native_type = pytypes.GenericTupleType.parameterise(typ.items, location)\n arg = expect.exactly_one_arg(\n args, location, default=expect.default_dummy_value(native_type)\n )\n wtype = typ.wtype\n if not wtype.can_encode_type(arg.pytype.checked_wtype(location)):\n arg = expect.not_this_type(arg, default=expect.default_dummy_value(native_type))\n return ARC4TupleExpressionBuilder(\n ARC4Encode(value=arg.resolve(), wtype=wtype, source_location=location), typ\n )\n\n\nclass ARC4TupleExpressionBuilder(\n BytesBackedInstanceExpressionBuilder[pytypes.ARC4TupleType], StaticSizedCollectionBuilder\n):\n def __init__(self, expr: Expression, typ: pytypes.PyType):\n assert isinstance(typ, pytypes.ARC4TupleType)\n super().__init__(typ, expr)\n\n @typing.override\n def index(self, index: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n match index:\n case LiteralBuilder(value=int(index_value)):\n pass\n case InstanceBuilder(pytype=pytypes.IntLiteralType):\n raise CodeError(\"tuple index must be a simple int literal\", index.source_location)\n case other:\n expect.not_this_type(other, default=expect.default_raise)\n try:\n item_typ = self.pytype.items[index_value]\n except IndexError:\n raise CodeError(\"index out of bounds\", index.source_location) from None\n return builder_for_instance(\n item_typ,\n TupleItemExpression(\n base=self.resolve(),\n index=index_value,\n source_location=location,\n ),\n )\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n return constant_bool_and_error(value=True, location=location, negate=negate)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n match name:\n case \"native\":\n native_pytype = pytypes.GenericTupleType.parameterise(self.pytype.items, location)\n native_wtype = native_pytype.checked_wtype(location)\n result_expr: Expression = ARC4Decode(\n value=self.resolve(),\n wtype=native_wtype,\n source_location=location,\n )\n return TupleExpressionBuilder(result_expr, native_pytype)\n case \"copy\":\n return CopyBuilder(self.resolve(), location, self.pytype)\n case _:\n return super().member_access(name, location)\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n return compare_bytes(self=self, op=op, other=other, source_location=location)\n\n @typing.override\n def contains(self, item: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n logger.error(\n \"item containment with ARC4 tuples is currently unsupported\", location=location\n )\n return dummy_value(pytypes.BoolType, location)\n\n @typing.override\n def iterate(self) -> typing.Never:\n # could only support for homogenous types anyway, in which case use a StaticArray?\n raise CodeError(\"iterating ARC4 tuples is currently unsupported\", self.source_location)\n\n @typing.override\n def iterate_static(self) -> Sequence[InstanceBuilder]:\n base = self.single_eval().resolve()\n return [\n builder_for_instance(\n item_type,\n TupleItemExpression(base=base, index=idx, source_location=self.source_location),\n )\n for idx, item_type in enumerate(self.pytype.items)\n ]\n\n @typing.override\n def iterable_item_type(self) -> typing.Never:\n self.iterate()\n\n @typing.override\n def slice_index(\n self,\n begin_index: InstanceBuilder | None,\n end_index: InstanceBuilder | None,\n stride: InstanceBuilder | None,\n location: SourceLocation,\n ) -> InstanceBuilder:\n raise CodeError(\"slicing ARC4 tuples is currently unsupported\", location)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/arc4\/tuple.py","language":"Python","license":"NOASSERTION","size":6588} {"code":"import decimal\nimport typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import DecimalConstant, Expression\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import NotIterableInstanceExpressionBuilder\nfrom puyapy.awst_build.eb._bytes_backed import BytesBackedInstanceExpressionBuilder\nfrom puyapy.awst_build.eb._utils import compare_bytes\nfrom puyapy.awst_build.eb.arc4._base import ARC4TypeBuilder, arc4_bool_bytes\nfrom puyapy.awst_build.eb.interface import (\n BuilderComparisonOp,\n InstanceBuilder,\n LiteralBuilder,\n NodeBuilder,\n)\n\n__all__ = [\n \"UFixedNxMTypeBuilder\",\n \"UFixedNxMExpressionBuilder\",\n]\n\nlogger = log.get_logger(__name__)\n\n\nclass UFixedNxMTypeBuilder(ARC4TypeBuilder):\n @typing.override\n def try_convert_literal(\n self, literal: LiteralBuilder, location: SourceLocation\n ) -> InstanceBuilder | None:\n match literal.value:\n case str(literal_value):\n result = self._str_to_decimal_constant(\n literal_value, error_location=literal.source_location, location=location\n )\n return UFixedNxMExpressionBuilder(result, self.produces())\n return None\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.at_most_one_arg(args, location)\n if arg is None:\n result = self._str_to_decimal_constant(\"0.0\", location=location)\n return UFixedNxMExpressionBuilder(result, self.produces())\n\n arg = expect.argument_of_type(arg, pytypes.StrLiteralType, default=expect.default_raise)\n return arg.resolve_literal(UFixedNxMTypeBuilder(self.produces(), location))\n\n def _str_to_decimal_constant(\n self,\n literal_value: str,\n *,\n location: SourceLocation,\n error_location: SourceLocation | None = None,\n ) -> DecimalConstant:\n error_location = location or error_location\n fixed_wtype = self.produces().wtype\n assert isinstance(fixed_wtype, wtypes.ARC4UFixedNxM)\n\n with decimal.localcontext(\n decimal.Context(\n prec=160,\n traps=[\n decimal.Rounded,\n decimal.InvalidOperation,\n decimal.Overflow,\n decimal.DivisionByZero,\n ],\n )\n ):\n try:\n d = decimal.Decimal(literal_value)\n except ArithmeticError:\n logger.error(\"invalid decimal literal\", location=error_location) # noqa: TRY400\n d = decimal.Decimal()\n try:\n q = d.quantize(decimal.Decimal(f\"1e-{fixed_wtype.m}\"))\n except ArithmeticError:\n logger.error( # noqa: TRY400\n \"invalid decimal constant (wrong precision)\", location=error_location\n )\n q = decimal.Decimal(\"0.\" + \"0\" * fixed_wtype.m)\n\n sign, digits, exponent = q.as_tuple()\n if sign != 0: # is negative\n logger.error(\n \"invalid decimal constant (value is negative)\", location=error_location\n )\n if not isinstance(exponent, int): # is infinite\n logger.error(\n \"invalid decimal constant (value is infinite)\", location=error_location\n )\n adjusted_int = int(\"\".join(map(str, digits)))\n if adjusted_int.bit_length() > fixed_wtype.n:\n logger.error(\"invalid decimal constant (too many bits)\", location=error_location)\n result = DecimalConstant(value=q, wtype=fixed_wtype, source_location=location)\n return result\n\n\nclass UFixedNxMExpressionBuilder(\n NotIterableInstanceExpressionBuilder[pytypes.ARC4UFixedNxMType],\n BytesBackedInstanceExpressionBuilder[pytypes.ARC4UFixedNxMType],\n):\n def __init__(self, expr: Expression, typ: pytypes.PyType):\n assert isinstance(typ, pytypes.ARC4UFixedNxMType)\n assert typ.generic in (\n pytypes.GenericARC4UFixedNxMType,\n pytypes.GenericARC4BigUFixedNxMType,\n )\n super().__init__(typ, expr)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n return arc4_bool_bytes(\n self,\n false_bytes=b\"\\x00\" * (self.pytype.bits \/\/ 8),\n negate=negate,\n location=location,\n )\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n other = other.resolve_literal(UFixedNxMTypeBuilder(self.pytype, other.source_location))\n return compare_bytes(op=op, self=self, other=other, source_location=location)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/arc4\/ufixed.py","language":"Python","license":"NOASSERTION","size":5138} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import (\n ARC4Decode,\n ARC4Encode,\n Expression,\n IntegerConstant,\n NumericComparison,\n NumericComparisonExpression,\n ReinterpretCast,\n)\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import intrinsic_factory, pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import NotIterableInstanceExpressionBuilder\nfrom puyapy.awst_build.eb._bytes_backed import BytesBackedInstanceExpressionBuilder\nfrom puyapy.awst_build.eb.arc4._base import ARC4TypeBuilder, arc4_bool_bytes\nfrom puyapy.awst_build.eb.bool import BoolExpressionBuilder\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import (\n BuilderComparisonOp,\n InstanceBuilder,\n LiteralBuilder,\n NodeBuilder,\n)\n\n__all__ = [\n \"UIntNTypeBuilder\",\n \"UIntNExpressionBuilder\",\n]\n\nlogger = log.get_logger(__name__)\n\n\nclass UIntNTypeBuilder(ARC4TypeBuilder[pytypes.ARC4UIntNType]):\n def __init__(self, pytype: pytypes.PyType, location: SourceLocation):\n assert isinstance(pytype, pytypes.ARC4UIntNType)\n super().__init__(pytype, location)\n\n @typing.override\n def try_convert_literal(\n self, literal: LiteralBuilder, location: SourceLocation\n ) -> InstanceBuilder | None:\n pytype = self.produces()\n match literal.value:\n case int(int_value):\n if int_value < 0 or int_value.bit_length() > pytype.bits:\n logger.error(f\"invalid {pytype} value\", location=literal.source_location)\n # take int() of the value since it could match a bool also\n expr = IntegerConstant(\n value=int(int_value), wtype=pytype.wtype, source_location=location\n )\n return UIntNExpressionBuilder(expr, pytype)\n return None\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.at_most_one_arg(args, location)\n typ = self.produces()\n wtype = typ.wtype\n match arg:\n case InstanceBuilder(pytype=pytypes.IntLiteralType):\n return arg.resolve_literal(UIntNTypeBuilder(typ, location))\n case None:\n expr: Expression = IntegerConstant(value=0, wtype=wtype, source_location=location)\n case _:\n encodeable = expect.argument_of_type_else_dummy(\n arg, pytypes.UInt64Type, pytypes.BigUIntType, pytypes.BoolType\n )\n expr = ARC4Encode(\n value=encodeable.resolve(), wtype=wtype, source_location=location\n )\n return UIntNExpressionBuilder(expr, typ)\n\n\nclass UIntNExpressionBuilder(\n NotIterableInstanceExpressionBuilder[pytypes.ARC4UIntNType],\n BytesBackedInstanceExpressionBuilder[pytypes.ARC4UIntNType],\n):\n def __init__(self, expr: Expression, typ: pytypes.PyType):\n assert isinstance(typ, pytypes.ARC4UIntNType)\n super().__init__(typ, expr)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n match name:\n case \"native\":\n result_expr = ARC4Decode(\n value=self.resolve(),\n wtype=self.pytype.native_type.wtype,\n source_location=location,\n )\n return builder_for_instance(self.pytype.native_type, result_expr)\n case _:\n return super().member_access(name, location)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n return arc4_bool_bytes(\n self,\n false_bytes=b\"\\x00\" * (self.pytype.bits \/\/ 8),\n location=location,\n negate=negate,\n )\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n other = other.resolve_literal(UIntNTypeBuilder(self.pytype, other.source_location))\n if pytypes.BigUIntType <= other.pytype:\n other_expr = other.resolve()\n elif other.pytype.is_type_or_subtype(pytypes.BoolType, pytypes.UInt64Type):\n other_expr = intrinsic_factory.itob_as(other.resolve(), wtypes.biguint_wtype, location)\n elif isinstance(other.pytype, pytypes.ARC4UIntNType):\n other_expr = ReinterpretCast(\n expr=other.resolve(),\n wtype=wtypes.biguint_wtype,\n source_location=other.source_location,\n )\n else:\n return NotImplemented\n cmp_expr = NumericComparisonExpression(\n operator=NumericComparison(op.value),\n lhs=ReinterpretCast(\n expr=self.resolve(),\n wtype=wtypes.biguint_wtype,\n source_location=self.source_location,\n ),\n rhs=other_expr,\n source_location=location,\n )\n return BoolExpressionBuilder(cmp_expr)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/arc4\/uint.py","language":"Python","license":"NOASSERTION","size":5340} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import Expression\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb._base import GenericTypeBuilder\nfrom puyapy.awst_build.eb.interface import InstanceBuilder, NodeBuilder, TypeBuilder\n\n\nclass ArrayGenericTypeBuilder(GenericTypeBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n raise NotImplementedError\n\n\nclass ArrayTypeBuilder(TypeBuilder[pytypes.ArrayType]):\n def __init__(self, typ: pytypes.PyType, location: SourceLocation):\n assert isinstance(typ, pytypes.ArrayType)\n assert typ.generic == pytypes.GenericArrayType\n wtype = typ.wtype\n assert isinstance(wtype, wtypes.WArray)\n self._wtype = wtype\n super().__init__(typ, location)\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n raise NotImplementedError\n\n\ndef ArrayExpressionBuilder(expr: Expression, typ: pytypes.PyType) -> typing.Never: # noqa: N802\n raise NotImplementedError\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/array.py","language":"Python","license":"NOASSERTION","size":1441} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport attrs\nimport mypy.nodes\n\nfrom puya import algo_constants, log\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import (\n BigUIntAugmentedAssignment,\n BigUIntBinaryOperation,\n BigUIntBinaryOperator,\n BigUIntConstant,\n Expression,\n NumericComparison,\n NumericComparisonExpression,\n Statement,\n)\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import intrinsic_factory, pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import NotIterableInstanceExpressionBuilder\nfrom puyapy.awst_build.eb._bytes_backed import (\n BytesBackedInstanceExpressionBuilder,\n BytesBackedTypeBuilder,\n)\nfrom puyapy.awst_build.eb._utils import dummy_statement\nfrom puyapy.awst_build.eb.bool import BoolExpressionBuilder\nfrom puyapy.awst_build.eb.interface import (\n BuilderBinaryOp,\n BuilderComparisonOp,\n BuilderUnaryOp,\n InstanceBuilder,\n LiteralBuilder,\n NodeBuilder,\n)\n\nlogger = log.get_logger(__name__)\n\n\nclass BigUIntTypeBuilder(BytesBackedTypeBuilder):\n def __init__(self, location: SourceLocation):\n super().__init__(pytypes.BigUIntType, location)\n\n @typing.override\n def try_convert_literal(\n self, literal: LiteralBuilder, location: SourceLocation\n ) -> InstanceBuilder | None:\n match literal.value:\n case int(int_value):\n pytype = self.produces()\n if int_value < 0 or int_value.bit_length() > algo_constants.MAX_BIGUINT_BITS:\n logger.error(f\"invalid {pytype} value\", location=literal.source_location)\n expr = BigUIntConstant(value=int(int_value), source_location=location)\n return BigUIntExpressionBuilder(expr)\n return None\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.at_most_one_arg(args, location)\n match arg:\n case InstanceBuilder(pytype=pytypes.IntLiteralType):\n return arg.resolve_literal(converter=BigUIntTypeBuilder(location))\n case None:\n value: Expression = BigUIntConstant(value=0, source_location=location)\n case _:\n arg = expect.argument_of_type_else_dummy(arg, pytypes.UInt64Type)\n value = _uint64_to_biguint(arg, location)\n return BigUIntExpressionBuilder(value)\n\n\nclass BigUIntExpressionBuilder(\n NotIterableInstanceExpressionBuilder, BytesBackedInstanceExpressionBuilder\n):\n def __init__(self, expr: Expression):\n super().__init__(pytypes.BigUIntType, expr)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n cmp_expr = NumericComparisonExpression(\n lhs=self.resolve(),\n operator=NumericComparison.eq if negate else NumericComparison.ne,\n rhs=BigUIntConstant(value=0, source_location=location),\n source_location=location,\n )\n return BoolExpressionBuilder(cmp_expr)\n\n @typing.override\n def unary_op(self, op: BuilderUnaryOp, location: SourceLocation) -> InstanceBuilder:\n if op == BuilderUnaryOp.positive:\n # unary + is allowed, but for the current types it has no real impact\n # so just expand the existing expression to include the unary operator\n return BigUIntExpressionBuilder(attrs.evolve(self.resolve(), source_location=location))\n return super().unary_op(op, location)\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n other = other.resolve_literal(converter=BigUIntTypeBuilder(other.source_location))\n if pytypes.BigUIntType <= other.pytype:\n other_expr = other.resolve()\n elif pytypes.UInt64Type <= other.pytype:\n other_expr = _uint64_to_biguint(other, location)\n else:\n return NotImplemented\n cmp_expr = NumericComparisonExpression(\n source_location=location,\n lhs=self.resolve(),\n operator=NumericComparison(op.value),\n rhs=other_expr,\n )\n return BoolExpressionBuilder(cmp_expr)\n\n @typing.override\n def binary_op(\n self,\n other: InstanceBuilder,\n op: BuilderBinaryOp,\n location: SourceLocation,\n *,\n reverse: bool,\n ) -> InstanceBuilder:\n biguint_op = _translate_biguint_math_operator(op, location)\n if biguint_op is None:\n return NotImplemented\n other = other.resolve_literal(converter=BigUIntTypeBuilder(other.source_location))\n if pytypes.BigUIntType <= other.pytype:\n other_expr = other.resolve()\n elif pytypes.UInt64Type <= other.pytype:\n other_expr = _uint64_to_biguint(other, location)\n else:\n return NotImplemented\n lhs = self.resolve()\n rhs = other_expr\n if reverse:\n (lhs, rhs) = (rhs, lhs)\n bin_op_expr = BigUIntBinaryOperation(\n source_location=location, left=lhs, op=biguint_op, right=rhs\n )\n return BigUIntExpressionBuilder(bin_op_expr)\n\n @typing.override\n def augmented_assignment(\n self, op: BuilderBinaryOp, rhs: InstanceBuilder, location: SourceLocation\n ) -> Statement:\n biguint_op = _translate_biguint_math_operator(op, location)\n if biguint_op is None:\n logger.error(f\"unsupported operator for type: {op.value!r}\", location=location)\n return dummy_statement(location)\n if pytypes.UInt64Type <= rhs.pytype:\n value = _uint64_to_biguint(rhs, location)\n else:\n value = expect.argument_of_type_else_dummy(\n rhs, self.pytype, resolve_literal=True\n ).resolve()\n target = self.resolve_lvalue()\n return BigUIntAugmentedAssignment(\n source_location=location,\n target=target,\n value=value,\n op=biguint_op,\n )\n\n\ndef _translate_biguint_math_operator(\n operator: BuilderBinaryOp, loc: SourceLocation\n) -> BigUIntBinaryOperator | None:\n if operator is BuilderBinaryOp.div:\n logger.error(\n (\n \"To maintain semantic compatibility with Python, \"\n \"only the truncating division operator (\/\/) is supported \"\n ),\n location=loc,\n )\n # continue traversing code to generate any further errors\n operator = BuilderBinaryOp.floor_div\n try:\n return BigUIntBinaryOperator(operator.value)\n except ValueError:\n return None\n\n\ndef _uint64_to_biguint(arg_in: InstanceBuilder, location: SourceLocation) -> Expression:\n return intrinsic_factory.itob_as(arg_in.resolve(), wtypes.biguint_wtype, location)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/biguint.py","language":"Python","license":"NOASSERTION","size":7032} {"code":"import typing\n\nfrom puya.awst.nodes import (\n BinaryBooleanOperator,\n BooleanBinaryOperation,\n ConditionalExpression,\n Expression,\n Not,\n)\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb.bool import BoolExpressionBuilder\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import (\n BuilderBinaryOp,\n BuilderComparisonOp,\n BuilderUnaryOp,\n InstanceBuilder,\n NodeBuilder,\n TypeBuilder,\n)\nfrom puyapy.awst_build.utils import determine_base_type\n\n\nclass BinaryBoolOpBuilder(InstanceBuilder):\n \"\"\"\n This builder works to defer the evaluation of a boolean binary op (ie and\/or), because\n in some cases (unions, python literals) we can only successfully evaluate in certain contexts.\n\n For example:\n a = Bytes(...)\n b = UInt64(...)\n if a or b: # this is fine, even though `a or b` produces `Bytes | UInt64`\n ...\n c = a or b # compiler error\n\n You wouldn't be able to do anything with c, since in general we can't know at compile\n time what the type of c is, and the AVM doesn't provide any type introspection.\n Even if there was an op that said whether a stack item or a scratch slot etc held\n a bytes[] or a uint64, there are differences between logical types and physical types\n that need to be accounted for - for example, biguint is a bytes[] but we would need\n to use a different equality op b== instead of ==\n \"\"\"\n\n def __init__(\n self,\n left: InstanceBuilder,\n right: InstanceBuilder,\n op: BinaryBooleanOperator,\n location: SourceLocation,\n *,\n result_type: pytypes.PyType | None = None,\n ):\n super().__init__(location)\n if result_type is None:\n # if either left or right is already a union, just produce another union\n if isinstance(left.pytype, pytypes.UnionType) or isinstance(\n right.pytype, pytypes.UnionType\n ):\n # note if left and\/or right are unions this constructor will expand them for us\n result_type = pytypes.UnionType([left.pytype, right.pytype], location)\n else:\n # otherwise, left and right are both non-union types, so try and\n # compute a common base type, falling back to a union if not possible\n result_type = determine_base_type(left.pytype, right.pytype, location=location)\n self._result_type = result_type\n self._left = left\n self._right = right\n self._op = op\n\n @typing.override\n @property\n def pytype(self) -> pytypes.PyType:\n return self._result_type\n\n @typing.override\n def single_eval(self) -> InstanceBuilder:\n left = self._left.single_eval()\n right = self._right.single_eval()\n return self._evolve_builders(left, right, recalculate_type=False)\n\n @typing.override\n def resolve_literal(self, converter: TypeBuilder) -> InstanceBuilder:\n left = self._left.resolve_literal(converter)\n right = self._right.resolve_literal(converter)\n return self._evolve_builders(left, right)\n\n @typing.override\n def try_resolve_literal(self, converter: TypeBuilder) -> InstanceBuilder | None:\n left = self._left.try_resolve_literal(converter)\n right = self._right.try_resolve_literal(converter)\n if left is None or right is None:\n return None\n return self._evolve_builders(left, right)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n bool_left = self._left.bool_eval(self._left.source_location).resolve()\n bool_right = self._right.bool_eval(self._right.source_location).resolve()\n result_expr: Expression = BooleanBinaryOperation(\n left=bool_left, op=self._op, right=bool_right, source_location=location\n )\n if negate:\n result_expr = Not(expr=result_expr, source_location=location)\n return BoolExpressionBuilder(result_expr)\n\n @typing.override\n def bool_binary_op(\n self, other: InstanceBuilder, op: BinaryBooleanOperator, location: SourceLocation\n ) -> InstanceBuilder:\n return BinaryBoolOpBuilder(left=self, right=other, op=op, location=location)\n\n @typing.override\n def resolve(self) -> Expression:\n if isinstance(self.pytype, pytypes.UnionType):\n raise CodeError(\n \"expression would produce a union type,\"\n \" which isn't supported unless evaluating a boolean condition\",\n self.source_location,\n )\n result_wtype = self.pytype.checked_wtype(self.source_location)\n\n # (left:uint64 and right:uint64) => left_cache if not bool(left_cache := left) else right\n # (left:uint64 or right:uint64) => left_cache if bool(left_cache := left) else right\n left_cache = self._left.single_eval()\n condition = left_cache.bool_eval(\n self.source_location, negate=self._op is BinaryBooleanOperator.and_\n )\n expr_result = ConditionalExpression(\n condition=condition.resolve(),\n true_expr=left_cache.resolve(),\n false_expr=self._right.resolve(),\n wtype=result_wtype,\n source_location=self.source_location,\n )\n return expr_result\n\n def _evolve_builders(\n self, left: InstanceBuilder, right: InstanceBuilder, *, recalculate_type: bool = True\n ) -> InstanceBuilder:\n return BinaryBoolOpBuilder(\n left=left,\n right=right,\n op=self._op,\n location=self.source_location,\n result_type=None if recalculate_type else self.pytype,\n )\n\n # region Invalid Python syntax\n @typing.override\n def resolve_lvalue(self) -> typing.Never:\n raise CodeError(\n # message copied from Python\n \"cannot assign to expression here. Maybe you meant '==' instead of '='?\",\n self.source_location,\n )\n\n @typing.override\n def delete(self, location: SourceLocation) -> typing.Never:\n raise CodeError(\n # message copied from Python\n \"cannot delete expression\",\n location,\n )\n\n @typing.override\n def augmented_assignment(\n self, op: BuilderBinaryOp, right: InstanceBuilder, location: SourceLocation\n ) -> typing.Never:\n raise CodeError(\n # copied (and trimmed) from Python\n \"illegal expression for augmented assignment\",\n location,\n )\n\n # endregion\n\n # region Forward to resolved builder\n def _resolve_builder(self) -> InstanceBuilder:\n expr = self.resolve()\n return builder_for_instance(self.pytype, expr)\n\n @typing.override\n def unary_op(self, op: BuilderUnaryOp, location: SourceLocation) -> InstanceBuilder:\n return self._resolve_builder().unary_op(op, location)\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n return self._resolve_builder().compare(other, op, location)\n\n @typing.override\n def binary_op(\n self,\n other: InstanceBuilder,\n op: BuilderBinaryOp,\n location: SourceLocation,\n *,\n reverse: bool,\n ) -> InstanceBuilder:\n return self._resolve_builder().binary_op(other, op, location, reverse=reverse)\n\n @typing.override\n def contains(self, item: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n return self._resolve_builder().contains(item, location)\n\n @typing.override\n def iterate(self) -> Expression:\n return self._resolve_builder().iterate()\n\n @typing.override\n def iterable_item_type(self) -> pytypes.PyType:\n return self._resolve_builder().iterable_item_type()\n\n @typing.override\n def index(self, index: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n return self._resolve_builder().index(index, location)\n\n @typing.override\n def slice_index(\n self,\n begin_index: InstanceBuilder | None,\n end_index: InstanceBuilder | None,\n stride: InstanceBuilder | None,\n location: SourceLocation,\n ) -> InstanceBuilder:\n return self._resolve_builder().slice_index(begin_index, end_index, stride, location)\n\n @typing.override\n def to_bytes(self, location: SourceLocation) -> Expression:\n return self._resolve_builder().to_bytes(location)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n return self._resolve_builder().member_access(name, location)\n\n # endregion\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/binary_bool_op.py","language":"Python","license":"NOASSERTION","size":8845} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst.nodes import (\n BinaryBooleanOperator,\n BoolConstant,\n BooleanBinaryOperation,\n Expression,\n Not,\n NumericComparison,\n NumericComparisonExpression,\n)\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import intrinsic_factory, pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import NotIterableInstanceExpressionBuilder\nfrom puyapy.awst_build.eb.interface import (\n BuilderComparisonOp,\n InstanceBuilder,\n LiteralBuilder,\n NodeBuilder,\n TypeBuilder,\n)\n\nlogger = log.get_logger(__name__)\n\n\nclass BoolTypeBuilder(TypeBuilder):\n def __init__(self, location: SourceLocation):\n super().__init__(pytypes.BoolType, location)\n\n @typing.override\n def try_convert_literal(\n self, literal: LiteralBuilder, location: SourceLocation\n ) -> InstanceBuilder | None:\n match literal.value:\n case bool(literal_value):\n expr = BoolConstant(value=literal_value, source_location=location)\n return BoolExpressionBuilder(expr)\n return None\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.at_most_one_arg(args, location)\n match arg:\n case None:\n false = BoolConstant(value=False, source_location=location)\n return BoolExpressionBuilder(false)\n case InstanceBuilder(pytype=pytypes.BoolType):\n return arg\n case _:\n return arg.bool_eval(location)\n\n\nclass BoolExpressionBuilder(NotIterableInstanceExpressionBuilder):\n def __init__(self, expr: Expression):\n super().__init__(pytypes.BoolType, expr)\n\n @typing.override\n def to_bytes(self, location: SourceLocation) -> Expression:\n return intrinsic_factory.itob(self.resolve(), location)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n if not negate:\n return self\n return BoolExpressionBuilder(Not(location, self.resolve()))\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n if other.pytype != pytypes.BoolType:\n return NotImplemented\n cmp_expr = NumericComparisonExpression(\n source_location=location,\n lhs=self.resolve(),\n operator=NumericComparison(op.value),\n rhs=other.resolve(),\n )\n return BoolExpressionBuilder(cmp_expr)\n\n @typing.override\n def bool_binary_op(\n self, other: InstanceBuilder, op: BinaryBooleanOperator, location: SourceLocation\n ) -> InstanceBuilder:\n if other.pytype != pytypes.BoolType:\n return super().bool_binary_op(other, op, location)\n result = BooleanBinaryOperation(\n left=self.resolve(),\n op=op,\n right=other.resolve(),\n source_location=location,\n )\n return BoolExpressionBuilder(result)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/bool.py","language":"Python","license":"NOASSERTION","size":3320} {"code":"import base64\nimport typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import algo_constants, log, utils\nfrom puya.awst.nodes import (\n BytesAugmentedAssignment,\n BytesBinaryOperation,\n BytesBinaryOperator,\n BytesConstant,\n BytesEncoding,\n BytesUnaryOperation,\n BytesUnaryOperator,\n CallArg,\n Expression,\n IndexExpression,\n IntersectionSliceExpression,\n PuyaLibCall,\n PuyaLibFunction,\n Statement,\n)\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import intrinsic_factory, pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder, InstanceExpressionBuilder\nfrom puyapy.awst_build.eb._utils import (\n compare_bytes,\n dummy_statement,\n dummy_value,\n resolve_negative_literal_index,\n)\nfrom puyapy.awst_build.eb.bool import BoolExpressionBuilder\nfrom puyapy.awst_build.eb.interface import (\n BuilderBinaryOp,\n BuilderComparisonOp,\n BuilderUnaryOp,\n InstanceBuilder,\n LiteralBuilder,\n NodeBuilder,\n TypeBuilder,\n)\nfrom puyapy.awst_build.eb.uint64 import UInt64ExpressionBuilder\n\nlogger = log.get_logger(__name__)\n\n\nclass BytesTypeBuilder(TypeBuilder):\n def __init__(self, location: SourceLocation):\n super().__init__(pytypes.BytesType, location)\n\n @typing.override\n def try_convert_literal(\n self, literal: LiteralBuilder, location: SourceLocation\n ) -> InstanceBuilder | None:\n match literal.value:\n case bytes(literal_value):\n if len(literal_value) > algo_constants.MAX_BYTES_LENGTH:\n logger.error(\n \"bytes constant exceeds max length\", location=literal.source_location\n )\n\n expr = BytesConstant(\n value=literal_value, encoding=BytesEncoding.unknown, source_location=location\n )\n return BytesExpressionBuilder(expr)\n return None\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.at_most_one_arg(args, location)\n match arg:\n case InstanceBuilder(pytype=pytypes.BytesLiteralType):\n return arg.resolve_literal(BytesTypeBuilder(location))\n case None:\n value = BytesConstant(\n value=b\"\", encoding=BytesEncoding.unknown, source_location=location\n )\n return BytesExpressionBuilder(value)\n case other:\n return expect.not_this_type(\n other, default=expect.default_dummy_value(self.produces())\n )\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n \"\"\"Handle self.name\"\"\"\n match name:\n case \"from_base32\":\n return _FromEncodedStr(location, BytesEncoding.base32)\n case \"from_base64\":\n return _FromEncodedStr(location, BytesEncoding.base64)\n case \"from_hex\":\n return _FromEncodedStr(location, BytesEncoding.base16)\n case _:\n return super().member_access(name, location)\n\n\nclass _FromEncodedStr(FunctionBuilder):\n def __init__(\n self,\n location: SourceLocation,\n encoding: typing.Literal[BytesEncoding.base16, BytesEncoding.base32, BytesEncoding.base64],\n ):\n super().__init__(location=location)\n self.encoding = encoding\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.exactly_one_arg(args, location, default=expect.default_none)\n if arg is not None:\n encoded_value = expect.simple_string_literal(arg, default=expect.default_none)\n if encoded_value is not None:\n match self.encoding:\n case BytesEncoding.base64:\n if not utils.valid_base64(encoded_value):\n logger.error(\"invalid base64 value\", location=arg.source_location)\n bytes_value = b\"\"\n else:\n bytes_value = base64.b64decode(encoded_value)\n case BytesEncoding.base32:\n if not utils.valid_base32(encoded_value):\n logger.error(\"invalid base32 value\", location=arg.source_location)\n bytes_value = b\"\"\n else:\n bytes_value = base64.b32decode(encoded_value)\n case BytesEncoding.base16:\n encoded_value = encoded_value.upper()\n if not utils.valid_base16(encoded_value):\n logger.error(\"invalid base16 value\", location=arg.source_location)\n bytes_value = b\"\"\n else:\n bytes_value = base64.b16decode(encoded_value)\n case _:\n typing.assert_never(self.encoding)\n expr = BytesConstant(\n source_location=location,\n value=bytes_value,\n encoding=self.encoding,\n )\n return BytesExpressionBuilder(expr)\n return dummy_value(pytypes.BytesType, location)\n\n\nclass BytesExpressionBuilder(InstanceExpressionBuilder[pytypes.RuntimeType]):\n def __init__(self, expr: Expression):\n super().__init__(pytypes.BytesType, expr)\n\n @typing.override\n def to_bytes(self, location: SourceLocation) -> Expression:\n return self.resolve()\n\n def length(self, location: SourceLocation) -> InstanceBuilder:\n len_call = intrinsic_factory.bytes_len(expr=self.resolve(), loc=location)\n return UInt64ExpressionBuilder(len_call)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> InstanceBuilder:\n match name:\n case \"length\":\n return self.length(location)\n raise CodeError(f\"unrecognised member of {self.pytype}: {name}\", location)\n\n @typing.override\n def index(self, index: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n length = self.length(location)\n index = resolve_negative_literal_index(index, length, location)\n expr = IndexExpression(\n base=self.resolve(),\n index=index.resolve(),\n wtype=self.pytype.wtype,\n source_location=location,\n )\n return BytesExpressionBuilder(expr)\n\n @typing.override\n def slice_index(\n self,\n begin_index: InstanceBuilder | None,\n end_index: InstanceBuilder | None,\n stride: InstanceBuilder | None,\n location: SourceLocation,\n ) -> InstanceBuilder:\n if stride is not None:\n logger.error(\"stride is not supported\", location=stride.source_location)\n\n slice_expr: Expression = IntersectionSliceExpression(\n base=self.resolve(),\n begin_index=_eval_slice_component(begin_index),\n end_index=_eval_slice_component(end_index),\n wtype=self.pytype.wtype,\n source_location=location,\n )\n return BytesExpressionBuilder(slice_expr)\n\n @typing.override\n def iterate(self) -> Expression:\n return self.resolve()\n\n @typing.override\n def iterable_item_type(self) -> pytypes.PyType:\n return pytypes.BytesType\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n len_expr = intrinsic_factory.bytes_len(self.resolve(), location)\n len_builder = UInt64ExpressionBuilder(len_expr)\n return len_builder.bool_eval(location, negate=negate)\n\n @typing.override\n def unary_op(self, op: BuilderUnaryOp, location: SourceLocation) -> InstanceBuilder:\n if op == BuilderUnaryOp.bit_invert:\n return BytesExpressionBuilder(\n BytesUnaryOperation(\n expr=self.resolve(),\n op=BytesUnaryOperator.bit_invert,\n source_location=location,\n )\n )\n return super().unary_op(op, location)\n\n @typing.override\n def contains(self, item: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n item_expr = expect.argument_of_type_else_dummy(\n item, pytypes.BytesType, resolve_literal=True\n ).resolve()\n is_substring_expr = PuyaLibCall(\n func=PuyaLibFunction.is_substring,\n args=[CallArg(value=item_expr, name=None), CallArg(value=self.resolve(), name=None)],\n source_location=location,\n )\n return BoolExpressionBuilder(is_substring_expr)\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n other = other.resolve_literal(converter=BytesTypeBuilder(other.source_location))\n return compare_bytes(self=self, op=op, other=other, source_location=location)\n\n @typing.override\n def binary_op(\n self,\n other: InstanceBuilder,\n op: BuilderBinaryOp,\n location: SourceLocation,\n *,\n reverse: bool,\n ) -> InstanceBuilder:\n bytes_op = _translate_binary_bytes_operator(op)\n if bytes_op is None:\n return NotImplemented\n\n other = other.resolve_literal(converter=BytesTypeBuilder(other.source_location))\n if not (pytypes.BytesType <= other.pytype):\n return NotImplemented\n\n lhs = self.resolve()\n rhs = other.resolve()\n if reverse:\n (lhs, rhs) = (rhs, lhs)\n bin_op_expr = BytesBinaryOperation(\n source_location=location, left=lhs, right=rhs, op=bytes_op\n )\n return BytesExpressionBuilder(bin_op_expr)\n\n @typing.override\n def augmented_assignment(\n self, op: BuilderBinaryOp, rhs: InstanceBuilder, location: SourceLocation\n ) -> Statement:\n bytes_op = _translate_binary_bytes_operator(op)\n if bytes_op is None:\n logger.error(f\"unsupported operator for type: {op.value!r}\", location=location)\n return dummy_statement(location)\n\n rhs = expect.argument_of_type_else_dummy(rhs, self.pytype, resolve_literal=True)\n target = self.resolve_lvalue()\n return BytesAugmentedAssignment(\n target=target,\n op=bytes_op,\n value=rhs.resolve(),\n source_location=location,\n )\n\n\ndef _translate_binary_bytes_operator(operator: BuilderBinaryOp) -> BytesBinaryOperator | None:\n try:\n return BytesBinaryOperator(operator.value)\n except ValueError:\n return None\n\n\ndef _eval_slice_component(val: NodeBuilder | None) -> Expression | None | int:\n match val:\n case None:\n return None\n case LiteralBuilder(value=int(int_value)):\n return int_value\n return expect.argument_of_type_else_dummy(val, pytypes.UInt64Type).resolve()\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/bytes.py","language":"Python","license":"NOASSERTION","size":11433} {"code":"import typing\nfrom collections.abc import Mapping, Sequence\n\nimport mypy.nodes\n\nfrom puya.awst.nodes import CompiledContract, CompiledLogicSig, Expression\nfrom puya.awst.txn_fields import TxnField\nfrom puya.log import get_logger\nfrom puya.parse import SourceLocation\nfrom puya.program_refs import LogicSigReference\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder\nfrom puyapy.awst_build.eb._utils import dummy_value\nfrom puyapy.awst_build.eb.dict_ import DictLiteralBuilder\nfrom puyapy.awst_build.eb.interface import InstanceBuilder, NodeBuilder\nfrom puyapy.awst_build.eb.logicsig import LogicSigExpressionBuilder\nfrom puyapy.awst_build.eb.tuple import TupleExpressionBuilder\nfrom puyapy.awst_build.utils import get_arg_mapping\n\nlogger = get_logger(__name__)\n\n# these names should match pytypes CompiledContract definition\nPROGRAM_FIELDS = {\n \"approval_program\": TxnField.ApprovalProgramPages,\n \"clear_state_program\": TxnField.ClearStateProgramPages,\n}\nAPP_ALLOCATION_FIELDS = {\n \"extra_program_pages\": TxnField.ExtraProgramPages,\n \"global_bytes\": TxnField.GlobalNumByteSlice,\n \"global_uints\": TxnField.GlobalNumUint,\n \"local_bytes\": TxnField.LocalNumByteSlice,\n \"local_uints\": TxnField.LocalNumUint,\n}\n\n\nclass CompiledContractExpressionBuilder(TupleExpressionBuilder):\n def __init__(self, expr: Expression) -> None:\n super().__init__(expr, pytypes.CompiledContractType)\n\n\nclass CompiledLogicSigExpressionBuilder(TupleExpressionBuilder):\n def __init__(self, expr: Expression) -> None:\n super().__init__(expr, pytypes.CompiledLogicSigType)\n\n\n_TEMPLATE_VAR_KWARG_NAMES = [\n \"template_vars\",\n \"template_vars_prefix\",\n]\n\n\nclass CompileContractFunctionBuilder(FunctionBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n contract_arg_name = \"contract\"\n arg_map, _ = get_arg_mapping(\n args=args,\n arg_names=arg_names,\n call_location=location,\n raise_on_missing=False,\n required_positional_names=[contract_arg_name],\n optional_kw_only=[\n *APP_ALLOCATION_FIELDS,\n *_TEMPLATE_VAR_KWARG_NAMES,\n ],\n )\n prefix, template_vars = _extract_prefix_template_args(arg_map)\n allocation_overrides = {}\n for python_name, field in APP_ALLOCATION_FIELDS.items():\n if arg := arg_map.get(python_name):\n allocation_overrides[field] = expect.argument_of_type_else_dummy(\n arg, pytypes.UInt64Type, resolve_literal=True\n ).resolve()\n\n result_type = pytypes.CompiledContractType\n match arg_map[contract_arg_name]:\n case NodeBuilder(pytype=pytypes.TypeType(typ=pytypes.ContractType() as contract_typ)):\n contract = contract_typ.name\n case invalid_or_none:\n if invalid_or_none is None:\n # if None (=missing), then error message already logged by get_arg_mapping\n return dummy_value(result_type, location)\n return expect.not_this_type(\n invalid_or_none, default=expect.default_dummy_value(result_type)\n )\n\n return CompiledContractExpressionBuilder(\n CompiledContract(\n contract=contract,\n allocation_overrides=allocation_overrides,\n prefix=prefix,\n template_variables=template_vars,\n wtype=result_type.wtype,\n source_location=location,\n )\n )\n\n\nclass CompileLogicSigFunctionBuilder(FunctionBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n logicsig_arg_name = \"logicsig\"\n arg_map, _ = get_arg_mapping(\n args=args,\n arg_names=arg_names,\n call_location=location,\n raise_on_missing=False,\n required_positional_names=[logicsig_arg_name],\n optional_kw_only=_TEMPLATE_VAR_KWARG_NAMES,\n )\n match arg_map.get(logicsig_arg_name):\n case LogicSigExpressionBuilder(ref=logic_sig):\n pass\n case missing_or_invalid:\n logic_sig = LogicSigReference(\"\") # dummy reference\n # if None (=missing), then error message already logged by get_arg_mapping\n if missing_or_invalid is not None:\n expect.not_this_type(missing_or_invalid, default=expect.default_none)\n prefix, template_vars = _extract_prefix_template_args(arg_map)\n return CompiledLogicSigExpressionBuilder(\n CompiledLogicSig(\n logic_sig=logic_sig,\n prefix=prefix,\n template_variables=template_vars,\n wtype=pytypes.CompiledLogicSigType.wtype,\n source_location=location,\n )\n )\n\n\ndef _extract_prefix_template_args(\n name_args: dict[str, NodeBuilder],\n) -> tuple[str | None, Mapping[str, Expression]]:\n prefix: str | None = None\n template_vars: Mapping[str, Expression] = {}\n\n if template_vars_node := name_args.get(\"template_vars\"):\n if isinstance(template_vars_node, DictLiteralBuilder):\n template_vars = {k: v.resolve() for k, v in template_vars_node.mapping.items()}\n else:\n expect.not_this_type(template_vars_node, default=expect.default_none)\n if prefix_node := name_args.get(\"template_vars_prefix\"):\n prefix = expect.simple_string_literal(prefix_node, default=expect.default_none)\n return prefix, template_vars\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/compiled.py","language":"Python","license":"NOASSERTION","size":5997} {"code":"import typing\n\nfrom puya.awst.nodes import (\n BinaryBooleanOperator,\n ConditionalExpression,\n Expression,\n Lvalue,\n Statement,\n)\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb.bool import BoolExpressionBuilder\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import (\n BuilderBinaryOp,\n BuilderComparisonOp,\n BuilderUnaryOp,\n InstanceBuilder,\n LiteralBuilder,\n NodeBuilder,\n TypeBuilder,\n)\n\n\nclass ConditionalLiteralBuilder(InstanceBuilder):\n def __init__(\n self,\n *,\n true_literal: LiteralBuilder,\n false_literal: LiteralBuilder,\n condition: InstanceBuilder,\n location: SourceLocation,\n ):\n super().__init__(location)\n self._pytype = _common_base(true_literal.pytype, false_literal.pytype, location)\n self._true_literal = true_literal\n self._false_literal = false_literal\n self._condition = condition\n\n @typing.override\n @property\n def pytype(self) -> pytypes.PyType:\n return self._true_literal.pytype\n\n @typing.override\n def resolve(self) -> Expression:\n true_expr = self._true_literal.resolve()\n false_expr = self._false_literal.resolve()\n condition_expr = self._condition.resolve()\n return ConditionalExpression(\n condition=condition_expr,\n true_expr=true_expr,\n false_expr=false_expr,\n source_location=self.source_location,\n )\n\n @typing.override\n def resolve_literal(self, converter: TypeBuilder) -> InstanceBuilder:\n true_b = converter.convert_literal(\n literal=self._true_literal, location=converter.source_location\n )\n false_b = converter.convert_literal(\n literal=self._false_literal, location=converter.source_location\n )\n return self._resolve_literals(true_b, false_b)\n\n @typing.override\n def try_resolve_literal(self, converter: TypeBuilder) -> InstanceBuilder | None:\n true_b = converter.try_convert_literal(\n literal=self._true_literal, location=converter.source_location\n )\n false_b = converter.try_convert_literal(\n literal=self._false_literal, location=converter.source_location\n )\n if true_b is None or false_b is None:\n return None\n return self._resolve_literals(true_b, false_b)\n\n def _resolve_literals(\n self, true_b: InstanceBuilder, false_b: InstanceBuilder\n ) -> InstanceBuilder:\n result_pytype = _common_base(true_b.pytype, false_b.pytype, self.source_location)\n result_pytype = true_b.pytype\n true_expr = true_b.resolve()\n false_expr = false_b.resolve()\n condition_expr = self._condition.resolve()\n result_expr = ConditionalExpression(\n condition=condition_expr,\n true_expr=true_expr,\n false_expr=false_expr,\n source_location=self.source_location,\n )\n return builder_for_instance(result_pytype, result_expr)\n\n @typing.override\n def resolve_lvalue(self) -> Lvalue:\n raise CodeError(\"cannot assign to literal\", self.source_location)\n\n @typing.override\n def delete(self, location: SourceLocation) -> Statement:\n raise CodeError(\"cannot delete literal\", location)\n\n @typing.override\n def unary_op(self, op: BuilderUnaryOp, location: SourceLocation) -> InstanceBuilder:\n transformed_true = self._true_literal.unary_op(op, location)\n transformed_false = self._false_literal.unary_op(op, location)\n return ConditionalLiteralBuilder(\n true_literal=transformed_true,\n false_literal=transformed_false,\n condition=self._condition,\n location=location,\n )\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n other = other.single_eval()\n transformed_true = self._true_literal.compare(other, op, location)\n transformed_false = self._false_literal.compare(other, op, location)\n if transformed_true is NotImplemented or transformed_false is NotImplemented:\n return NotImplemented\n return ConditionalLiteralBuilder(\n true_literal=transformed_true,\n false_literal=transformed_false,\n condition=self._condition,\n location=location,\n )\n\n @typing.override\n def binary_op(\n self,\n other: InstanceBuilder,\n op: BuilderBinaryOp,\n location: SourceLocation,\n *,\n reverse: bool,\n ) -> InstanceBuilder:\n other = other.single_eval()\n transformed_true = self._true_literal.binary_op(other, op, location, reverse=reverse)\n transformed_false = self._false_literal.binary_op(other, op, location, reverse=reverse)\n if transformed_true is NotImplemented or transformed_false is NotImplemented:\n return NotImplemented\n return ConditionalLiteralBuilder(\n true_literal=transformed_true,\n false_literal=transformed_false,\n condition=self._condition,\n location=location,\n )\n\n @typing.override\n def bool_binary_op(\n self, other: InstanceBuilder, op: BinaryBooleanOperator, location: SourceLocation\n ) -> InstanceBuilder:\n return super().bool_binary_op(other, op, location)\n\n @typing.override\n def augmented_assignment(\n self, op: BuilderBinaryOp, rhs: InstanceBuilder, location: SourceLocation\n ) -> Statement:\n raise CodeError(\"cannot assign to literal\", location)\n\n @typing.override\n def to_bytes(self, location: SourceLocation) -> Expression:\n true_expr = self._true_literal.to_bytes(location)\n false_expr = self._false_literal.to_bytes(location)\n condition_expr = self._condition.resolve()\n return ConditionalExpression(\n condition=condition_expr,\n true_expr=true_expr,\n false_expr=false_expr,\n source_location=self.source_location,\n )\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n transformed_true = self._true_literal.member_access(name, location)\n transformed_false = self._false_literal.member_access(name, location)\n return ConditionalLiteralBuilder(\n true_literal=transformed_true,\n false_literal=transformed_false,\n condition=self._condition,\n location=location,\n )\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n true_expr = self._true_literal.bool_eval(location, negate=negate).resolve()\n false_expr = self._false_literal.bool_eval(location, negate=negate).resolve()\n condition_expr = self._condition.resolve()\n return BoolExpressionBuilder(\n ConditionalExpression(\n condition=condition_expr,\n true_expr=true_expr,\n false_expr=false_expr,\n source_location=location,\n )\n )\n\n @typing.override\n def contains(self, item: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n item = item.single_eval()\n transformed_true = self._true_literal.contains(item, location)\n transformed_false = self._false_literal.contains(item, location)\n return ConditionalLiteralBuilder(\n true_literal=transformed_true,\n false_literal=transformed_false,\n condition=self._condition,\n location=location,\n )\n\n @typing.override\n def iterate(self) -> typing.Never:\n raise CodeError(\"cannot iterate literal\")\n\n @typing.override\n def iterable_item_type(self) -> typing.Never:\n self.iterate()\n\n @typing.override\n def index(self, index: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n index = index.single_eval()\n transformed_true = self._true_literal.index(index, location)\n transformed_false = self._false_literal.index(index, location)\n return ConditionalLiteralBuilder(\n true_literal=transformed_true,\n false_literal=transformed_false,\n condition=self._condition,\n location=location,\n )\n\n @typing.override\n def slice_index(\n self,\n begin_index: InstanceBuilder | None,\n end_index: InstanceBuilder | None,\n stride: InstanceBuilder | None,\n location: SourceLocation,\n ) -> InstanceBuilder:\n if begin_index is not None:\n begin_index = begin_index.single_eval()\n if end_index is not None:\n end_index = end_index.single_eval()\n if stride is not None:\n stride = stride.single_eval()\n transformed_true = self._true_literal.slice_index(\n begin_index=begin_index, end_index=end_index, stride=stride, location=location\n )\n transformed_false = self._false_literal.slice_index(\n begin_index=begin_index, end_index=end_index, stride=stride, location=location\n )\n return ConditionalLiteralBuilder(\n true_literal=transformed_true,\n false_literal=transformed_false,\n condition=self._condition,\n location=location,\n )\n\n @typing.override\n def single_eval(self) -> InstanceBuilder:\n condition = self._condition.single_eval()\n return ConditionalLiteralBuilder(\n true_literal=self._true_literal,\n false_literal=self._false_literal,\n condition=condition,\n location=self.source_location,\n )\n\n\ndef _common_base(a: pytypes.PyType, b: pytypes.PyType, location: SourceLocation) -> pytypes.PyType:\n if a <= b:\n return a\n elif b < a:\n return b\n else:\n raise CodeError(\"type mismatch\", location)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/conditional_literal.py","language":"Python","license":"NOASSERTION","size":10077} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport attrs\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst.nodes import (\n AppStateExpression,\n AppStorageDefinition,\n AppStorageKind,\n InstanceMethodTarget,\n)\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb._utils import constant_bool_and_error\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import InstanceBuilder, NodeBuilder, TypeBuilder\nfrom puyapy.awst_build.eb.storage import (\n BoxMapProxyExpressionBuilder,\n BoxProxyExpressionBuilder,\n BoxRefProxyExpressionBuilder,\n GlobalStateExpressionBuilder,\n LocalStateExpressionBuilder,\n)\nfrom puyapy.awst_build.eb.subroutine import (\n BaseClassSubroutineInvokerExpressionBuilder,\n SubroutineInvokerExpressionBuilder,\n)\nfrom puyapy.models import ContractFragmentBase\n\nlogger = log.get_logger(__name__)\n\n\nclass ContractTypeExpressionBuilder(TypeBuilder[pytypes.ContractType]):\n def __init__(\n self,\n pytype: pytypes.ContractType,\n fragment: ContractFragmentBase,\n location: SourceLocation,\n ):\n assert pytype.name == fragment.id\n super().__init__(pytype, location)\n self.fragment: typing.Final = fragment\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n raise CodeError(\"cannot instantiate contract classes\", location)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n sym_type = self.fragment.resolve_symbol(name)\n if sym_type is None:\n return super().member_access(name, location)\n if not isinstance(sym_type, pytypes.FuncType):\n raise CodeError(\"static references are only supported for methods\", location)\n func_type = attrs.evolve(\n sym_type,\n args=[\n pytypes.FuncArg(type=self.produces(), name=None, kind=mypy.nodes.ArgKind.ARG_POS),\n *sym_type.args,\n ],\n )\n method = self.fragment.resolve_method(name)\n if method is None:\n raise CodeError(\"unable to resolve method member\", location)\n return BaseClassSubroutineInvokerExpressionBuilder(\n self.fragment.id, method, func_type=func_type, location=location\n )\n\n\nclass ContractSelfExpressionBuilder(NodeBuilder): # TODO: this _is_ an instance, technically\n def __init__(\n self,\n fragment: ContractFragmentBase,\n pytype: pytypes.ContractType,\n location: SourceLocation,\n ):\n super().__init__(location)\n self._fragment = fragment\n self._pytype = pytype\n\n @typing.override\n @property\n def pytype(self) -> pytypes.ContractType:\n return self._pytype\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n sym_type = self._fragment.resolve_symbol(name)\n if sym_type is None:\n raise CodeError(f\"unrecognised member of {self.pytype}: {name}\", location)\n if isinstance(sym_type, pytypes.FuncType):\n return SubroutineInvokerExpressionBuilder(\n target=InstanceMethodTarget(member_name=name),\n func_type=sym_type,\n location=location,\n )\n else:\n storage = self._fragment.resolve_storage(name)\n if storage is None:\n raise CodeError(\"unable to resolve storage member\", location)\n if storage.definition is None:\n raise CodeError(\"use of storage proxy before definition\", location)\n return _builder_for_storage_access(sym_type, name, storage.definition, location)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n return constant_bool_and_error(value=True, location=location, negate=negate)\n\n\ndef _builder_for_storage_access(\n typ: pytypes.PyType,\n member_name: str,\n definition: AppStorageDefinition,\n location: SourceLocation,\n) -> NodeBuilder:\n key = attrs.evolve(definition.key, source_location=location)\n if not isinstance(typ, pytypes.StorageProxyType | pytypes.StorageMapProxyType):\n app_global_expr = AppStateExpression(\n key=key,\n wtype=typ.checked_wtype(location),\n exists_assertion_message=f\"check self.{member_name} exists\",\n source_location=location,\n )\n return builder_for_instance(typ, app_global_expr)\n if typ == pytypes.BoxRefType:\n return BoxRefProxyExpressionBuilder(key, member_name)\n match definition.kind:\n case AppStorageKind.app_global:\n return GlobalStateExpressionBuilder(key, typ, member_name)\n case AppStorageKind.account_local:\n return LocalStateExpressionBuilder(key, typ, member_name)\n case AppStorageKind.box:\n if isinstance(typ, pytypes.StorageMapProxyType):\n return BoxMapProxyExpressionBuilder(key, typ, member_name)\n else:\n return BoxProxyExpressionBuilder(key, typ, member_name)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/contracts.py","language":"Python","license":"NOASSERTION","size":5368} {"code":"import typing\nfrom collections.abc import Mapping\n\nfrom puya import log\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build.eb._utils import constant_bool_and_error\nfrom puyapy.awst_build.eb.interface import (\n InstanceBuilder,\n NodeBuilder,\n)\n\nlogger = log.get_logger(__name__)\n\n\nclass DictLiteralBuilder(NodeBuilder):\n def __init__(self, mapping: Mapping[str, InstanceBuilder], location: SourceLocation):\n super().__init__(location)\n self._mapping = mapping\n\n @typing.override\n @property\n def pytype(self) -> None:\n return None\n\n @property\n def mapping(self) -> Mapping[str, InstanceBuilder]:\n return self._mapping\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> typing.Never:\n if name in dir(dict()): # noqa: C408\n raise CodeError(\"method is not currently supported\", location)\n raise CodeError(\"unrecognised member access\", location)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n return constant_bool_and_error(value=bool(self._mapping), location=location, negate=negate)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/dict_.py","language":"Python","license":"NOASSERTION","size":1218} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst.nodes import (\n CallArg,\n Expression,\n PuyaLibCall,\n PuyaLibFunction,\n UInt64Constant,\n)\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder\nfrom puyapy.awst_build.eb._utils import dummy_value\nfrom puyapy.awst_build.eb.interface import InstanceBuilder, NodeBuilder\nfrom puyapy.awst_build.eb.none import NoneExpressionBuilder\nfrom puyapy.awst_build.utils import get_arg_mapping\n\nlogger = log.get_logger(__name__)\n\n\nclass EnsureBudgetBuilder(FunctionBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n required_budget_arg_name = \"required_budget\"\n fee_source_arg_name = \"fee_source\"\n arg_mapping, _ = get_arg_mapping(\n required_positional_names=[required_budget_arg_name],\n optional_positional_names=[fee_source_arg_name],\n args=args,\n arg_names=arg_names,\n call_location=location,\n raise_on_missing=False,\n )\n required_budget_arg = arg_mapping.get(required_budget_arg_name)\n if required_budget_arg is None:\n required_budget = dummy_value(pytypes.UInt64Type, location)\n else:\n required_budget = expect.argument_of_type_else_dummy(\n required_budget_arg, pytypes.UInt64Type, resolve_literal=True\n )\n\n fee_source_arg = arg_mapping.get(fee_source_arg_name)\n if fee_source_arg is None:\n fee_source_expr: Expression = UInt64Constant(value=0, source_location=location)\n else:\n fee_source_expr = expect.argument_of_type_else_dummy(\n fee_source_arg, pytypes.OpUpFeeSourceType\n ).resolve()\n\n call_args = [\n CallArg(\n name=required_budget_arg_name,\n value=required_budget.resolve(),\n ),\n CallArg(\n name=fee_source_arg_name,\n value=fee_source_expr,\n ),\n ]\n call_expr = PuyaLibCall(\n func=PuyaLibFunction.ensure_budget,\n args=call_args,\n source_location=location,\n )\n return NoneExpressionBuilder(call_expr)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/ensure_budget.py","language":"Python","license":"NOASSERTION","size":2536} {"code":"from puya.awst.nodes import Expression\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb.interface import CallableBuilder, InstanceBuilder\n\n\ndef builder_for_instance(pytyp: pytypes.PyType, expr: Expression) -> InstanceBuilder:\n from puyapy.awst_build.eb import _type_registry\n\n return _type_registry.builder_for_instance(pytyp, expr)\n\n\ndef builder_for_type(pytyp: pytypes.PyType, expr_loc: SourceLocation) -> CallableBuilder:\n from puyapy.awst_build.eb import _type_registry\n\n return _type_registry.builder_for_type(pytyp, expr_loc)\n\n\ndef try_get_builder_for_func(fullname: str, expr_loc: SourceLocation) -> CallableBuilder | None:\n from puyapy.awst_build.eb import _type_registry\n\n builder = _type_registry.FUNC_NAME_TO_BUILDER.get(fullname)\n if builder is not None:\n return builder(expr_loc)\n return None\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/factories.py","language":"Python","license":"NOASSERTION","size":890} {"code":"from __future__ import annotations\n\nimport abc\nimport enum\nimport typing\nfrom collections.abc import Sequence\n\nimport attrs\nimport mypy.nodes\nimport typing_extensions\n\nfrom puya import log\nfrom puya.awst.nodes import (\n BinaryBooleanOperator,\n Expression,\n Lvalue,\n Statement,\n)\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puya.utils import invert_ordered_binary_op\nfrom puyapy.awst_build import pytypes\nfrom puyapy.models import ConstantValue\n\nlogger = log.get_logger(__name__)\n\n\n@enum.unique\nclass BuilderComparisonOp(enum.StrEnum):\n eq = \"==\"\n ne = \"!=\"\n lt = \"<\"\n lte = \"<=\"\n gt = \">\"\n gte = \">=\"\n\n def reversed(self) -> BuilderComparisonOp:\n return BuilderComparisonOp(invert_ordered_binary_op(self.value))\n\n\n@enum.unique\nclass BuilderUnaryOp(enum.StrEnum):\n positive = \"+\"\n negative = \"-\"\n bit_invert = \"~\"\n\n\n@enum.unique\nclass BuilderBinaryOp(enum.StrEnum):\n add = \"+\"\n sub = \"-\"\n mult = \"*\"\n div = \"\/\"\n floor_div = \"\/\/\"\n mod = \"%\"\n pow = \"**\"\n mat_mult = \"@\"\n lshift = \"<<\"\n rshift = \">>\"\n bit_or = \"|\"\n bit_xor = \"^\"\n bit_and = \"&\"\n\n\nclass NodeBuilder(abc.ABC):\n def __init__(self, location: SourceLocation):\n self.source_location: typing.Final = location\n\n @property\n @abc.abstractmethod\n def pytype(self) -> pytypes.PyType | None: ...\n\n @abc.abstractmethod\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n \"\"\"Handle self.name\"\"\"\n\n @abc.abstractmethod\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n \"\"\"Handle boolean-ness evaluation, possibly inverted (ie \"not\" unary operator)\"\"\"\n\n\nclass CallableBuilder(NodeBuilder, abc.ABC):\n @abc.abstractmethod\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n \"\"\"Handle self(args...)\"\"\"\n\n\n_TPyType_co = typing_extensions.TypeVar(\n \"_TPyType_co\", bound=pytypes.PyType, default=pytypes.PyType, covariant=True\n)\n\n\nclass InstanceBuilder(NodeBuilder, typing.Generic[_TPyType_co], abc.ABC):\n @typing.override\n @property\n @abc.abstractmethod\n def pytype(self) -> _TPyType_co: ...\n\n @abc.abstractmethod\n def resolve(self) -> Expression:\n \"\"\"Produce an expression for use as an intermediary\"\"\"\n\n @abc.abstractmethod\n def resolve_literal(self, converter: TypeBuilder) -> InstanceBuilder:\n \"\"\"For use prior to calling resolve(), when a known type is expected,\n and implicit conversion is possible without breaking semantic compatibility.\n\n Primarily, this would be as an argument to an algopy function or class, or as an\n operand to a binary operator with an algopy-typed object.\n\n When implementing, this function should return self if there are no literals to convert,\n or if the literals are not expected to be homogenous (e.g. in the general case of a tuple\n with literals)\"\"\"\n\n @abc.abstractmethod\n def try_resolve_literal(self, converter: TypeBuilder) -> InstanceBuilder | None:\n \"\"\"Similar to resolve_literal, but in the case where a conversion is possible but the\n literal values are the wrong type, don't produce any errors and return None instead.\n\n If no conversion is necessary (ie no literals or it's not meaningful to convert literals\n this way, such as a tuple with literals), just return the current instance.\n \"\"\"\n\n @abc.abstractmethod\n def resolve_lvalue(self) -> Lvalue:\n \"\"\"Produce an expression for the target of an assignment\"\"\"\n\n @abc.abstractmethod\n def delete(self, location: SourceLocation) -> Statement:\n \"\"\"Handle del self\"\"\"\n\n @abc.abstractmethod\n def unary_op(self, op: BuilderUnaryOp, location: SourceLocation) -> InstanceBuilder:\n \"\"\"Handle {op} self\"\"\"\n\n @abc.abstractmethod\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n \"\"\"Handle self {op} other\"\"\"\n\n @abc.abstractmethod\n def binary_op(\n self,\n other: InstanceBuilder,\n op: BuilderBinaryOp,\n location: SourceLocation,\n *,\n reverse: bool,\n ) -> InstanceBuilder:\n \"\"\"Handle self {op} other\"\"\"\n\n @abc.abstractmethod\n def bool_binary_op(\n self, other: InstanceBuilder, op: BinaryBooleanOperator, location: SourceLocation\n ) -> InstanceBuilder:\n \"\"\"Handle self and\/or other\"\"\"\n from puyapy.awst_build.eb.binary_bool_op import BinaryBoolOpBuilder\n\n return BinaryBoolOpBuilder(left=self, right=other, op=op, location=location)\n\n @abc.abstractmethod\n def augmented_assignment(\n self, op: BuilderBinaryOp, rhs: InstanceBuilder, location: SourceLocation\n ) -> Statement:\n \"\"\"Handle self {op}= rhs\"\"\"\n\n @abc.abstractmethod\n def contains(self, item: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n \"\"\"Handle item in self\"\"\"\n from puyapy.awst_build.eb._utils import dummy_value\n\n logger.error(\"expression is not iterable\", location=self.source_location)\n return dummy_value(pytypes.BoolType, location)\n\n @abc.abstractmethod\n def iterate(self) -> Expression:\n \"\"\"Produce target of ForInLoop\"\"\"\n raise CodeError(\"expression is not iterable\", self.source_location)\n\n @abc.abstractmethod\n def iterable_item_type(self) -> pytypes.PyType:\n \"\"\"The type of the item if this expression is iterable\"\"\"\n raise CodeError(\"expression is not iterable\", self.source_location)\n\n @abc.abstractmethod\n def index(self, index: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n \"\"\"Handle self[index]\"\"\"\n raise CodeError(\"expression is not a collection\", location)\n\n @abc.abstractmethod\n def slice_index(\n self,\n begin_index: InstanceBuilder | None,\n end_index: InstanceBuilder | None,\n stride: InstanceBuilder | None,\n location: SourceLocation,\n ) -> InstanceBuilder:\n \"\"\"Handle self[begin_index:end_index:stride]\"\"\"\n raise CodeError(\"expression is not a collection\", location)\n\n @abc.abstractmethod\n def to_bytes(self, location: SourceLocation) -> Expression:\n \"\"\"Handle conversion\/cast to bytes, if possible\"\"\"\n\n @abc.abstractmethod\n def single_eval(self) -> InstanceBuilder:\n \"\"\"wrap any underlying expressions etc. (if applicable) to avoid multiple evaluations\"\"\"\n\n\nclass StaticSizedCollectionBuilder(NodeBuilder, abc.ABC):\n @abc.abstractmethod\n def iterate_static(self) -> Sequence[InstanceBuilder]: ...\n\n\nclass LiteralBuilder(InstanceBuilder, abc.ABC):\n @property\n @abc.abstractmethod\n def value(self) -> ConstantValue: ...\n\n @typing.override\n @abc.abstractmethod\n def unary_op(self, op: BuilderUnaryOp, location: SourceLocation) -> LiteralBuilder: ...\n\n @typing.override\n @abc.abstractmethod\n def member_access(self, name: str, location: SourceLocation) -> LiteralBuilder: ...\n\n @typing.override\n @abc.abstractmethod\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> LiteralBuilder: ...\n\n @typing.override\n @abc.abstractmethod\n def binary_op(\n self,\n other: InstanceBuilder,\n op: BuilderBinaryOp,\n location: SourceLocation,\n *,\n reverse: bool,\n ) -> LiteralBuilder: ...\n\n @typing.override\n @abc.abstractmethod\n def contains(self, item: InstanceBuilder, location: SourceLocation) -> LiteralBuilder: ...\n\n @typing.override\n @abc.abstractmethod\n def index(self, index: InstanceBuilder, location: SourceLocation) -> LiteralBuilder: ...\n\n @typing.override\n @abc.abstractmethod\n def slice_index(\n self,\n begin_index: InstanceBuilder | None,\n end_index: InstanceBuilder | None,\n stride: InstanceBuilder | None,\n location: SourceLocation,\n ) -> LiteralBuilder: ...\n\n\n# TODO: separate interface from implementation\nclass TypeBuilder(CallableBuilder, typing.Generic[_TPyType_co], abc.ABC):\n def __init__(self, pytype: _TPyType_co, location: SourceLocation):\n super().__init__(location)\n self._pytype = pytype\n\n @typing.final\n @typing.override\n @property\n def pytype(self) -> pytypes.TypeType:\n return pytypes.TypeType(self._pytype)\n\n @typing.final\n def produces(self) -> _TPyType_co:\n return self._pytype\n\n @typing.final\n def convert_literal(\n self, literal: LiteralBuilder, location: SourceLocation\n ) -> InstanceBuilder:\n from puyapy.awst_build.eb._utils import dummy_value\n\n result = self.try_convert_literal(literal, location)\n if result is not None:\n return result\n logger.error(\n f\"can't covert literal to {self.produces()}\", location=literal.source_location\n )\n return dummy_value(self.produces(), location)\n\n def try_convert_literal(\n self, literal: LiteralBuilder, location: SourceLocation\n ) -> InstanceBuilder | None:\n \"\"\"\n If the type of `literal.value` is correct, return a new instance, otherwise return `None`.\n If the value is out of range or otherwise invalid, an error is logged,\n but an instance is still returned.\n \"\"\"\n return None\n\n @typing.override\n @typing.final\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n from puyapy.awst_build.eb._utils import constant_bool_and_error\n\n return constant_bool_and_error(value=True, location=location, negate=negate)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n raise CodeError(f\"unrecognised member {name!r} of type '{self._pytype}'\", location)\n\n\n@attrs.frozen(kw_only=True)\nclass StorageProxyConstructorArgs:\n key: Expression | None\n key_arg_name: str\n description: str | None\n initial_value: InstanceBuilder | None = None\n\n\nclass StorageProxyConstructorResult(\n InstanceBuilder[pytypes.StorageProxyType | pytypes.StorageMapProxyType], abc.ABC\n):\n @property\n @abc.abstractmethod\n def args(self) -> StorageProxyConstructorArgs: ...\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/interface.py","language":"Python","license":"NOASSERTION","size":10437} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst.nodes import IntrinsicCall, MethodConstant\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder\nfrom puyapy.awst_build.eb._literals import LiteralBuilderImpl\nfrom puyapy.awst_build.eb._utils import dummy_value\nfrom puyapy.awst_build.eb.bytes import BytesExpressionBuilder\nfrom puyapy.awst_build.eb.factories import builder_for_instance, builder_for_type\nfrom puyapy.awst_build.eb.interface import (\n InstanceBuilder,\n LiteralBuilder,\n NodeBuilder,\n TypeBuilder,\n)\nfrom puyapy.awst_build.intrinsic_models import (\n FunctionOpMapping,\n OpMappingWithOverloads,\n PropertyOpMapping,\n)\n\nlogger = log.get_logger(__name__)\n\n\nclass Arc4SignatureBuilder(FunctionBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.exactly_one_arg(args, location, default=expect.default_none)\n if arg is None:\n return dummy_value(pytypes.BytesType, location)\n str_value = expect.simple_string_literal(arg, default=expect.default_fixed_value(\"\"))\n return BytesExpressionBuilder(\n MethodConstant(\n value=str_value,\n source_location=location,\n )\n )\n\n\nclass IntrinsicEnumTypeBuilder(TypeBuilder[pytypes.IntrinsicEnumType]):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n raise CodeError(\"cannot instantiate enumeration type\", location)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n produces = self.produces()\n value = produces.members.get(name)\n if value is None:\n return super().member_access(name, location)\n return LiteralBuilderImpl(value=value, source_location=location)\n\n\nclass IntrinsicNamespaceTypeBuilder(TypeBuilder[pytypes.IntrinsicNamespaceType]):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n raise CodeError(\"cannot instantiate namespace type\", location)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n produces = self.produces()\n mapping = produces.members.get(name)\n if mapping is None:\n return super().member_access(name, location)\n if isinstance(mapping, PropertyOpMapping):\n intrinsic_expr = IntrinsicCall(\n op_code=mapping.op_code,\n immediates=[mapping.immediate],\n wtype=mapping.wtype,\n source_location=location,\n )\n return builder_for_instance(mapping.typ, intrinsic_expr)\n else:\n fullname = \".\".join((produces.name, name))\n return IntrinsicFunctionExpressionBuilder(fullname, mapping, location)\n\n\nclass IntrinsicFunctionExpressionBuilder(FunctionBuilder):\n def __init__(\n self, fullname: str, mapping: OpMappingWithOverloads, location: SourceLocation\n ) -> None:\n self._fullname = fullname\n self._mapping = mapping\n super().__init__(location)\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n if not expect.exactly_n_args(args, location, self._mapping.arity):\n return dummy_value(self._mapping.result, location)\n intrinsic_expr = _map_call(self._mapping, args=args, location=location)\n return builder_for_instance(self._mapping.result, intrinsic_expr)\n\n\ndef _best_op_mapping(\n op_mappings: OpMappingWithOverloads, args: Sequence[NodeBuilder]\n) -> FunctionOpMapping:\n \"\"\"Find op mapping that matches as many arguments to immediate args as possible\"\"\"\n literal_arg_positions = {\n arg_idx\n for arg_idx, arg in enumerate(args)\n # we can't handle any form of dynamism for immediates, such as `1 if foo else 2`,\n # so we must check for LiteralBuilder only\n if isinstance(arg, LiteralBuilder)\n }\n for op_mapping in sorted(\n op_mappings.overloads, key=lambda om: len(om.literal_arg_positions), reverse=True\n ):\n if literal_arg_positions.issuperset(op_mapping.literal_arg_positions):\n return op_mapping\n # fall back to first, let argument mapping handle logging errors\n return op_mappings.overloads[0]\n\n\ndef _map_call(\n ast_mapper: OpMappingWithOverloads,\n args: Sequence[NodeBuilder],\n location: SourceLocation,\n) -> IntrinsicCall:\n if len(ast_mapper.overloads) == 1:\n (op_mapping,) = ast_mapper.overloads\n else:\n op_mapping = _best_op_mapping(ast_mapper, args)\n\n immediates = list(op_mapping.immediates)\n stack_args = list[InstanceBuilder]()\n for arg, arg_data in zip(args, op_mapping.args, strict=True):\n arg_in = expect.instance_builder(arg, default=expect.default_none)\n if arg_in is None:\n pass\n elif isinstance(arg_data, int):\n immediates_index = arg_data\n literal_type = typing.cast(type[str | int], immediates[immediates_index])\n if not (\n isinstance(arg_in, LiteralBuilder) # see note in _best_op_mapping\n and isinstance(arg_value := arg_in.value, literal_type)\n ):\n logger.error(\n f\"argument must be a literal {literal_type.__name__} value\",\n location=arg_in.source_location,\n )\n immediates[immediates_index] = literal_type()\n else:\n assert isinstance(arg_value, int | str)\n immediates[immediates_index] = arg_value\n else:\n allowed_pytypes = arg_data\n if isinstance(arg_in.pytype, pytypes.LiteralOnlyType) or (\n isinstance(arg_in.pytype, pytypes.UnionType)\n and any(isinstance(t, pytypes.LiteralOnlyType) for t in arg_in.pytype.types)\n ):\n for allowed_type in allowed_pytypes:\n type_builder = builder_for_type(allowed_type, arg_in.source_location)\n if isinstance(type_builder, TypeBuilder):\n converted = arg_in.try_resolve_literal(type_builder)\n if converted is not None:\n arg_in = converted\n break\n stack_args.append(expect.argument_of_type_else_dummy(arg_in, *allowed_pytypes))\n return IntrinsicCall(\n op_code=op_mapping.op_code,\n wtype=ast_mapper.result_wtype,\n immediates=typing.cast(list[str | int], immediates),\n stack_args=[a.resolve() for a in stack_args],\n source_location=location,\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/intrinsics.py","language":"Python","license":"NOASSERTION","size":7444} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst.nodes import BytesConstant, BytesEncoding, Expression\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import intrinsic_factory, pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder\nfrom puyapy.awst_build.eb.interface import InstanceBuilder, NodeBuilder\nfrom puyapy.awst_build.eb.none import NoneExpressionBuilder\nfrom puyapy.awst_build.eb.uint64 import UInt64TypeBuilder\n\nlogger = log.get_logger(__name__)\n\n\nclass LogBuilder(FunctionBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n empty_utf8: Expression = BytesConstant(\n value=b\"\", encoding=BytesEncoding.utf8, source_location=location\n )\n args = list(args)\n try:\n sep_index = arg_names.index(\"sep\")\n except ValueError:\n sep = empty_utf8\n else:\n sep_arg = args.pop(sep_index)\n if isinstance(sep_arg, InstanceBuilder) and sep_arg.pytype.is_type_or_subtype(\n pytypes.StringType,\n pytypes.StrLiteralType,\n pytypes.BytesType,\n pytypes.BytesLiteralType,\n ):\n sep = sep_arg.to_bytes(sep_arg.source_location)\n else:\n expect.not_this_type(sep_arg, default=expect.default_none)\n sep = empty_utf8\n\n bytes_args = []\n for arg in args:\n if not isinstance(arg, InstanceBuilder):\n expect.not_this_type(arg, default=expect.default_none)\n else:\n if arg.pytype == pytypes.IntLiteralType: # match int exactly, ie exclude bool\n arg = arg.resolve_literal(UInt64TypeBuilder(arg.source_location))\n # TODO: make to_bytes non-throwing\n bytes_expr = arg.to_bytes(arg.source_location)\n bytes_args.append(bytes_expr)\n\n if not bytes_args:\n log_value = empty_utf8\n else:\n log_value = bytes_args[0]\n for bytes_expr in bytes_args[1:]:\n arg_plus_sep = intrinsic_factory.concat(log_value, sep, bytes_expr.source_location)\n log_value = intrinsic_factory.concat(\n arg_plus_sep, bytes_expr, bytes_expr.source_location\n )\n log_expr = intrinsic_factory.log(log_value, location)\n return NoneExpressionBuilder(log_expr)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/log.py","language":"Python","license":"NOASSERTION","size":2682} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puya.program_refs import LogicSigReference\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb.interface import InstanceBuilder, NodeBuilder, TypeBuilder\n\n\nclass LogicSigExpressionBuilder(TypeBuilder):\n def __init__(self, ref: LogicSigReference, location: SourceLocation):\n super().__init__(pytypes.LogicSigType, location)\n self.ref = ref\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n raise CodeError(\"cannot instantiate logic signatures\", location)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/logicsig.py","language":"Python","license":"NOASSERTION","size":818} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya.awst.nodes import Expression, VoidConstant\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import NotIterableInstanceExpressionBuilder\nfrom puyapy.awst_build.eb._utils import constant_bool_and_error\nfrom puyapy.awst_build.eb.interface import InstanceBuilder, NodeBuilder, TypeBuilder\n\n\nclass NoneTypeBuilder(TypeBuilder):\n def __init__(self, location: SourceLocation):\n super().__init__(pytypes.NoneType, location)\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n expect.no_args(args, location)\n return NoneExpressionBuilder(VoidConstant(location))\n\n\nclass NoneExpressionBuilder(NotIterableInstanceExpressionBuilder):\n def __init__(self, expr: Expression):\n super().__init__(pytypes.NoneType, expr)\n\n @typing.override\n def to_bytes(self, location: SourceLocation) -> Expression:\n raise CodeError(\"None is not usable as a value\", location)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n return constant_bool_and_error(value=False, location=location, negate=negate)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/none.py","language":"Python","license":"NOASSERTION","size":1496} {"code":"","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/reference_types\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"import abc\nimport typing\nfrom collections.abc import Callable, Mapping\n\nfrom immutabledict import immutabledict\n\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import (\n CheckedMaybe,\n Expression,\n IntrinsicCall,\n Not,\n NumericComparison,\n NumericComparisonExpression,\n ReinterpretCast,\n)\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import intrinsic_factory, pytypes\nfrom puyapy.awst_build.eb._base import NotIterableInstanceExpressionBuilder\nfrom puyapy.awst_build.eb.bool import BoolExpressionBuilder\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import (\n BuilderComparisonOp,\n InstanceBuilder,\n NodeBuilder,\n TypeBuilder,\n)\n\n\nclass ReferenceValueExpressionBuilder(NotIterableInstanceExpressionBuilder, abc.ABC):\n def __init__(\n self,\n expr: Expression,\n *,\n typ: pytypes.PyType,\n native_type: pytypes.RuntimeType,\n native_access_member: str,\n field_mapping: Mapping[str, tuple[str, pytypes.RuntimeType]],\n field_op_code: str,\n field_bool_comment: str,\n ):\n super().__init__(typ, expr)\n self.native_type = native_type\n self.native_access_member = native_access_member\n self.field_mapping = immutabledict[str, tuple[str, pytypes.RuntimeType]](field_mapping)\n self.field_op_code = field_op_code\n self.field_bool_comment = field_bool_comment\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n if name == self.native_access_member:\n native_cast = ReinterpretCast(\n expr=self.resolve(), wtype=self.native_type.wtype, source_location=location\n )\n return builder_for_instance(self.native_type, native_cast)\n if name in self.field_mapping:\n immediate, typ = self.field_mapping[name]\n acct_params_get = IntrinsicCall(\n op_code=self.field_op_code,\n immediates=[immediate],\n stack_args=[self.resolve()],\n wtype=wtypes.WTuple((typ.wtype, wtypes.bool_wtype), location),\n source_location=location,\n )\n checked_maybe = CheckedMaybe(acct_params_get, comment=self.field_bool_comment)\n return builder_for_instance(typ, checked_maybe)\n return super().member_access(name, location)\n\n\nclass UInt64BackedReferenceValueExpressionBuilder(ReferenceValueExpressionBuilder):\n def __init__(\n self,\n expr: Expression,\n *,\n typ: pytypes.PyType,\n typ_literal_converter: Callable[[SourceLocation], TypeBuilder],\n native_access_member: str,\n field_mapping: Mapping[str, tuple[str, pytypes.RuntimeType]],\n field_op_code: str,\n field_bool_comment: str,\n ):\n self._typ_literal_converter = typ_literal_converter\n super().__init__(\n expr,\n typ=typ,\n native_type=pytypes.UInt64Type,\n native_access_member=native_access_member,\n field_mapping=field_mapping,\n field_op_code=field_op_code,\n field_bool_comment=field_bool_comment,\n )\n\n @typing.override\n def to_bytes(self, location: SourceLocation) -> Expression:\n return intrinsic_factory.itob(self.resolve(), location)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n as_bool = ReinterpretCast(\n expr=self.resolve(),\n wtype=wtypes.bool_wtype,\n source_location=self.resolve().source_location,\n )\n if negate:\n expr: Expression = Not(location, as_bool)\n else:\n expr = as_bool\n return BoolExpressionBuilder(expr)\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n other = other.resolve_literal(self._typ_literal_converter(other.source_location))\n if not (\n other.pytype == self.pytype # can only compare with other of same type?\n and op in (BuilderComparisonOp.eq, BuilderComparisonOp.ne)\n ):\n return NotImplemented\n cmp_expr = NumericComparisonExpression(\n source_location=location,\n lhs=self.resolve(),\n operator=NumericComparison(op.value),\n rhs=other.resolve(),\n )\n return BoolExpressionBuilder(cmp_expr)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/reference_types\/_base.py","language":"Python","license":"NOASSERTION","size":4549} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log, utils\nfrom puya.algo_constants import ENCODED_ADDRESS_LENGTH\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import (\n AddressConstant,\n CheckedMaybe,\n Expression,\n IntrinsicCall,\n NumericComparison,\n NumericComparisonExpression,\n ReinterpretCast,\n TupleItemExpression,\n UInt64Constant,\n)\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import intrinsic_factory, pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder\nfrom puyapy.awst_build.eb._bytes_backed import BytesBackedTypeBuilder\nfrom puyapy.awst_build.eb._utils import (\n cast_to_bytes,\n compare_bytes,\n compare_expr_bytes,\n dummy_value,\n)\nfrom puyapy.awst_build.eb.bool import BoolExpressionBuilder\nfrom puyapy.awst_build.eb.interface import (\n BuilderComparisonOp,\n InstanceBuilder,\n LiteralBuilder,\n NodeBuilder,\n)\nfrom puyapy.awst_build.eb.reference_types._base import ReferenceValueExpressionBuilder\n\nlogger = log.get_logger(__name__)\n\n\nclass AccountTypeBuilder(BytesBackedTypeBuilder):\n def __init__(self, location: SourceLocation):\n super().__init__(pytypes.AccountType, location)\n\n @typing.override\n def try_convert_literal(\n self, literal: LiteralBuilder, location: SourceLocation\n ) -> InstanceBuilder | None:\n match literal.value:\n case str(str_value):\n if not utils.valid_address(str_value):\n logger.error(\n \"invalid address value - should have length\"\n f\" {ENCODED_ADDRESS_LENGTH} and not include base32 padding\",\n location=literal.source_location,\n )\n expr = AddressConstant(\n value=str_value,\n wtype=wtypes.account_wtype,\n source_location=location,\n )\n return AccountExpressionBuilder(expr)\n return None\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.at_most_one_arg(args, location)\n match arg:\n case InstanceBuilder(pytype=pytypes.StrLiteralType):\n return arg.resolve_literal(converter=AccountTypeBuilder(location))\n case None:\n value: Expression = intrinsic_factory.zero_address(location)\n case _:\n arg = expect.argument_of_type_else_dummy(arg, pytypes.BytesType)\n address_bytes_temp = arg.single_eval().resolve()\n is_correct_length = NumericComparisonExpression(\n operator=NumericComparison.eq,\n source_location=location,\n lhs=UInt64Constant(value=32, source_location=location),\n rhs=intrinsic_factory.bytes_len(address_bytes_temp, location),\n )\n value = CheckedMaybe.from_tuple_items(\n expr=ReinterpretCast(\n expr=address_bytes_temp,\n wtype=wtypes.account_wtype,\n source_location=location,\n ),\n check=is_correct_length,\n source_location=location,\n comment=\"Address length is 32 bytes\",\n )\n return AccountExpressionBuilder(value)\n\n\nclass AccountExpressionBuilder(ReferenceValueExpressionBuilder):\n def __init__(self, expr: Expression):\n native_type = pytypes.BytesType\n native_access_member = \"bytes\"\n field_mapping = {\n \"balance\": (\"AcctBalance\", pytypes.UInt64Type),\n \"min_balance\": (\"AcctMinBalance\", pytypes.UInt64Type),\n \"auth_address\": (\"AcctAuthAddr\", pytypes.AccountType),\n \"total_num_uint\": (\"AcctTotalNumUint\", pytypes.UInt64Type),\n \"total_num_byte_slice\": (\"AcctTotalNumByteSlice\", pytypes.UInt64Type),\n \"total_extra_app_pages\": (\"AcctTotalExtraAppPages\", pytypes.UInt64Type),\n \"total_apps_created\": (\"AcctTotalAppsCreated\", pytypes.UInt64Type),\n \"total_apps_opted_in\": (\"AcctTotalAppsOptedIn\", pytypes.UInt64Type),\n \"total_assets_created\": (\"AcctTotalAssetsCreated\", pytypes.UInt64Type),\n \"total_assets\": (\"AcctTotalAssets\", pytypes.UInt64Type),\n \"total_boxes\": (\"AcctTotalBoxes\", pytypes.UInt64Type),\n \"total_box_bytes\": (\"AcctTotalBoxBytes\", pytypes.UInt64Type),\n }\n field_op_code = \"acct_params_get\"\n field_bool_comment = \"account funded\"\n super().__init__(\n expr,\n typ=pytypes.AccountType,\n native_type=native_type,\n native_access_member=native_access_member,\n field_mapping=field_mapping,\n field_op_code=field_op_code,\n field_bool_comment=field_bool_comment,\n )\n\n @typing.override\n def to_bytes(self, location: SourceLocation) -> Expression:\n return cast_to_bytes(self.resolve(), location)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n if name == \"is_opted_in\":\n return _IsOptedIn(self.resolve(), location)\n return super().member_access(name, location)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n return compare_expr_bytes(\n lhs=self.resolve(),\n op=BuilderComparisonOp.eq if negate else BuilderComparisonOp.ne,\n rhs=intrinsic_factory.zero_address(location),\n source_location=location,\n )\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n other = other.resolve_literal(converter=AccountTypeBuilder(other.source_location))\n return compare_bytes(self=self, op=op, other=other, source_location=location)\n\n\nclass _IsOptedIn(FunctionBuilder):\n def __init__(self, expr: Expression, source_location: SourceLocation):\n super().__init__(source_location)\n self.expr = expr\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.exactly_one_arg(args, location, default=expect.default_none)\n if arg is None:\n return dummy_value(pytypes.BoolType, location)\n elif pytypes.AssetType <= arg.pytype:\n return BoolExpressionBuilder(\n TupleItemExpression(\n base=IntrinsicCall(\n op_code=\"asset_holding_get\",\n immediates=[\"AssetBalance\"],\n stack_args=[self.expr, arg.resolve()],\n wtype=wtypes.WTuple((wtypes.uint64_wtype, wtypes.bool_wtype), location),\n source_location=location,\n ),\n index=1,\n source_location=location,\n )\n )\n else:\n arg = expect.argument_of_type_else_dummy(arg, pytypes.ApplicationType)\n return BoolExpressionBuilder(\n IntrinsicCall(\n op_code=\"app_opted_in\",\n stack_args=[self.expr, arg.resolve()],\n source_location=location,\n wtype=wtypes.bool_wtype,\n )\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/reference_types\/account.py","language":"Python","license":"NOASSERTION","size":7791} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import Expression, ReinterpretCast, UInt64Constant\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb.interface import (\n InstanceBuilder,\n LiteralBuilder,\n NodeBuilder,\n TypeBuilder,\n)\nfrom puyapy.awst_build.eb.reference_types._base import UInt64BackedReferenceValueExpressionBuilder\n\nlogger = log.get_logger(__name__)\n\n\nclass ApplicationTypeBuilder(TypeBuilder):\n def __init__(self, location: SourceLocation):\n super().__init__(pytypes.ApplicationType, location)\n\n @typing.override\n def try_convert_literal(\n self, literal: LiteralBuilder, location: SourceLocation\n ) -> InstanceBuilder | None:\n match literal.value:\n case int(int_value):\n if int_value < 0 or int_value.bit_length() > 64: # TODO: should this be 256?\n logger.error(\"invalid application ID\", location=literal.source_location)\n const = UInt64Constant(value=int_value, source_location=location)\n expr = ReinterpretCast(\n expr=const, wtype=wtypes.application_wtype, source_location=location\n )\n return ApplicationExpressionBuilder(expr)\n return None\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.at_most_one_arg(args, location)\n match arg:\n case InstanceBuilder(pytype=pytypes.IntLiteralType):\n return arg.resolve_literal(ApplicationTypeBuilder(location))\n case None:\n uint64_expr: Expression = UInt64Constant(value=0, source_location=location)\n case _:\n arg = expect.argument_of_type_else_dummy(arg, pytypes.UInt64Type)\n uint64_expr = arg.resolve()\n app_expr = ReinterpretCast(\n source_location=location, wtype=wtypes.application_wtype, expr=uint64_expr\n )\n return ApplicationExpressionBuilder(app_expr)\n\n\nclass ApplicationExpressionBuilder(UInt64BackedReferenceValueExpressionBuilder):\n def __init__(self, expr: Expression):\n native_access_member = \"id\"\n field_mapping = {\n \"approval_program\": (\"AppApprovalProgram\", pytypes.BytesType),\n \"clear_state_program\": (\"AppClearStateProgram\", pytypes.BytesType),\n \"global_num_uint\": (\"AppGlobalNumUint\", pytypes.UInt64Type),\n \"global_num_bytes\": (\"AppGlobalNumByteSlice\", pytypes.UInt64Type),\n \"local_num_uint\": (\"AppLocalNumUint\", pytypes.UInt64Type),\n \"local_num_bytes\": (\"AppLocalNumByteSlice\", pytypes.UInt64Type),\n \"extra_program_pages\": (\"AppExtraProgramPages\", pytypes.UInt64Type),\n \"creator\": (\"AppCreator\", pytypes.AccountType),\n \"address\": (\"AppAddress\", pytypes.AccountType),\n }\n field_op_code = \"app_params_get\"\n field_bool_comment = \"application exists\"\n super().__init__(\n expr,\n typ=pytypes.ApplicationType,\n typ_literal_converter=ApplicationTypeBuilder,\n native_access_member=native_access_member,\n field_mapping=field_mapping,\n field_op_code=field_op_code,\n field_bool_comment=field_bool_comment,\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/reference_types\/application.py","language":"Python","license":"NOASSERTION","size":3611} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import (\n CheckedMaybe,\n Expression,\n IntrinsicCall,\n ReinterpretCast,\n UInt64Constant,\n)\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import (\n InstanceBuilder,\n LiteralBuilder,\n NodeBuilder,\n TypeBuilder,\n)\nfrom puyapy.awst_build.eb.reference_types._base import UInt64BackedReferenceValueExpressionBuilder\n\nlogger = log.get_logger(__name__)\n\n\nclass AssetTypeBuilder(TypeBuilder[pytypes.RuntimeType]):\n def __init__(self, location: SourceLocation):\n super().__init__(pytypes.AssetType, location)\n\n @typing.override\n def try_convert_literal(\n self, literal: LiteralBuilder, location: SourceLocation\n ) -> InstanceBuilder | None:\n match literal.value:\n case int(int_value):\n if int_value < 0 or int_value.bit_length() > 64: # TODO: should this be 256?\n logger.error(\"invalid asset ID\", location=literal.source_location)\n const = UInt64Constant(value=int_value, source_location=location)\n expr = ReinterpretCast(\n expr=const, wtype=self.produces().wtype, source_location=location\n )\n return AssetExpressionBuilder(expr)\n return None\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.at_most_one_arg(args, location)\n match arg:\n case InstanceBuilder(pytype=pytypes.IntLiteralType):\n return arg.resolve_literal(AssetTypeBuilder(location))\n case None:\n uint64_expr: Expression = UInt64Constant(value=0, source_location=location)\n case _:\n arg = expect.argument_of_type_else_dummy(arg, pytypes.UInt64Type)\n uint64_expr = arg.resolve()\n asset_expr = ReinterpretCast(\n expr=uint64_expr, wtype=wtypes.asset_wtype, source_location=location\n )\n return AssetExpressionBuilder(asset_expr)\n\n\nASSET_HOLDING_FIELD_MAPPING: typing.Final = {\n \"balance\": (\"AssetBalance\", pytypes.UInt64Type),\n \"frozen\": (\"AssetFrozen\", pytypes.BoolType),\n}\n\n\nclass AssetHoldingExpressionBuilder(FunctionBuilder):\n def __init__(self, asset: Expression, holding_field: str, location: SourceLocation):\n self.asset = asset\n self.holding_field = holding_field\n super().__init__(location)\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.exactly_one_arg_of_type_else_dummy(args, pytypes.AccountType, location)\n account_expr = arg.resolve()\n immediate, typ = ASSET_HOLDING_FIELD_MAPPING[self.holding_field]\n asset_params_get = IntrinsicCall(\n source_location=location,\n wtype=wtypes.WTuple((typ.wtype, wtypes.bool_wtype), location),\n op_code=\"asset_holding_get\",\n immediates=[immediate],\n stack_args=[account_expr, self.asset],\n )\n return builder_for_instance(\n typ, CheckedMaybe(asset_params_get, comment=\"account opted into asset\")\n )\n\n\nclass AssetExpressionBuilder(UInt64BackedReferenceValueExpressionBuilder):\n def __init__(self, expr: Expression):\n native_access_member = \"id\"\n field_mapping = {\n \"total\": (\"AssetTotal\", pytypes.UInt64Type),\n \"decimals\": (\"AssetDecimals\", pytypes.UInt64Type),\n \"default_frozen\": (\"AssetDefaultFrozen\", pytypes.BoolType),\n \"unit_name\": (\"AssetUnitName\", pytypes.BytesType),\n \"name\": (\"AssetName\", pytypes.BytesType),\n \"url\": (\"AssetURL\", pytypes.BytesType),\n \"metadata_hash\": (\"AssetMetadataHash\", pytypes.BytesType),\n \"manager\": (\"AssetManager\", pytypes.AccountType),\n \"reserve\": (\"AssetReserve\", pytypes.AccountType),\n \"freeze\": (\"AssetFreeze\", pytypes.AccountType),\n \"clawback\": (\"AssetClawback\", pytypes.AccountType),\n \"creator\": (\"AssetCreator\", pytypes.AccountType),\n }\n field_op_code = \"asset_params_get\"\n field_bool_comment = \"asset exists\"\n super().__init__(\n expr,\n typ=pytypes.AssetType,\n typ_literal_converter=AssetTypeBuilder,\n native_access_member=native_access_member,\n field_mapping=field_mapping,\n field_op_code=field_op_code,\n field_bool_comment=field_bool_comment,\n )\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n if name in ASSET_HOLDING_FIELD_MAPPING:\n return AssetHoldingExpressionBuilder(self.resolve(), name, location)\n return super().member_access(name, location)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/reference_types\/asset.py","language":"Python","license":"NOASSERTION","size":5371} {"code":"from puyapy.awst_build.eb.storage.box import (\n BoxGenericTypeExpressionBuilder,\n BoxProxyExpressionBuilder,\n BoxTypeBuilder,\n)\nfrom puyapy.awst_build.eb.storage.box_map import (\n BoxMapGenericTypeExpressionBuilder,\n BoxMapProxyExpressionBuilder,\n BoxMapTypeBuilder,\n)\nfrom puyapy.awst_build.eb.storage.box_ref import (\n BoxRefProxyExpressionBuilder,\n BoxRefTypeBuilder,\n)\nfrom puyapy.awst_build.eb.storage.global_state import (\n GlobalStateExpressionBuilder,\n GlobalStateGenericTypeBuilder,\n GlobalStateTypeBuilder,\n)\nfrom puyapy.awst_build.eb.storage.local_state import (\n LocalStateExpressionBuilder,\n LocalStateGenericTypeBuilder,\n LocalStateTypeBuilder,\n)\n\n__all__ = [\n \"BoxTypeBuilder\",\n \"BoxGenericTypeExpressionBuilder\",\n \"BoxProxyExpressionBuilder\",\n \"BoxRefTypeBuilder\",\n \"BoxRefProxyExpressionBuilder\",\n \"BoxMapTypeBuilder\",\n \"BoxMapGenericTypeExpressionBuilder\",\n \"BoxMapProxyExpressionBuilder\",\n \"GlobalStateTypeBuilder\",\n \"GlobalStateGenericTypeBuilder\",\n \"GlobalStateExpressionBuilder\",\n \"LocalStateTypeBuilder\",\n \"LocalStateGenericTypeBuilder\",\n \"LocalStateExpressionBuilder\",\n]\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/storage\/__init__.py","language":"Python","license":"NOASSERTION","size":1179} {"code":"import abc\nimport typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya.awst.nodes import (\n BoxValueExpression,\n ExpressionStatement,\n StateDelete,\n StateGet,\n StateGetEx,\n Statement,\n)\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder\nfrom puyapy.awst_build.eb._utils import cast_to_bytes\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import InstanceBuilder, NodeBuilder\nfrom puyapy.awst_build.eb.storage._util import box_length_checked, index_box_bytes, slice_box_bytes\nfrom puyapy.awst_build.eb.storage._value_proxy import ValueProxyExpressionBuilder\nfrom puyapy.awst_build.eb.tuple import TupleExpressionBuilder\nfrom puyapy.awst_build.eb.uint64 import UInt64ExpressionBuilder\n\n\nclass _BoxKeyExpressionIntermediateExpressionBuilder(FunctionBuilder, abc.ABC):\n def __init__(self, box: BoxValueExpression, content_type: pytypes.PyType) -> None:\n super().__init__(box.source_location)\n self.box = box\n self.content_type = content_type\n\n\nclass BoxGetExpressionBuilder(_BoxKeyExpressionIntermediateExpressionBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n default_arg_inst = expect.exactly_one_arg_of_type_else_dummy(\n args, self.content_type, location\n )\n default_expr = default_arg_inst.resolve()\n return builder_for_instance(\n self.content_type,\n StateGet(field=self.box, default=default_expr, source_location=location),\n )\n\n\nclass BoxMaybeExpressionBuilder(_BoxKeyExpressionIntermediateExpressionBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n expect.no_args(args, location)\n result_type = pytypes.GenericTupleType.parameterise(\n [self.content_type, pytypes.BoolType], location\n )\n return TupleExpressionBuilder(\n StateGetEx(field=self.box, source_location=location),\n result_type,\n )\n\n\nclass BoxValueExpressionBuilder(ValueProxyExpressionBuilder[pytypes.PyType, BoxValueExpression]):\n \"\"\"This is used to intercept operations on Box and BoxMap values to use more efficient\n ops (i.e. box_extract, box_length) where possible and provide support for operations like\n delete\"\"\"\n\n @typing.override\n def delete(self, location: SourceLocation) -> Statement:\n return ExpressionStatement(\n expr=StateDelete(field=self.resolve(), source_location=location)\n )\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n if name == \"bytes\":\n return _ValueBytes(self.resolve(), location)\n else:\n return super().member_access(name, location)\n\n @typing.override\n def index(self, index: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n if pytypes.BytesType <= self.pytype:\n return index_box_bytes(self.resolve(), index, location)\n return super().index(index, location)\n\n @typing.override\n def slice_index(\n self,\n begin_index: InstanceBuilder | None,\n end_index: InstanceBuilder | None,\n stride: InstanceBuilder | None,\n location: SourceLocation,\n ) -> InstanceBuilder:\n if pytypes.BytesType <= self.pytype:\n return slice_box_bytes(self.resolve(), begin_index, end_index, stride, location)\n return super().slice_index(begin_index, end_index, stride, location)\n\n\nclass _ValueBytes(ValueProxyExpressionBuilder):\n def __init__(self, expr: BoxValueExpression, location: SourceLocation) -> None:\n self._typed = expr\n super().__init__(pytypes.BytesType, cast_to_bytes(expr, location))\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n match name:\n case \"length\":\n return UInt64ExpressionBuilder(box_length_checked(self._typed, location))\n case _:\n return super().member_access(name, location)\n\n @typing.override\n def index(self, index: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n return index_box_bytes(self._typed, index, location)\n\n @typing.override\n def slice_index(\n self,\n begin_index: InstanceBuilder | None,\n end_index: InstanceBuilder | None,\n stride: InstanceBuilder | None,\n location: SourceLocation,\n ) -> InstanceBuilder:\n return slice_box_bytes(self._typed, begin_index, end_index, stride, location)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/storage\/_common.py","language":"Python","license":"NOASSERTION","size":5010} {"code":"import typing\n\nimport attrs\n\nfrom puya import log\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import (\n BinaryBooleanOperator,\n BytesConstant,\n BytesEncoding,\n Expression,\n Lvalue,\n ReinterpretCast,\n Statement,\n)\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb.interface import (\n BuilderBinaryOp,\n BuilderComparisonOp,\n BuilderUnaryOp,\n InstanceBuilder,\n NodeBuilder,\n StorageProxyConstructorArgs,\n StorageProxyConstructorResult,\n TypeBuilder,\n)\n\nlogger = log.get_logger(__name__)\n\n\n@typing.final\nclass StorageProxyDefinitionBuilder(StorageProxyConstructorResult):\n def __init__(\n self,\n args: StorageProxyConstructorArgs,\n typ: pytypes.StorageProxyType | pytypes.StorageMapProxyType,\n location: SourceLocation,\n ):\n super().__init__(location)\n self._typ = typ\n self._args = args\n\n @typing.override\n @property\n def args(self) -> StorageProxyConstructorArgs:\n return self._args\n\n @typing.override\n @property\n def pytype(self) -> pytypes.StorageProxyType | pytypes.StorageMapProxyType:\n return self._typ\n\n @typing.override\n def to_bytes(self, location: SourceLocation) -> Expression:\n return self._assign_first(location)\n\n @typing.override\n def resolve(self) -> Expression:\n return self._assign_first(self.source_location)\n\n @typing.override\n def resolve_literal(self, converter: TypeBuilder) -> InstanceBuilder:\n return self.try_resolve_literal(converter)\n\n @typing.override\n def try_resolve_literal(self, converter: TypeBuilder) -> InstanceBuilder:\n return self\n\n @typing.override\n def resolve_lvalue(self) -> Lvalue:\n raise CodeError(f\"{self._typ} is not valid as an assignment target\", self.source_location)\n\n @typing.override\n def delete(self, location: SourceLocation) -> Statement:\n raise self._assign_first(location)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n return self._assign_first(location)\n\n @typing.override\n def unary_op(self, op: BuilderUnaryOp, location: SourceLocation) -> InstanceBuilder:\n return self._assign_first(location)\n\n @typing.override\n def contains(self, item: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n return self._assign_first(location)\n\n @typing.override\n def index(self, index: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n return self._assign_first(location)\n\n @typing.override\n def slice_index(\n self,\n begin_index: InstanceBuilder | None,\n end_index: InstanceBuilder | None,\n stride: InstanceBuilder | None,\n location: SourceLocation,\n ) -> InstanceBuilder:\n return self._assign_first(location)\n\n @typing.override\n def iterate(self) -> Expression:\n return self._assign_first(self.source_location)\n\n @typing.override\n def iterable_item_type(self) -> pytypes.PyType:\n return self._assign_first(self.source_location)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n return self._assign_first(location)\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n return self._assign_first(location)\n\n @typing.override\n def binary_op(\n self,\n other: InstanceBuilder,\n op: BuilderBinaryOp,\n location: SourceLocation,\n *,\n reverse: bool,\n ) -> InstanceBuilder:\n return self._assign_first(location)\n\n @typing.override\n def bool_binary_op(\n self, other: InstanceBuilder, op: BinaryBooleanOperator, location: SourceLocation\n ) -> InstanceBuilder:\n return self._assign_first(location)\n\n @typing.override\n def augmented_assignment(\n self, op: BuilderBinaryOp, rhs: InstanceBuilder, location: SourceLocation\n ) -> Statement:\n return self._assign_first(location)\n\n def _assign_first(self, location: SourceLocation) -> typing.Never:\n raise CodeError(\n f\"{self._typ} with inferred\"\n f\" key{'_prefix' if isinstance(self._typ, pytypes.StorageMapProxyType) else ''}\"\n \" must be assigned to an instance variable before being used\",\n location,\n )\n\n @typing.override\n def single_eval(self) -> InstanceBuilder:\n if self._args.initial_value is None:\n return self\n return StorageProxyDefinitionBuilder(\n attrs.evolve(self._args, initial_value=self._args.initial_value.single_eval()),\n typ=self._typ,\n location=self.source_location,\n )\n\n\ndef extract_key_override(\n key_arg: NodeBuilder | None, location: SourceLocation, *, typ: wtypes.WType\n) -> Expression | None:\n if key_arg is None:\n return None\n if isinstance(key_arg, InstanceBuilder) and key_arg.pytype.is_type_or_subtype(\n pytypes.StringType,\n pytypes.StrLiteralType,\n pytypes.BytesType,\n pytypes.BytesLiteralType,\n ):\n key_override = key_arg.to_bytes(key_arg.source_location)\n if isinstance(key_override, BytesConstant):\n return attrs.evolve(key_override, wtype=typ)\n else:\n return ReinterpretCast(expr=key_override, wtype=typ, source_location=location)\n else:\n expect.not_this_type(key_arg, default=expect.default_none)\n return BytesConstant(\n value=b\"0\",\n wtype=typ,\n encoding=BytesEncoding.unknown,\n source_location=key_arg.source_location,\n )\n\n\ndef extract_description(descr_arg: NodeBuilder | None) -> str | None:\n if descr_arg is None:\n return None\n return expect.simple_string_literal(descr_arg, default=expect.default_none)\n\n\ndef parse_storage_proxy_constructor_args(\n arg_mapping: dict[str, NodeBuilder],\n key_wtype: wtypes.WType,\n key_arg_name: str,\n descr_arg_name: str | None,\n location: SourceLocation,\n initial_value: InstanceBuilder | None = None,\n) -> StorageProxyConstructorArgs:\n key_arg = arg_mapping.get(key_arg_name)\n key_override = extract_key_override(key_arg, location, typ=key_wtype)\n\n description = None\n if descr_arg_name is not None:\n descr_arg = arg_mapping.get(descr_arg_name)\n description = extract_description(descr_arg)\n\n return StorageProxyConstructorArgs(\n key=key_override,\n description=description,\n initial_value=initial_value,\n key_arg_name=key_arg_name,\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/storage\/_storage.py","language":"Python","license":"NOASSERTION","size":6806} {"code":"from puya import log\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import (\n BoxValueExpression,\n CheckedMaybe,\n Expression,\n IntrinsicCall,\n NumericComparison,\n NumericComparisonExpression,\n TupleItemExpression,\n UInt64BinaryOperation,\n UInt64BinaryOperator,\n UInt64Constant,\n)\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import intrinsic_factory, pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._utils import resolve_negative_literal_index\nfrom puyapy.awst_build.eb.bytes import BytesExpressionBuilder\nfrom puyapy.awst_build.eb.interface import (\n BuilderBinaryOp,\n InstanceBuilder,\n LiteralBuilder,\n NodeBuilder,\n)\nfrom puyapy.awst_build.eb.uint64 import UInt64ExpressionBuilder\n\nlogger = log.get_logger(__name__)\n\n\ndef index_box_bytes(\n box: BoxValueExpression,\n index: InstanceBuilder,\n location: SourceLocation,\n) -> InstanceBuilder:\n box_length = box_length_unchecked(box, location)\n begin_index = resolve_negative_literal_index(index, box_length, location)\n return BytesExpressionBuilder(\n IntrinsicCall(\n op_code=\"box_extract\",\n stack_args=[\n box.key,\n begin_index.resolve(),\n UInt64Constant(value=1, source_location=location),\n ],\n source_location=location,\n wtype=wtypes.bytes_wtype,\n )\n )\n\n\ndef slice_box_bytes(\n box: BoxValueExpression,\n begin_index: InstanceBuilder | None,\n end_index: InstanceBuilder | None,\n stride: InstanceBuilder | None,\n location: SourceLocation,\n) -> InstanceBuilder:\n if stride:\n logger.error(\"stride is not supported when slicing boxes\", location=location)\n len_expr = box_length_unchecked(box, location).single_eval().resolve()\n\n begin_index_expr = _eval_slice_component(len_expr, begin_index, location) or UInt64Constant(\n value=0, source_location=location\n )\n end_index_expr = _eval_slice_component(len_expr, end_index, location) or len_expr\n length_expr = (\n UInt64ExpressionBuilder(end_index_expr)\n .binary_op(\n UInt64ExpressionBuilder(begin_index_expr), BuilderBinaryOp.sub, location, reverse=False\n )\n .resolve()\n )\n\n return BytesExpressionBuilder(\n IntrinsicCall(\n op_code=\"box_extract\",\n stack_args=[box.key, begin_index_expr, length_expr],\n source_location=location,\n wtype=wtypes.bytes_wtype,\n )\n )\n\n\ndef box_length_unchecked(box: BoxValueExpression, location: SourceLocation) -> InstanceBuilder:\n box_len_expr = _box_len(box.key, location)\n box_length = TupleItemExpression(\n base=box_len_expr,\n index=0,\n source_location=location,\n )\n return UInt64ExpressionBuilder(box_length)\n\n\ndef box_length_checked(box: BoxValueExpression, location: SourceLocation) -> Expression:\n box_len_expr = _box_len(box.key, location)\n return CheckedMaybe(box_len_expr, comment=box.exists_assertion_message or \"box exists\")\n\n\ndef _box_len(box_key: Expression, location: SourceLocation) -> IntrinsicCall:\n assert box_key.wtype == wtypes.box_key\n return IntrinsicCall(\n op_code=\"box_len\",\n wtype=wtypes.WTuple([wtypes.uint64_wtype, wtypes.bool_wtype], source_location=location),\n stack_args=[box_key],\n source_location=location,\n )\n\n\ndef _eval_slice_component(\n len_expr: Expression, val: NodeBuilder | None, location: SourceLocation\n) -> Expression | None:\n if val is None:\n return None\n\n if not isinstance(val, LiteralBuilder):\n # no negatives to deal with here, easy\n temp_index = (\n expect.argument_of_type_else_dummy(val, pytypes.UInt64Type).single_eval().resolve()\n )\n return intrinsic_factory.select(\n false=len_expr,\n true=temp_index,\n condition=NumericComparisonExpression(\n lhs=temp_index,\n operator=NumericComparison.lt,\n rhs=len_expr,\n source_location=location,\n ),\n loc=location,\n )\n\n int_lit = val.value\n if not isinstance(int_lit, int):\n logger.error(f\"Invalid literal for slicing: {int_lit!r}\", location=val.source_location)\n int_lit = 0\n\n # take the min of abs(int_lit) and len(self.expr)\n abs_lit_expr = UInt64Constant(value=abs(int_lit), source_location=val.source_location)\n trunc_value_expr = intrinsic_factory.select(\n false=len_expr,\n true=abs_lit_expr,\n condition=NumericComparisonExpression(\n lhs=abs_lit_expr,\n operator=NumericComparison.lt,\n rhs=len_expr,\n source_location=location,\n ),\n loc=location,\n )\n return (\n trunc_value_expr\n if int_lit >= 0\n else UInt64BinaryOperation(\n left=len_expr,\n op=UInt64BinaryOperator.sub,\n right=trunc_value_expr,\n source_location=location,\n )\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/storage\/_util.py","language":"Python","license":"NOASSERTION","size":5069} {"code":"import typing\n\nimport typing_extensions\n\nfrom puya.awst.nodes import Expression, Statement\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb._base import (\n InstanceExpressionBuilder,\n)\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import (\n BuilderBinaryOp,\n BuilderComparisonOp,\n BuilderUnaryOp,\n InstanceBuilder,\n NodeBuilder,\n)\n\n_TPyType_co = typing_extensions.TypeVar(\n \"_TPyType_co\", bound=pytypes.PyType, default=pytypes.PyType, covariant=True\n)\n_TExpression_co = typing_extensions.TypeVar(\n \"_TExpression_co\", bound=Expression, default=Expression, covariant=True\n)\n\n\nclass ValueProxyExpressionBuilder(InstanceExpressionBuilder[_TPyType_co, _TExpression_co]):\n def __init__(self, typ: _TPyType_co, expr: _TExpression_co):\n super().__init__(typ, expr)\n\n @property\n def _proxied(self) -> InstanceBuilder:\n return builder_for_instance(self.pytype, self.resolve())\n\n @typing.override\n def to_bytes(self, location: SourceLocation) -> Expression:\n return self._proxied.to_bytes(location)\n\n @typing.override\n def delete(self, location: SourceLocation) -> Statement:\n return self._proxied.delete(location)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n return self._proxied.bool_eval(location, negate=negate)\n\n @typing.override\n def unary_op(self, op: BuilderUnaryOp, location: SourceLocation) -> InstanceBuilder:\n return self._proxied.unary_op(op, location)\n\n @typing.override\n def contains(self, item: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n return self._proxied.contains(item, location)\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n return self._proxied.compare(other, op, location)\n\n @typing.override\n def binary_op(\n self,\n other: InstanceBuilder,\n op: BuilderBinaryOp,\n location: SourceLocation,\n *,\n reverse: bool,\n ) -> InstanceBuilder:\n return self._proxied.binary_op(other, op, location, reverse=reverse)\n\n @typing.override\n def augmented_assignment(\n self, op: BuilderBinaryOp, rhs: InstanceBuilder, location: SourceLocation\n ) -> Statement:\n return self._proxied.augmented_assignment(op, rhs, location)\n\n @typing.override\n def index(self, index: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n return self._proxied.index(index, location)\n\n @typing.override\n def slice_index(\n self,\n begin_index: InstanceBuilder | None,\n end_index: InstanceBuilder | None,\n stride: InstanceBuilder | None,\n location: SourceLocation,\n ) -> InstanceBuilder:\n return self._proxied.slice_index(begin_index, end_index, stride, location)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n return self._proxied.member_access(name, location)\n\n @typing.override\n def iterate(self) -> Expression:\n return self._proxied.iterate()\n\n @typing.override\n def iterable_item_type(self) -> pytypes.PyType:\n return self._proxied.iterable_item_type()\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/storage\/_value_proxy.py","language":"Python","license":"NOASSERTION","size":3393} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import BoxValueExpression, Expression, Not, StateExists\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb._base import GenericTypeBuilder, NotIterableInstanceExpressionBuilder\nfrom puyapy.awst_build.eb._bytes_backed import BytesBackedInstanceExpressionBuilder\nfrom puyapy.awst_build.eb.bool import BoolExpressionBuilder\nfrom puyapy.awst_build.eb.interface import (\n InstanceBuilder,\n NodeBuilder,\n StorageProxyConstructorArgs,\n StorageProxyConstructorResult,\n TypeBuilder,\n)\nfrom puyapy.awst_build.eb.storage._common import (\n BoxGetExpressionBuilder,\n BoxMaybeExpressionBuilder,\n BoxValueExpressionBuilder,\n)\nfrom puyapy.awst_build.eb.storage._storage import (\n StorageProxyDefinitionBuilder,\n parse_storage_proxy_constructor_args,\n)\nfrom puyapy.awst_build.eb.storage._util import box_length_checked\nfrom puyapy.awst_build.eb.uint64 import UInt64ExpressionBuilder\nfrom puyapy.awst_build.utils import get_arg_mapping\n\nlogger = log.get_logger(__name__)\n\n\nclass BoxTypeBuilder(TypeBuilder[pytypes.StorageProxyType]):\n def __init__(self, typ: pytypes.PyType, location: SourceLocation) -> None:\n assert isinstance(typ, pytypes.StorageProxyType)\n assert typ.generic == pytypes.GenericBoxType\n super().__init__(typ, location)\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n return _init(args, arg_names, location, result_type=self.produces())\n\n\nclass BoxGenericTypeExpressionBuilder(GenericTypeBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n return _init(args, arg_names, location, result_type=None)\n\n\ndef _init(\n args: Sequence[NodeBuilder],\n arg_names: list[str | None],\n location: SourceLocation,\n *,\n result_type: pytypes.StorageProxyType | None,\n) -> InstanceBuilder:\n type_arg_name = \"type_\"\n key_arg_name = \"key\"\n arg_mapping, _ = get_arg_mapping(\n required_positional_names=[type_arg_name],\n optional_kw_only=[key_arg_name],\n args=args,\n arg_names=arg_names,\n call_location=location,\n raise_on_missing=True,\n )\n type_arg = arg_mapping[type_arg_name]\n match type_arg.pytype:\n case pytypes.TypeType(typ=content):\n pass\n case _:\n raise CodeError(\"first argument must be a type reference\", location)\n\n if result_type is None:\n result_type = pytypes.GenericBoxType.parameterise([content], location)\n elif result_type.content != content:\n logger.error(\n \"explicit type annotation does not match first argument\"\n \" - suggest to remove the explicit type annotation, it shouldn't be required\",\n location=location,\n )\n\n typed_args = parse_storage_proxy_constructor_args(\n arg_mapping,\n key_wtype=wtypes.box_key,\n key_arg_name=key_arg_name,\n descr_arg_name=None,\n location=location,\n )\n\n if typed_args.key is None:\n return StorageProxyDefinitionBuilder(typed_args, result_type, location)\n return _BoxProxyExpressionBuilderFromConstructor(typed_args, result_type)\n\n\nclass BoxProxyExpressionBuilder(\n NotIterableInstanceExpressionBuilder[pytypes.StorageProxyType],\n BytesBackedInstanceExpressionBuilder[pytypes.StorageProxyType],\n bytes_member=\"key\",\n):\n def __init__(self, expr: Expression, typ: pytypes.PyType, member_name: str | None = None):\n assert isinstance(typ, pytypes.StorageProxyType)\n assert typ.generic == pytypes.GenericBoxType\n self._member_name = member_name\n super().__init__(typ, expr)\n\n def _box_key_expr(self, location: SourceLocation) -> BoxValueExpression:\n if self._member_name:\n exists_assertion_message = f\"check self.{self._member_name} exists\"\n else:\n exists_assertion_message = \"check Box exists\"\n return BoxValueExpression(\n key=self.resolve(),\n wtype=self.pytype.content_wtype,\n exists_assertion_message=exists_assertion_message,\n source_location=location,\n )\n\n def _get_value(self, location: SourceLocation) -> BoxValueExpressionBuilder:\n return BoxValueExpressionBuilder(self.pytype.content, self._box_key_expr(location))\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n match name:\n case \"value\":\n return self._get_value(location)\n case \"get\":\n return BoxGetExpressionBuilder(\n self._box_key_expr(location), content_type=self.pytype.content\n )\n case \"maybe\":\n return BoxMaybeExpressionBuilder(\n self._box_key_expr(location), content_type=self.pytype.content\n )\n case \"length\":\n return UInt64ExpressionBuilder(\n box_length_checked(self._get_value(location).resolve(), location)\n )\n return super().member_access(name, location)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n box_exists = StateExists(\n field=self._box_key_expr(location),\n source_location=location,\n )\n return BoolExpressionBuilder(\n Not(expr=box_exists, source_location=location) if negate else box_exists\n )\n\n\nclass _BoxProxyExpressionBuilderFromConstructor(\n BoxProxyExpressionBuilder, StorageProxyConstructorResult\n):\n def __init__(self, args: StorageProxyConstructorArgs, typ: pytypes.StorageProxyType):\n assert args.key is not None\n super().__init__(args.key, typ, member_name=None)\n self._args = args\n\n @typing.override\n @property\n def args(self) -> StorageProxyConstructorArgs:\n return self._args\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/storage\/box.py","language":"Python","license":"NOASSERTION","size":6382} {"code":"import abc\nimport typing\nfrom collections.abc import Callable, Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import (\n BoxValueExpression,\n Expression,\n StateExists,\n StateGet,\n StateGetEx,\n)\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import intrinsic_factory, pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder, GenericTypeBuilder\nfrom puyapy.awst_build.eb._bytes_backed import BytesBackedInstanceExpressionBuilder\nfrom puyapy.awst_build.eb._utils import dummy_value\nfrom puyapy.awst_build.eb.bool import BoolExpressionBuilder\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import (\n InstanceBuilder,\n NodeBuilder,\n StorageProxyConstructorArgs,\n StorageProxyConstructorResult,\n TypeBuilder,\n)\nfrom puyapy.awst_build.eb.storage._common import BoxValueExpressionBuilder\nfrom puyapy.awst_build.eb.storage._storage import (\n StorageProxyDefinitionBuilder,\n parse_storage_proxy_constructor_args,\n)\nfrom puyapy.awst_build.eb.storage._util import box_length_checked\nfrom puyapy.awst_build.eb.tuple import TupleExpressionBuilder\nfrom puyapy.awst_build.eb.uint64 import UInt64ExpressionBuilder\nfrom puyapy.awst_build.utils import get_arg_mapping\n\nlogger = log.get_logger(__name__)\n\n\nclass BoxMapTypeBuilder(TypeBuilder[pytypes.StorageMapProxyType]):\n def __init__(self, typ: pytypes.PyType, location: SourceLocation) -> None:\n assert isinstance(typ, pytypes.StorageMapProxyType)\n assert typ.generic == pytypes.GenericBoxMapType\n super().__init__(typ, location)\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n return _init(args, arg_names, location, result_type=self.produces())\n\n\nclass BoxMapGenericTypeExpressionBuilder(GenericTypeBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n return _init(args, arg_names, location, result_type=None)\n\n\ndef _init(\n args: Sequence[NodeBuilder],\n arg_names: list[str | None],\n location: SourceLocation,\n *,\n result_type: pytypes.StorageMapProxyType | None,\n) -> InstanceBuilder:\n key_type_arg_name = \"key_type\"\n value_type_arg_name = \"value_type\"\n key_prefix_arg_name = \"key_prefix\"\n\n arg_mapping, _ = get_arg_mapping(\n required_positional_names=[key_type_arg_name, value_type_arg_name],\n optional_kw_only=[key_prefix_arg_name],\n args=args,\n arg_names=arg_names,\n call_location=location,\n raise_on_missing=True,\n )\n key_type_arg = arg_mapping[key_type_arg_name]\n value_type_arg = arg_mapping[value_type_arg_name]\n match key_type_arg.pytype, value_type_arg.pytype:\n case pytypes.TypeType(typ=key), pytypes.TypeType(typ=content):\n pass\n case _:\n raise CodeError(\"first and second arguments must be type references\", location)\n\n if result_type is None:\n result_type = pytypes.GenericBoxMapType.parameterise([key, content], location)\n elif not (result_type.key == key and result_type.content == content):\n logger.error(\n \"explicit type annotation does not match first argument\"\n \" - suggest to remove the explicit type annotation, it shouldn't be required\",\n location=location,\n )\n # the type of the key is not retained in the AWST, so to\n wtypes.validate_persistable(result_type.key_wtype, location)\n\n typed_args = parse_storage_proxy_constructor_args(\n arg_mapping,\n key_wtype=wtypes.box_key,\n key_arg_name=key_prefix_arg_name,\n descr_arg_name=None,\n location=location,\n )\n\n if typed_args.key is None:\n return StorageProxyDefinitionBuilder(typed_args, result_type, location)\n return _BoxMapProxyExpressionBuilderFromConstructor(typed_args, result_type)\n\n\nclass BoxMapProxyExpressionBuilder(\n BytesBackedInstanceExpressionBuilder[pytypes.StorageMapProxyType], bytes_member=\"key_prefix\"\n):\n def __init__(self, expr: Expression, typ: pytypes.PyType, member_name: str | None = None):\n assert isinstance(typ, pytypes.StorageMapProxyType)\n assert typ.generic == pytypes.GenericBoxMapType\n self._member_name = member_name\n super().__init__(typ, expr)\n\n def _build_box_value(\n self, key: InstanceBuilder, location: SourceLocation\n ) -> BoxValueExpression:\n key_data = key.to_bytes(location)\n key_prefix = self.resolve()\n full_key = intrinsic_factory.concat(\n key_prefix, key_data, location, result_type=wtypes.box_key\n )\n if self._member_name:\n exists_assertion_message = f\"check self.{self._member_name} entry exists\"\n else:\n exists_assertion_message = \"check BoxMap entry exists\"\n return BoxValueExpression(\n key=full_key,\n wtype=self.pytype.content_wtype,\n exists_assertion_message=exists_assertion_message,\n source_location=location,\n )\n\n @typing.override\n def index(self, index: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n return BoxValueExpressionBuilder(\n self.pytype.content, self._build_box_value(index, location)\n )\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n match name:\n case \"length\":\n return _Length(location, self._build_box_value, self.pytype)\n case \"maybe\":\n return _Maybe(location, self._build_box_value, self.pytype)\n case \"get\":\n return _Get(location, self._build_box_value, self.pytype)\n case _:\n return super().member_access(name, location)\n\n @typing.override\n def contains(self, item: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n box_exists = StateExists(\n field=self._build_box_value(item, location), source_location=location\n )\n return BoolExpressionBuilder(box_exists)\n\n @typing.override\n def slice_index(\n self,\n begin_index: InstanceBuilder | None,\n end_index: InstanceBuilder | None,\n stride: InstanceBuilder | None,\n location: SourceLocation,\n ) -> InstanceBuilder:\n raise CodeError(\"slicing of BoxMap is not supported\", location)\n\n @typing.override\n def iterate(self) -> typing.Never: # pragma: no cover\n raise CodeError(\"iteration of BoxMap is not supported\", self.source_location)\n\n @typing.override\n def iterable_item_type(self) -> typing.Never:\n self.iterate()\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n raise CodeError(\"cannot determine if a BoxMap is empty or not\", location)\n\n\nclass _BoxMapProxyExpressionBuilderFromConstructor(\n BoxMapProxyExpressionBuilder, StorageProxyConstructorResult\n):\n def __init__(self, args: StorageProxyConstructorArgs, typ: pytypes.StorageMapProxyType):\n assert args.key is not None\n super().__init__(args.key, typ, member_name=None)\n self._args = args\n\n @typing.override\n @property\n def args(self) -> StorageProxyConstructorArgs:\n return self._args\n\n\nBoxValueBuilder = Callable[[InstanceBuilder, SourceLocation], BoxValueExpression]\n\n\nclass _MethodBase(FunctionBuilder, abc.ABC):\n def __init__(\n self,\n location: SourceLocation,\n box_value_builder: BoxValueBuilder,\n box_type: pytypes.StorageMapProxyType,\n ) -> None:\n super().__init__(location)\n self.build_box_value = box_value_builder\n self.box_type = box_type\n\n\nclass _Length(_MethodBase):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n key_arg_name = \"key\"\n args_map, any_missing = get_arg_mapping(\n required_positional_names=[key_arg_name],\n args=args,\n arg_names=arg_names,\n call_location=location,\n raise_on_missing=False,\n )\n if any_missing:\n return dummy_value(pytypes.UInt64Type, location)\n\n key_arg = expect.argument_of_type_else_dummy(\n args_map[key_arg_name], self.box_type.key, resolve_literal=True\n )\n key = self.build_box_value(key_arg, location)\n return UInt64ExpressionBuilder(box_length_checked(key, location))\n\n\nclass _Get(_MethodBase):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n key_arg_name = \"key\"\n default_arg_name = \"default\"\n args_map, any_missing = get_arg_mapping(\n required_positional_names=[key_arg_name],\n required_kw_only=[default_arg_name],\n args=args,\n arg_names=arg_names,\n call_location=location,\n raise_on_missing=False,\n )\n if any_missing:\n return dummy_value(self.box_type.content, location)\n key_arg = expect.argument_of_type_else_dummy(args_map[key_arg_name], self.box_type.key)\n default_arg = expect.argument_of_type_else_dummy(\n args_map[default_arg_name], self.box_type.content\n )\n key = self.build_box_value(key_arg, location)\n result_expr = StateGet(default=default_arg.resolve(), field=key, source_location=location)\n return builder_for_instance(self.box_type.content, result_expr)\n\n\nclass _Maybe(_MethodBase):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n result_typ = pytypes.GenericTupleType.parameterise(\n [self.box_type.content, pytypes.BoolType], location\n )\n key_arg_name = \"key\"\n args_map, any_missing = get_arg_mapping(\n required_positional_names=[key_arg_name],\n args=args,\n arg_names=arg_names,\n call_location=location,\n raise_on_missing=False,\n )\n if any_missing:\n return dummy_value(result_typ, location)\n item_key_inst = expect.argument_of_type_else_dummy(\n args_map[key_arg_name], self.box_type.key\n )\n key = self.build_box_value(item_key_inst, location)\n return TupleExpressionBuilder(StateGetEx(field=key, source_location=location), result_typ)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/storage\/box_map.py","language":"Python","license":"NOASSERTION","size":11175} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import BoxValueExpression, Expression, IntrinsicCall, Not, StateExists\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder, NotIterableInstanceExpressionBuilder\nfrom puyapy.awst_build.eb._bytes_backed import BytesBackedInstanceExpressionBuilder\nfrom puyapy.awst_build.eb._utils import dummy_value\nfrom puyapy.awst_build.eb.bool import BoolExpressionBuilder\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import (\n InstanceBuilder,\n NodeBuilder,\n StorageProxyConstructorArgs,\n StorageProxyConstructorResult,\n TypeBuilder,\n)\nfrom puyapy.awst_build.eb.none import NoneExpressionBuilder\nfrom puyapy.awst_build.eb.storage._common import BoxGetExpressionBuilder, BoxMaybeExpressionBuilder\nfrom puyapy.awst_build.eb.storage._storage import (\n StorageProxyDefinitionBuilder,\n parse_storage_proxy_constructor_args,\n)\nfrom puyapy.awst_build.eb.storage._util import box_length_checked\nfrom puyapy.awst_build.eb.uint64 import UInt64ExpressionBuilder\nfrom puyapy.awst_build.utils import get_arg_mapping\n\n\nclass BoxRefTypeBuilder(TypeBuilder[pytypes.StorageProxyType]):\n def __init__(self, location: SourceLocation) -> None:\n super().__init__(pytypes.BoxRefType, location)\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n key_arg_name = \"key\"\n arg_mapping, _ = get_arg_mapping(\n optional_kw_only=[key_arg_name],\n args=args,\n arg_names=arg_names,\n call_location=location,\n raise_on_missing=False,\n )\n typed_args = parse_storage_proxy_constructor_args(\n arg_mapping,\n key_wtype=wtypes.box_key,\n key_arg_name=key_arg_name,\n descr_arg_name=None,\n location=location,\n )\n\n if typed_args.key is None:\n return StorageProxyDefinitionBuilder(typed_args, self.produces(), location)\n return _BoxRefProxyExpressionBuilderFromConstructor(typed_args)\n\n\nclass BoxRefProxyExpressionBuilder(\n NotIterableInstanceExpressionBuilder[pytypes.StorageProxyType],\n BytesBackedInstanceExpressionBuilder[pytypes.StorageProxyType],\n bytes_member=\"key\",\n):\n def __init__(self, expr: Expression, member_name: str | None = None):\n super().__init__(pytypes.BoxRefType, expr)\n self._member_name = member_name\n\n def _box_key_expr(self, location: SourceLocation) -> BoxValueExpression:\n if self._member_name:\n exists_assertion_message = f\"check self.{self._member_name} exists\"\n else:\n exists_assertion_message = \"check BoxRef exists\"\n return BoxValueExpression(\n key=self.resolve(),\n wtype=wtypes.bytes_wtype,\n exists_assertion_message=exists_assertion_message,\n source_location=location,\n )\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n box_exists = StateExists(\n field=self._box_key_expr(location),\n source_location=location,\n )\n return BoolExpressionBuilder(\n Not(expr=box_exists, source_location=location) if negate else box_exists\n )\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n match name:\n case \"create\":\n return _Create(location, box_proxy=self.resolve())\n case \"delete\":\n return _IntrinsicMethod(\n location,\n box_proxy=self.resolve(),\n op_code=\"box_del\",\n args={},\n return_type=pytypes.BoolType,\n )\n case \"extract\":\n return _IntrinsicMethod(\n location,\n box_proxy=self.resolve(),\n op_code=\"box_extract\",\n args={\"start_index\": pytypes.UInt64Type, \"length\": pytypes.UInt64Type},\n return_type=pytypes.BytesType,\n )\n case \"resize\":\n return _IntrinsicMethod(\n location,\n box_proxy=self.resolve(),\n op_code=\"box_resize\",\n args={\"new_size\": pytypes.UInt64Type},\n return_type=pytypes.NoneType,\n )\n case \"replace\":\n return _IntrinsicMethod(\n location,\n box_proxy=self.resolve(),\n op_code=\"box_replace\",\n args={\"start_index\": pytypes.UInt64Type, \"value\": pytypes.BytesType},\n return_type=pytypes.NoneType,\n )\n case \"splice\":\n return _IntrinsicMethod(\n location,\n box_proxy=self.resolve(),\n op_code=\"box_splice\",\n args={\n \"start_index\": pytypes.UInt64Type,\n \"length\": pytypes.UInt64Type,\n \"value\": pytypes.BytesType,\n },\n return_type=pytypes.NoneType,\n )\n\n case \"get\":\n return BoxGetExpressionBuilder(\n self._box_key_expr(location), content_type=pytypes.BytesType\n )\n case \"put\":\n return _Put(location, box_proxy=self.resolve())\n case \"maybe\":\n return BoxMaybeExpressionBuilder(\n self._box_key_expr(location), content_type=pytypes.BytesType\n )\n case \"length\":\n return UInt64ExpressionBuilder(\n box_length_checked(self._box_key_expr(location), location)\n )\n case _:\n return super().member_access(name, location)\n\n\nclass _BoxRefProxyExpressionBuilderFromConstructor(\n BoxRefProxyExpressionBuilder, StorageProxyConstructorResult\n):\n def __init__(self, args: StorageProxyConstructorArgs):\n assert args.key is not None\n super().__init__(args.key, member_name=None)\n self._args = args\n\n @typing.override\n @property\n def args(self) -> StorageProxyConstructorArgs:\n return self._args\n\n\nclass _IntrinsicMethod(FunctionBuilder):\n def __init__(\n self,\n location: SourceLocation,\n *,\n box_proxy: Expression,\n op_code: str,\n args: dict[str, pytypes.PyType],\n return_type: pytypes.RuntimeType,\n ) -> None:\n super().__init__(location)\n self.box_proxy = box_proxy\n self.op_code = op_code\n self.args = args\n self.return_type = return_type\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n args_map, any_missing = get_arg_mapping(\n required_positional_names=list(self.args.keys()),\n args=args,\n arg_names=arg_names,\n call_location=location,\n raise_on_missing=False,\n )\n if any_missing:\n return dummy_value(self.return_type, location)\n stack_args = [\n expect.argument_of_type_else_dummy(\n args_map[arg_name], arg_type, resolve_literal=True\n ).resolve()\n for arg_name, arg_type in self.args.items()\n ]\n result_expr = IntrinsicCall(\n op_code=self.op_code,\n stack_args=[self.box_proxy, *stack_args],\n wtype=self.return_type.wtype,\n source_location=location,\n )\n return builder_for_instance(self.return_type, result_expr)\n\n\nclass _Create(FunctionBuilder):\n def __init__(self, location: SourceLocation, *, box_proxy: Expression) -> None:\n super().__init__(location)\n self.box_proxy = box_proxy\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.exactly_one_arg_of_type_else_dummy(\n args, pytypes.UInt64Type, location, resolve_literal=True\n )\n size = arg.resolve()\n return BoolExpressionBuilder(\n IntrinsicCall(\n op_code=\"box_create\",\n stack_args=[self.box_proxy, size],\n wtype=wtypes.bool_wtype,\n source_location=location,\n )\n )\n\n\nclass _Put(FunctionBuilder):\n def __init__(self, location: SourceLocation, *, box_proxy: Expression) -> None:\n super().__init__(location)\n self.box_proxy = box_proxy\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.exactly_one_arg_of_type_else_dummy(\n args, pytypes.BytesType, location, resolve_literal=True\n )\n data = arg.resolve()\n return NoneExpressionBuilder(\n IntrinsicCall(\n op_code=\"box_put\",\n stack_args=[self.box_proxy, data],\n wtype=wtypes.void_wtype,\n source_location=location,\n )\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/storage\/box_ref.py","language":"Python","license":"NOASSERTION","size":9889} {"code":"import abc\nimport typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import (\n AppStateExpression,\n Expression,\n ExpressionStatement,\n Not,\n StateDelete,\n StateExists,\n StateGet,\n StateGetEx,\n Statement,\n)\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import (\n FunctionBuilder,\n GenericTypeBuilder,\n NotIterableInstanceExpressionBuilder,\n)\nfrom puyapy.awst_build.eb._bytes_backed import BytesBackedInstanceExpressionBuilder\nfrom puyapy.awst_build.eb.bool import BoolExpressionBuilder\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import (\n InstanceBuilder,\n NodeBuilder,\n StorageProxyConstructorArgs,\n StorageProxyConstructorResult,\n TypeBuilder,\n)\nfrom puyapy.awst_build.eb.storage._storage import (\n StorageProxyDefinitionBuilder,\n parse_storage_proxy_constructor_args,\n)\nfrom puyapy.awst_build.eb.storage._value_proxy import ValueProxyExpressionBuilder\nfrom puyapy.awst_build.eb.tuple import TupleExpressionBuilder\nfrom puyapy.awst_build.utils import get_arg_mapping\n\nlogger = log.get_logger(__name__)\n\n\nclass GlobalStateTypeBuilder(TypeBuilder[pytypes.StorageProxyType]):\n def __init__(self, typ: pytypes.PyType, location: SourceLocation) -> None:\n assert isinstance(typ, pytypes.StorageProxyType)\n assert typ.generic == pytypes.GenericGlobalStateType\n self._typ = typ\n super().__init__(typ, location)\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n return _init(args, arg_names, location, result_type=self._typ)\n\n\nclass GlobalStateGenericTypeBuilder(GenericTypeBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n return _init(args, arg_names, location, result_type=None)\n\n\ndef _init(\n args: Sequence[NodeBuilder],\n arg_names: list[str | None],\n location: SourceLocation,\n *,\n result_type: pytypes.StorageProxyType | None,\n) -> InstanceBuilder:\n type_or_value_arg_name = \"type_or_initial_value\"\n key_arg_name = \"key\"\n descr_arg_name = \"description\"\n arg_mapping, _ = get_arg_mapping(\n required_positional_names=[type_or_value_arg_name],\n optional_kw_only=[key_arg_name, descr_arg_name],\n args=args,\n arg_names=arg_names,\n call_location=location,\n raise_on_missing=True,\n )\n\n match arg_mapping[type_or_value_arg_name]:\n case NodeBuilder(pytype=pytypes.TypeType(typ=content)):\n iv_builder = None\n if result_type is None:\n result_type = pytypes.GenericGlobalStateType.parameterise([content], location)\n elif result_type.content != content:\n logger.error(\n \"explicit type annotation does not match first argument\"\n \" - suggest to remove the explicit type annotation, it shouldn't be required\",\n location=location,\n )\n case value_arg if result_type is not None:\n iv_builder = expect.argument_of_type_else_dummy(value_arg, result_type.content)\n case InstanceBuilder(pytype=content) as iv_builder:\n result_type = pytypes.GenericGlobalStateType.parameterise([content], location)\n case _:\n raise CodeError(\n \"first argument must be a type reference or an initial value\", location\n )\n\n typed_args = parse_storage_proxy_constructor_args(\n arg_mapping,\n key_wtype=wtypes.state_key,\n key_arg_name=key_arg_name,\n descr_arg_name=descr_arg_name,\n initial_value=iv_builder,\n location=location,\n )\n\n if typed_args.key is None:\n return StorageProxyDefinitionBuilder(typed_args, result_type, location)\n return _GlobalStateExpressionBuilderFromConstructor(typed_args, result_type)\n\n\nclass GlobalStateExpressionBuilder(\n NotIterableInstanceExpressionBuilder[pytypes.StorageProxyType],\n BytesBackedInstanceExpressionBuilder[pytypes.StorageProxyType],\n bytes_member=\"key\",\n):\n def __init__(self, expr: Expression, typ: pytypes.PyType, member_name: str | None = None):\n assert isinstance(typ, pytypes.StorageProxyType)\n assert typ.generic == pytypes.GenericGlobalStateType\n self.member_name: typing.Final = member_name\n super().__init__(typ, expr)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n field = _build_field(self, location)\n exists_expr = StateExists(field=field, source_location=location)\n if negate:\n expr: Expression = Not(location, exists_expr)\n else:\n expr = exists_expr\n return BoolExpressionBuilder(expr)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n match name:\n case \"value\":\n field = _build_field(self, location)\n return _Value(self.pytype.content, field)\n case \"get\":\n return _Get(self, location)\n case \"maybe\":\n return _Maybe(self, location)\n case _:\n return super().member_access(name, location)\n\n\ndef _build_field(\n self: GlobalStateExpressionBuilder, location: SourceLocation\n) -> AppStateExpression:\n if self.member_name:\n exists_assertion_message = f\"check self.{self.member_name} exists\"\n else:\n exists_assertion_message = \"check GlobalState exists\"\n return AppStateExpression(\n key=self.resolve(),\n wtype=self.pytype.content_wtype,\n exists_assertion_message=exists_assertion_message,\n source_location=location,\n )\n\n\nclass _GlobalStateExpressionBuilderFromConstructor(\n GlobalStateExpressionBuilder, StorageProxyConstructorResult\n):\n def __init__(self, args: StorageProxyConstructorArgs, typ: pytypes.StorageProxyType):\n assert args.key is not None\n super().__init__(args.key, typ, member_name=None)\n self._args = args\n\n @typing.override\n @property\n def args(self) -> StorageProxyConstructorArgs:\n return self._args\n\n @typing.override\n def resolve(self) -> Expression:\n if self._args.initial_value is not None:\n logger.error(\n \"providing an initial value is only allowed when assigning to a member variable\",\n location=self.source_location,\n )\n return super().resolve()\n\n\nclass _MemberFunction(FunctionBuilder, abc.ABC):\n def __init__(self, base: GlobalStateExpressionBuilder, location: SourceLocation):\n super().__init__(location)\n self._base = base\n\n\nclass _Maybe(_MemberFunction):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n content_typ = self._base.pytype.content\n expect.no_args(args, location)\n field = _build_field(self._base, self.source_location)\n expr = StateGetEx(field=field, source_location=location)\n result_typ = pytypes.GenericTupleType.parameterise(\n [content_typ, pytypes.BoolType], location\n )\n return TupleExpressionBuilder(expr, result_typ)\n\n\nclass _Get(_MemberFunction):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n content_typ = self._base.pytype.content\n default_arg = expect.exactly_one_arg_of_type_else_dummy(args, content_typ, location)\n default_expr = default_arg.resolve()\n field = _build_field(self._base, self.source_location)\n expr = StateGet(field=field, default=default_expr, source_location=location)\n return builder_for_instance(content_typ, expr)\n\n\nclass _Value(ValueProxyExpressionBuilder[pytypes.PyType, AppStateExpression]):\n @typing.override\n def delete(self, location: SourceLocation) -> Statement:\n return ExpressionStatement(StateDelete(field=self.resolve(), source_location=location))\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/storage\/global_state.py","language":"Python","license":"NOASSERTION","size":8775} {"code":"import abc\nimport typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import (\n AppAccountStateExpression,\n Expression,\n ExpressionStatement,\n IntegerConstant,\n StateDelete,\n StateExists,\n StateGet,\n StateGetEx,\n Statement,\n)\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder, GenericTypeBuilder\nfrom puyapy.awst_build.eb._bytes_backed import BytesBackedInstanceExpressionBuilder\nfrom puyapy.awst_build.eb._utils import dummy_value\nfrom puyapy.awst_build.eb.bool import BoolExpressionBuilder\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import (\n InstanceBuilder,\n NodeBuilder,\n StorageProxyConstructorArgs,\n StorageProxyConstructorResult,\n TypeBuilder,\n)\nfrom puyapy.awst_build.eb.storage._storage import (\n StorageProxyDefinitionBuilder,\n parse_storage_proxy_constructor_args,\n)\nfrom puyapy.awst_build.eb.storage._value_proxy import ValueProxyExpressionBuilder\nfrom puyapy.awst_build.eb.tuple import TupleExpressionBuilder\nfrom puyapy.awst_build.utils import get_arg_mapping\n\nlogger = log.get_logger(__name__)\n\n\nclass LocalStateTypeBuilder(TypeBuilder[pytypes.StorageProxyType]):\n def __init__(self, typ: pytypes.PyType, location: SourceLocation) -> None:\n assert isinstance(typ, pytypes.StorageProxyType)\n assert typ.generic == pytypes.GenericLocalStateType\n self._typ = typ\n super().__init__(typ, location)\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n return _init(args, arg_names, location, result_type=self._typ)\n\n\nclass LocalStateGenericTypeBuilder(GenericTypeBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n return _init(args, arg_names, location, result_type=None)\n\n\ndef _init(\n args: Sequence[NodeBuilder],\n arg_names: list[str | None],\n location: SourceLocation,\n *,\n result_type: pytypes.StorageProxyType | None,\n) -> InstanceBuilder:\n type_arg_name = \"type_\"\n key_arg_name = \"key\"\n descr_arg_name = \"description\"\n arg_mapping, _ = get_arg_mapping(\n required_positional_names=[type_arg_name],\n optional_kw_only=[key_arg_name, descr_arg_name],\n args=args,\n arg_names=arg_names,\n call_location=location,\n raise_on_missing=True,\n )\n\n match arg_mapping[type_arg_name].pytype:\n case pytypes.TypeType(typ=content):\n pass\n case _:\n raise CodeError(\"first argument must be a type reference\", location)\n if result_type is None:\n result_type = pytypes.GenericLocalStateType.parameterise([content], location)\n elif result_type.content != content:\n logger.error(\n \"explicit type annotation does not match first argument\"\n \" - suggest to remove the explicit type annotation, it shouldn't be required\",\n location=location,\n )\n\n typed_args = parse_storage_proxy_constructor_args(\n arg_mapping,\n key_wtype=wtypes.state_key,\n key_arg_name=key_arg_name,\n descr_arg_name=descr_arg_name,\n location=location,\n )\n\n if typed_args.key is None:\n return StorageProxyDefinitionBuilder(typed_args, result_type, location)\n return _LocalStateExpressionBuilderFromConstructor(typed_args, result_type)\n\n\nclass LocalStateExpressionBuilder(\n BytesBackedInstanceExpressionBuilder[pytypes.StorageProxyType], bytes_member=\"key\"\n):\n def __init__(self, expr: Expression, typ: pytypes.PyType, member_name: str | None = None):\n assert isinstance(typ, pytypes.StorageProxyType)\n assert typ.generic == pytypes.GenericLocalStateType\n self.member_name: typing.Final = member_name\n super().__init__(typ, expr)\n\n @typing.override\n def index(self, index: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n expr = _build_field(self, index, location)\n return _Value(self.pytype.content, expr)\n\n @typing.override\n def contains(self, item: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n exists_expr = StateExists(\n field=_build_field(self, item, location), source_location=location\n )\n return BoolExpressionBuilder(exists_expr)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n match name:\n case \"get\":\n return _Get(self, location)\n case \"maybe\":\n return _Maybe(self, location)\n return super().member_access(name, location)\n\n @typing.override\n def iterate(self) -> typing.Never:\n raise CodeError(\"cannot iterate account states\", self.source_location)\n\n @typing.override\n def iterable_item_type(self) -> typing.Never:\n self.iterate()\n\n @typing.override\n def slice_index(\n self,\n begin_index: InstanceBuilder | None,\n end_index: InstanceBuilder | None,\n stride: InstanceBuilder | None,\n location: SourceLocation,\n ) -> InstanceBuilder:\n raise CodeError(\"cannot slice account states\", self.source_location)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n raise CodeError(\"cannot determine if a LocalState is empty or not\", location)\n\n\ndef _build_field(\n self: LocalStateExpressionBuilder,\n index: NodeBuilder,\n location: SourceLocation,\n) -> AppAccountStateExpression:\n # TODO: maybe resolve literal should allow functions, so we can validate\n # constant values inside e.g. conditional expressions, not just plain constants\n # like we check below with matching on IntegerConstant\n index_expr = expect.argument_of_type_else_dummy(\n index,\n # UInt64 comes first since we want to resolve int literals,\n # str literals for account not currently supported\n pytypes.UInt64Type,\n pytypes.AccountType,\n resolve_literal=True,\n ).resolve()\n # https:\/\/developer.algorand.org\/docs\/get-details\/dapps\/smart-contracts\/apps\/#resource-availability\n # Note that the sender address is implicitly included in the array,\n # but doesn't count towards the limit of 4, so the <= 4 below is correct\n # and intended\n if isinstance(index_expr, IntegerConstant) and not (0 <= index_expr.value <= 4):\n logger.error(\n \"account index should be between 0 and 4 inclusive\",\n location=index.source_location,\n )\n if self.member_name:\n exists_assertion_message = f\"check self.{self.member_name} exists for account\"\n else:\n exists_assertion_message = \"check LocalState exists for account\"\n return AppAccountStateExpression(\n key=self.resolve(),\n account=index_expr,\n wtype=self.pytype.content_wtype,\n exists_assertion_message=exists_assertion_message,\n source_location=location,\n )\n\n\nclass _LocalStateExpressionBuilderFromConstructor(\n LocalStateExpressionBuilder, StorageProxyConstructorResult\n):\n def __init__(self, args: StorageProxyConstructorArgs, typ: pytypes.StorageProxyType):\n assert args.key is not None\n super().__init__(args.key, typ, member_name=None)\n self._args = args\n\n @typing.override\n @property\n def args(self) -> StorageProxyConstructorArgs:\n return self._args\n\n\nclass _MemberFunction(FunctionBuilder, abc.ABC):\n def __init__(self, base: LocalStateExpressionBuilder, location: SourceLocation):\n super().__init__(location)\n self._base = base\n\n\nclass _Get(_MemberFunction):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n content_typ = self._base.pytype.content\n account_arg_name = \"account\"\n default_arg_name = \"default\"\n args_map, any_missing = get_arg_mapping(\n required_positional_names=[account_arg_name, default_arg_name],\n args=args,\n arg_names=arg_names,\n call_location=location,\n raise_on_missing=False,\n )\n if any_missing:\n return dummy_value(content_typ, location)\n item = args_map[account_arg_name]\n default_arg = expect.argument_of_type_else_dummy(args_map[default_arg_name], content_typ)\n account = _build_field(self._base, item, location)\n default = default_arg.resolve()\n expr = StateGet(field=account, default=default, source_location=location)\n return builder_for_instance(content_typ, expr)\n\n\nclass _Maybe(_MemberFunction):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n content_typ = self._base.pytype.content\n result_typ = pytypes.GenericTupleType.parameterise(\n [content_typ, pytypes.BoolType], location\n )\n arg = expect.exactly_one_arg(args, location, default=expect.default_fixed_value(None))\n if arg is None:\n return dummy_value(result_typ, location)\n\n field = _build_field(self._base, arg, location)\n app_local_get_ex = StateGetEx(field=field, source_location=location)\n return TupleExpressionBuilder(app_local_get_ex, result_typ)\n\n\nclass _Value(ValueProxyExpressionBuilder[pytypes.PyType, AppAccountStateExpression]):\n def delete(self, location: SourceLocation) -> Statement:\n return ExpressionStatement(StateDelete(field=self.resolve(), source_location=location))\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/storage\/local_state.py","language":"Python","license":"NOASSERTION","size":10275} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import algo_constants, log\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import (\n BoolConstant,\n BytesAugmentedAssignment,\n BytesBinaryOperation,\n BytesBinaryOperator,\n CallArg,\n ConditionalExpression,\n Expression,\n PuyaLibCall,\n PuyaLibFunction,\n Statement,\n StringConstant,\n UInt64Constant,\n)\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import intrinsic_factory, pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder\nfrom puyapy.awst_build.eb._bytes_backed import (\n BytesBackedInstanceExpressionBuilder,\n BytesBackedTypeBuilder,\n)\nfrom puyapy.awst_build.eb._utils import compare_bytes, dummy_statement, dummy_value\nfrom puyapy.awst_build.eb.bool import BoolExpressionBuilder\nfrom puyapy.awst_build.eb.bytes import BytesExpressionBuilder\nfrom puyapy.awst_build.eb.interface import (\n BuilderBinaryOp,\n BuilderComparisonOp,\n InstanceBuilder,\n LiteralBuilder,\n NodeBuilder,\n StaticSizedCollectionBuilder,\n)\nfrom puyapy.awst_build.eb.uint64 import UInt64ExpressionBuilder\n\nlogger = log.get_logger(__name__)\n\n\nclass StringTypeBuilder(BytesBackedTypeBuilder):\n def __init__(self, location: SourceLocation):\n super().__init__(pytypes.StringType, location)\n\n @typing.override\n def try_convert_literal(\n self, literal: LiteralBuilder, location: SourceLocation\n ) -> InstanceBuilder | None:\n match literal.value:\n case str(value):\n try:\n bytes_value = value.encode(\"utf8\")\n except UnicodeEncodeError as ex:\n logger.error( # noqa: TRY400\n f\"invalid UTF-8 string (encoding error: {ex})\",\n location=literal.source_location,\n )\n else:\n if len(bytes_value) > algo_constants.MAX_BYTES_LENGTH:\n logger.error(\n \"string constant exceeds max byte array length\",\n location=literal.source_location,\n )\n expr = StringConstant(value=value, source_location=location)\n return StringExpressionBuilder(expr)\n return None\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.at_most_one_arg(args, location)\n match arg:\n case InstanceBuilder(pytype=pytypes.StrLiteralType):\n return arg.resolve_literal(converter=StringTypeBuilder(location))\n case None:\n str_const = StringConstant(value=\"\", source_location=location)\n return StringExpressionBuilder(str_const)\n case other:\n return expect.not_this_type(\n other, default=expect.default_dummy_value(self.produces())\n )\n\n\nclass StringExpressionBuilder(BytesBackedInstanceExpressionBuilder):\n def __init__(self, expr: Expression):\n super().__init__(pytypes.StringType, expr)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n match name:\n case \"startswith\":\n return _StringStartsOrEndsWith(self, location, at_start=True)\n case \"endswith\":\n return _StringStartsOrEndsWith(self, location, at_start=False)\n case \"join\":\n return _StringJoin(self, location)\n case _:\n return super().member_access(name, location)\n\n @typing.override\n def augmented_assignment(\n self, op: BuilderBinaryOp, rhs: InstanceBuilder, location: SourceLocation\n ) -> Statement:\n if op != BuilderBinaryOp.add:\n logger.error(f\"unsupported operator for type: {op.value!r}\", location=location)\n return dummy_statement(location)\n rhs = expect.argument_of_type_else_dummy(rhs, self.pytype, resolve_literal=True)\n return BytesAugmentedAssignment(\n target=self.resolve_lvalue(),\n op=BytesBinaryOperator.add,\n value=rhs.resolve(),\n source_location=location,\n )\n\n @typing.override\n def binary_op(\n self,\n other: InstanceBuilder,\n op: BuilderBinaryOp,\n location: SourceLocation,\n *,\n reverse: bool,\n ) -> InstanceBuilder:\n if op != BuilderBinaryOp.add:\n return NotImplemented\n\n other = other.resolve_literal(converter=StringTypeBuilder(other.source_location))\n # defer to most derived if not equal\n if not (other.pytype <= pytypes.StringType):\n return NotImplemented\n\n lhs = self.resolve()\n rhs = other.resolve()\n if reverse:\n (lhs, rhs) = (rhs, lhs)\n return StringExpressionBuilder(\n BytesBinaryOperation(\n left=lhs,\n op=BytesBinaryOperator.add,\n right=rhs,\n source_location=location,\n )\n )\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n other = other.resolve_literal(converter=StringTypeBuilder(other.source_location))\n return compare_bytes(self=self, op=op, other=other, source_location=location)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n len_expr = intrinsic_factory.bytes_len(self.resolve(), location)\n len_builder = UInt64ExpressionBuilder(len_expr)\n return len_builder.bool_eval(location, negate=negate)\n\n @typing.override\n def contains(self, item: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n item = expect.argument_of_type_else_dummy(item, pytypes.StringType, resolve_literal=True)\n is_substring_expr = PuyaLibCall(\n func=PuyaLibFunction.is_substring,\n args=[\n CallArg(value=item.resolve(), name=None),\n CallArg(value=self.resolve(), name=None),\n ],\n source_location=location,\n )\n return BoolExpressionBuilder(is_substring_expr)\n\n @typing.override\n def iterate(self) -> typing.Never:\n raise CodeError(\n \"string iteration in not supported due to lack of UTF8 support in AVM\",\n self.source_location,\n )\n\n @typing.override\n def iterable_item_type(self) -> typing.Never:\n self.iterate()\n\n @typing.override\n def index(self, index: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n raise CodeError(\n \"string indexing in not supported due to lack of UTF8 support in AVM\", location\n )\n\n @typing.override\n def slice_index(\n self,\n begin_index: InstanceBuilder | None,\n end_index: InstanceBuilder | None,\n stride: InstanceBuilder | None,\n location: SourceLocation,\n ) -> InstanceBuilder:\n raise CodeError(\n \"string slicing in not supported due to lack of UTF8 support in AVM\", location\n )\n\n\nclass _StringStartsOrEndsWith(FunctionBuilder):\n def __init__(self, base: StringExpressionBuilder, location: SourceLocation, *, at_start: bool):\n super().__init__(location)\n self._base = base\n self._at_start = at_start\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.exactly_one_arg_of_type_else_dummy(\n args, pytypes.StringType, location, resolve_literal=True\n )\n arg = arg.single_eval()\n this = self._base.single_eval()\n\n this_length = BytesExpressionBuilder(this.to_bytes(location)).length(location)\n arg_length = BytesExpressionBuilder(arg.to_bytes(location)).length(location)\n\n arg_length_gt_this_length = arg_length.compare(\n this_length, op=BuilderComparisonOp.gt, location=location\n )\n\n if self._at_start:\n extracted = intrinsic_factory.extract3(\n this.resolve(),\n start=UInt64Constant(source_location=location, value=0),\n length=arg_length.resolve(),\n result_type=wtypes.string_wtype,\n )\n else:\n extracted = intrinsic_factory.extract3(\n this.resolve(),\n start=this_length.binary_op(\n arg_length, BuilderBinaryOp.sub, location, reverse=False\n ).resolve(),\n length=arg_length.resolve(),\n result_type=wtypes.string_wtype,\n )\n this_substr = StringExpressionBuilder(extracted)\n\n cond = ConditionalExpression(\n condition=arg_length_gt_this_length.resolve(),\n true_expr=BoolConstant(location, value=False),\n false_expr=this_substr.compare(arg, BuilderComparisonOp.eq, location).resolve(),\n source_location=location,\n )\n return BoolExpressionBuilder(cond)\n\n\nclass _StringJoin(FunctionBuilder):\n def __init__(self, base: StringExpressionBuilder, location: SourceLocation):\n super().__init__(location)\n self._base = base\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.exactly_one_arg(args, location, default=expect.default_none)\n if not isinstance(arg, StaticSizedCollectionBuilder):\n if arg is not None: # if None, already have an error logged\n expect.not_this_type(arg, default=expect.default_none)\n return dummy_value(pytypes.StringType, location)\n items = [\n expect.argument_of_type_else_dummy(\n ib, pytypes.StringType, resolve_literal=True\n ).resolve()\n for ib in arg.iterate_static()\n ]\n sep = self._base.single_eval().resolve()\n joined_value: Expression | None = None\n for item_expr in items:\n if joined_value is None:\n joined_value = item_expr\n else:\n joined_value = intrinsic_factory.concat(\n intrinsic_factory.concat(joined_value, sep, location),\n item_expr,\n location,\n result_type=wtypes.string_wtype,\n )\n if joined_value is None:\n joined_value = StringConstant(value=\"\", source_location=location)\n return StringExpressionBuilder(joined_value)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/string.py","language":"Python","license":"NOASSERTION","size":11081} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya.awst.nodes import Expression\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb.interface import InstanceBuilder, NodeBuilder, TypeBuilder\n\n\nclass StructSubclassExpressionBuilder(TypeBuilder[pytypes.StructType]):\n def __init__(self, typ: pytypes.PyType, location: SourceLocation):\n assert isinstance(typ, pytypes.StructType)\n assert pytypes.StructBaseType < typ\n super().__init__(typ, location)\n\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n raise NotImplementedError\n\n\ndef StructExpressionBuilder(expr: Expression, typ: pytypes.PyType) -> typing.Never: # noqa: N802\n raise NotImplementedError\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/struct.py","language":"Python","license":"NOASSERTION","size":923} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst.nodes import (\n CallArg,\n ContractMethodTarget,\n SubroutineCallExpression,\n SubroutineTarget,\n)\nfrom puya.errors import CodeError, InternalError\nfrom puya.parse import SourceLocation\nfrom puya.program_refs import ContractReference\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder\nfrom puyapy.awst_build.eb._utils import dummy_value\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import InstanceBuilder, NodeBuilder\nfrom puyapy.awst_build.utils import get_arg_mapping\nfrom puyapy.models import ContractFragmentMethod\n\nlogger = log.get_logger(__name__)\n\n\nclass SubroutineInvokerExpressionBuilder(FunctionBuilder):\n def __init__(\n self, target: SubroutineTarget, func_type: pytypes.FuncType, location: SourceLocation\n ):\n super().__init__(location)\n self.target = target\n self.func_type = func_type\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n result_pytyp = self.func_type.ret_type\n result_wtype = result_pytyp.wtype\n if isinstance(result_wtype, str):\n raise CodeError(\n f\"unsupported return type for user function: {result_pytyp}\", location=location\n )\n if any(arg_kind.is_star() for arg_kind in arg_kinds):\n logger.error(\n \"argument unpacking at call site not currently supported\", location=location\n )\n return dummy_value(result_pytyp, location)\n\n required_positional_names = list[str]()\n optional_positional_names = list[str]()\n required_kw_only = list[str]()\n optional_kw_only = list[str]()\n type_arg_map = dict[str, pytypes.FuncArg]()\n for idx, typ_arg in enumerate(self.func_type.args):\n if typ_arg.name is None and typ_arg.kind.is_named():\n raise InternalError(\"argument marked as named has no name\", location)\n arg_map_name = typ_arg.name or str(idx)\n match typ_arg.kind:\n case mypy.nodes.ARG_POS:\n required_positional_names.append(arg_map_name)\n case mypy.nodes.ARG_OPT:\n optional_positional_names.append(arg_map_name)\n case mypy.nodes.ARG_NAMED:\n required_kw_only.append(arg_map_name)\n case mypy.nodes.ARG_NAMED_OPT:\n optional_kw_only.append(arg_map_name)\n case mypy.nodes.ARG_STAR | mypy.nodes.ARG_STAR2:\n logger.error(\n \"functions with variadic arguments are not supported\", location=location\n )\n return dummy_value(result_pytyp, location)\n case _:\n typing.assert_never(typ_arg.kind)\n type_arg_map[arg_map_name] = typ_arg\n\n arg_map, any_missing = get_arg_mapping(\n required_positional_names=required_positional_names,\n optional_positional_names=optional_positional_names,\n required_kw_only=required_kw_only,\n optional_kw_only=optional_kw_only,\n args=args,\n arg_names=arg_names,\n call_location=location,\n raise_on_missing=False,\n )\n if any_missing:\n return dummy_value(result_pytyp, location)\n\n call_args = []\n # TODO: ideally, we would iterate arg_map, so the order is the same as the call site\n # need to build map from arg to FuncArg then though to extract expected type(s)\n for arg_map_name, typ_arg in type_arg_map.items():\n arg_typ = typ_arg.type\n if isinstance(arg_typ, pytypes.UnionType):\n logger.error(\"union types are not supported in user functions\", location=location)\n return dummy_value(result_pytyp, location)\n if isinstance(arg_typ, pytypes.LiteralOnlyType):\n logger.error(\n f\"unsupported type for user function argument: {arg_typ}\", location=location\n )\n return dummy_value(result_pytyp, location)\n\n arg = arg_map[arg_map_name]\n if pytypes.ContractBaseType < arg_typ:\n if not (arg_typ <= arg.pytype):\n logger.error(\"unexpected argument type\", location=arg.source_location)\n else:\n arg = expect.argument_of_type_else_dummy(arg, arg_typ)\n passed_name = arg_map_name if arg_map_name in arg_names else None\n call_args.append(CallArg(name=passed_name, value=arg.resolve()))\n\n call_expr = SubroutineCallExpression(\n target=self.target,\n args=call_args,\n wtype=result_wtype,\n source_location=location,\n )\n return builder_for_instance(result_pytyp, call_expr)\n\n\nclass BaseClassSubroutineInvokerExpressionBuilder(SubroutineInvokerExpressionBuilder):\n def __init__(\n self,\n cref: ContractReference,\n method: ContractFragmentMethod,\n func_type: pytypes.FuncType,\n location: SourceLocation,\n ):\n target = ContractMethodTarget(cref=cref, member_name=method.member_name)\n super().__init__(target, func_type, location)\n self.cref: typing.Final = cref\n self.method: typing.Final = method\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/subroutine.py","language":"Python","license":"NOASSERTION","size":5691} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst.nodes import TemplateVar\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder\nfrom puyapy.awst_build.eb._utils import dummy_value\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import InstanceBuilder, NodeBuilder\nfrom puyapy.awst_build.utils import get_arg_mapping\n\nlogger = log.get_logger(__name__)\n\n\nclass GenericTemplateVariableExpressionBuilder(FunctionBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n raise CodeError(\"TemplateVar usage requires type parameter\", location)\n\n\nclass TemplateVariableExpressionBuilder(FunctionBuilder):\n def __init__(self, typ: pytypes.PyType, location: SourceLocation):\n assert isinstance(typ, pytypes.PseudoGenericFunctionType)\n self.result_type = typ.return_type\n super().__init__(location)\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n var_name_arg_name = \"variable_name\"\n prefix_arg_name = \"prefix\"\n arg_mapping, any_missing = get_arg_mapping(\n required_positional_names=[var_name_arg_name],\n optional_kw_only=[prefix_arg_name],\n args=args,\n arg_names=arg_names,\n call_location=location,\n raise_on_missing=False,\n )\n if any_missing:\n return dummy_value(self.result_type, location)\n\n var_name = expect.simple_string_literal(\n arg_mapping[var_name_arg_name], default=expect.default_fixed_value(\"\")\n )\n\n if (prefix_arg := arg_mapping.get(prefix_arg_name)) is None:\n prefix_value = \"TMPL_\"\n else:\n prefix_value = expect.simple_string_literal(\n prefix_arg, default=expect.default_fixed_value(\"\")\n )\n\n result_expr = TemplateVar(\n name=prefix_value + var_name,\n wtype=self.result_type.checked_wtype(location),\n source_location=location,\n )\n return builder_for_instance(self.result_type, result_expr)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/template_variables.py","language":"Python","license":"NOASSERTION","size":2613} {"code":"from puyapy.awst_build.eb.transaction.group import (\n GroupTransactionExpressionBuilder,\n GroupTransactionTypeBuilder,\n)\nfrom puyapy.awst_build.eb.transaction.inner import (\n InnerTransactionExpressionBuilder,\n InnerTransactionTypeBuilder,\n SubmitInnerTransactionExpressionBuilder,\n)\nfrom puyapy.awst_build.eb.transaction.inner_params import (\n InnerTxnParamsExpressionBuilder,\n InnerTxnParamsTypeBuilder,\n)\n\n__all__ = [\n \"GroupTransactionTypeBuilder\",\n \"GroupTransactionExpressionBuilder\",\n \"InnerTransactionTypeBuilder\",\n \"InnerTransactionExpressionBuilder\",\n \"InnerTxnParamsTypeBuilder\",\n \"InnerTxnParamsExpressionBuilder\",\n \"SubmitInnerTransactionExpressionBuilder\",\n]\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/transaction\/__init__.py","language":"Python","license":"NOASSERTION","size":715} {"code":"import abc\nimport typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya.awst.nodes import Expression\nfrom puya.awst.txn_fields import TxnField\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder, NotIterableInstanceExpressionBuilder\nfrom puyapy.awst_build.eb._utils import constant_bool_and_error\nfrom puyapy.awst_build.eb.interface import InstanceBuilder, NodeBuilder\nfrom puyapy.awst_build.eb.transaction.txn_fields import PYTHON_TXN_FIELDS, PythonTxnField\n\n\nclass BaseTransactionExpressionBuilder(NotIterableInstanceExpressionBuilder, abc.ABC):\n @typing.override\n @typing.final\n def to_bytes(self, location: SourceLocation) -> Expression:\n raise CodeError(\"cannot serialize transaction type\", location)\n\n @abc.abstractmethod\n def get_field_value(\n self, field: TxnField, typ: pytypes.RuntimeType, location: SourceLocation\n ) -> InstanceBuilder: ...\n\n @abc.abstractmethod\n def get_array_field_value(\n self,\n field: TxnField,\n typ: pytypes.RuntimeType,\n index: InstanceBuilder,\n location: SourceLocation,\n ) -> InstanceBuilder: ...\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n field_data = PYTHON_TXN_FIELDS.get(name)\n if field_data is None:\n return super().member_access(name, location)\n if field_data.field.is_array:\n return _ArrayItem(base=self, field_data=field_data, location=location)\n else:\n return self.get_field_value(field_data.field, field_data.type, location)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n return constant_bool_and_error(value=True, location=location, negate=negate)\n\n\nclass _ArrayItem(FunctionBuilder):\n def __init__(\n self,\n base: BaseTransactionExpressionBuilder,\n field_data: PythonTxnField,\n location: SourceLocation,\n ):\n super().__init__(location)\n self.base = base\n self.field_data = field_data\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.exactly_one_arg_of_type_else_dummy(\n args,\n pytypes.UInt64Type,\n location,\n resolve_literal=True,\n )\n return self.base.get_array_field_value(\n self.field_data.field, self.field_data.type, arg, location\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/transaction\/base.py","language":"Python","license":"NOASSERTION","size":2777} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import algo_constants, log\nfrom puya.awst.nodes import Expression, GroupTransactionReference, IntrinsicCall, UInt64Constant\nfrom puya.awst.txn_fields import TxnField\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import (\n InstanceBuilder,\n LiteralBuilder,\n NodeBuilder,\n TypeBuilder,\n)\nfrom puyapy.awst_build.eb.transaction.base import BaseTransactionExpressionBuilder\n\nlogger = log.get_logger(__name__)\n\n\nclass GroupTransactionTypeBuilder(TypeBuilder[pytypes.GroupTransactionType]):\n @typing.override\n def try_convert_literal(\n self, literal: LiteralBuilder, location: SourceLocation\n ) -> InstanceBuilder | None:\n match literal.value:\n case int(int_value):\n if int_value < 0:\n logger.error(\n \"transaction group index should be non-negative\",\n location=literal.source_location,\n )\n elif int_value >= algo_constants.MAX_TRANSACTION_GROUP_SIZE:\n logger.error(\n \"transaction group index should be\"\n f\" less than {algo_constants.MAX_TRANSACTION_GROUP_SIZE}\",\n location=literal.source_location,\n )\n typ = self.produces()\n group_index = UInt64Constant(value=int_value, source_location=location)\n txn = GroupTransactionReference(\n index=group_index, wtype=typ.wtype, source_location=location\n )\n return GroupTransactionExpressionBuilder(txn, typ)\n return None\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.exactly_one_arg(\n args, location, default=expect.default_dummy_value(pytypes.UInt64Type)\n )\n typ = self.produces()\n if arg.pytype == pytypes.IntLiteralType: # exact type, exclude bool\n return arg.resolve_literal(GroupTransactionTypeBuilder(typ, location))\n group_index = expect.argument_of_type_else_dummy(arg, pytypes.UInt64Type).resolve()\n txn = GroupTransactionReference(\n index=group_index, wtype=typ.wtype, source_location=location\n )\n return GroupTransactionExpressionBuilder(txn, typ)\n\n\nclass GroupTransactionExpressionBuilder(BaseTransactionExpressionBuilder):\n def __init__(self, expr: Expression, typ: pytypes.PyType):\n assert isinstance(typ, pytypes.TransactionRelatedType)\n super().__init__(typ, expr)\n\n @typing.override\n def get_field_value(\n self, field: TxnField, typ: pytypes.RuntimeType, location: SourceLocation\n ) -> InstanceBuilder:\n assert not field.is_array\n assert typ.wtype.scalar_type == field.avm_type\n expr = IntrinsicCall( # TODO: use (+rename) InnerTransactionField\n op_code=\"gtxns\",\n immediates=[field.immediate],\n stack_args=[self.resolve()],\n wtype=typ.wtype,\n source_location=location,\n )\n return builder_for_instance(typ, expr)\n\n @typing.override\n def get_array_field_value(\n self,\n field: TxnField,\n typ: pytypes.RuntimeType,\n index: InstanceBuilder,\n location: SourceLocation,\n ) -> InstanceBuilder:\n assert field.is_array\n assert pytypes.UInt64Type <= index.pytype\n assert typ.wtype.scalar_type == field.avm_type\n expr = IntrinsicCall(\n op_code=\"gtxnsas\",\n immediates=[field.immediate],\n stack_args=[self.resolve(), index.resolve()],\n wtype=typ.wtype,\n source_location=location,\n )\n return builder_for_instance(typ, expr)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/transaction\/group.py","language":"Python","license":"NOASSERTION","size":4141} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya.awst.nodes import Expression, InnerTransactionField, SubmitInnerTransaction\nfrom puya.awst.txn_fields import TxnField\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import InstanceBuilder, NodeBuilder, TypeBuilder\nfrom puyapy.awst_build.eb.transaction.base import BaseTransactionExpressionBuilder\nfrom puyapy.awst_build.eb.tuple import TupleExpressionBuilder\n\n\nclass InnerTransactionTypeBuilder(TypeBuilder[pytypes.InnerTransactionResultType]):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> typing.Never:\n typ = self.produces()\n params_typ = pytypes.InnerTransactionFieldsetTypes[typ.transaction_type]\n raise CodeError(\n f\"{typ} cannot be instantiated directly, create a {params_typ} and submit instead\",\n location,\n )\n\n\nclass InnerTransactionExpressionBuilder(BaseTransactionExpressionBuilder):\n def __init__(self, expr: Expression, typ: pytypes.PyType):\n assert isinstance(typ, pytypes.InnerTransactionResultType)\n super().__init__(typ, expr)\n\n @typing.override\n def get_field_value(\n self, field: TxnField, typ: pytypes.RuntimeType, location: SourceLocation\n ) -> InstanceBuilder:\n expr = InnerTransactionField(\n itxn=self.resolve(),\n field=field,\n wtype=typ.wtype,\n source_location=location,\n )\n return builder_for_instance(typ, expr)\n\n @typing.override\n def get_array_field_value(\n self,\n field: TxnField,\n typ: pytypes.RuntimeType,\n index: InstanceBuilder,\n location: SourceLocation,\n ) -> InstanceBuilder:\n assert pytypes.UInt64Type <= index.pytype\n expr = InnerTransactionField(\n itxn=self.resolve(),\n field=field,\n array_index=index.resolve(),\n wtype=typ.wtype,\n source_location=location,\n )\n return builder_for_instance(typ, expr)\n\n\nclass SubmitInnerTransactionExpressionBuilder(FunctionBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg_exprs = []\n result_types = []\n for arg in args:\n match arg:\n case InstanceBuilder(\n pytype=pytypes.InnerTransactionFieldsetType(transaction_type=txn_type)\n ):\n arg_exprs.append(arg.resolve())\n arg_result_type = pytypes.InnerTransactionResultTypes[txn_type]\n result_types.append(arg_result_type)\n case other:\n expect.not_this_type(other, default=expect.default_raise)\n result_typ = pytypes.GenericTupleType.parameterise(result_types, location)\n return TupleExpressionBuilder(\n SubmitInnerTransaction(itxns=arg_exprs, source_location=location),\n result_typ,\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/transaction\/inner.py","language":"Python","license":"NOASSERTION","size":3504} {"code":"import abc\nimport typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst.nodes import (\n Copy,\n CreateInnerTransaction,\n Expression,\n SubmitInnerTransaction,\n UInt64Constant,\n UpdateInnerTransaction,\n)\nfrom puya.awst.txn_fields import TxnField\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import FunctionBuilder, NotIterableInstanceExpressionBuilder\nfrom puyapy.awst_build.eb._utils import constant_bool_and_error\nfrom puyapy.awst_build.eb.interface import InstanceBuilder, NodeBuilder, TypeBuilder\nfrom puyapy.awst_build.eb.none import NoneExpressionBuilder\nfrom puyapy.awst_build.eb.transaction.inner import InnerTransactionExpressionBuilder\nfrom puyapy.awst_build.eb.transaction.itxn_args import PYTHON_ITXN_ARGUMENTS\n\nlogger = log.get_logger(__name__)\n\n\nclass InnerTxnParamsTypeBuilder(TypeBuilder[pytypes.InnerTransactionFieldsetType]):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n transaction_fields = dict[TxnField, Expression]()\n transaction_fields[TxnField.Fee] = UInt64Constant(\n value=0, source_location=self.source_location\n )\n typ = self.produces()\n if typ.transaction_type is not None:\n transaction_fields[TxnField.TypeEnum] = UInt64Constant(\n value=typ.transaction_type.value,\n teal_alias=typ.transaction_type.name,\n source_location=self.source_location,\n )\n transaction_fields.update(_map_itxn_args(arg_names, args))\n\n create_expr = CreateInnerTransaction(\n fields=transaction_fields, wtype=typ.wtype, source_location=location\n )\n return InnerTxnParamsExpressionBuilder(typ, create_expr)\n\n\nclass InnerTxnParamsExpressionBuilder(\n NotIterableInstanceExpressionBuilder[pytypes.InnerTransactionFieldsetType]\n):\n @typing.override\n def to_bytes(self, location: SourceLocation) -> Expression:\n raise CodeError(\"cannot serialize inner transaction fieldset\", location)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n if name == \"submit\":\n return _Submit(self, location)\n elif name == \"set\":\n return _Set(self, location)\n elif name == \"copy\":\n return _Copy(self, location)\n return super().member_access(name, location)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n return constant_bool_and_error(value=True, location=location, negate=negate)\n\n\nclass _MemberFunction(FunctionBuilder, abc.ABC):\n def __init__(self, base: InnerTxnParamsExpressionBuilder, location: SourceLocation) -> None:\n super().__init__(location)\n self.base = base\n\n\nclass _Submit(_MemberFunction):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n expect.no_args(args, location)\n result_typ = pytypes.InnerTransactionResultTypes[self.base.pytype.transaction_type]\n submit_expr = SubmitInnerTransaction(itxns=[self.base.resolve()], source_location=location)\n return InnerTransactionExpressionBuilder(submit_expr, result_typ)\n\n\nclass _Copy(_MemberFunction):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n expect.no_args(args, location)\n copy_expr = Copy(value=self.base.resolve(), source_location=location)\n return InnerTxnParamsExpressionBuilder(self.base.pytype, copy_expr)\n\n\nclass _Set(_MemberFunction):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n transaction_fields = _map_itxn_args(arg_names, args)\n update_expr = UpdateInnerTransaction(\n itxn=self.base.resolve(), fields=transaction_fields, source_location=location\n )\n return NoneExpressionBuilder(update_expr)\n\n\ndef _map_itxn_args(\n arg_names: list[str | None], args: Sequence[NodeBuilder]\n) -> dict[TxnField, Expression]:\n transaction_fields = dict[TxnField, Expression]()\n for arg_name, arg in zip(arg_names, args, strict=True):\n if arg_name is None:\n logger.error(\"unexpected positional argument\", location=arg.source_location)\n elif (params := PYTHON_ITXN_ARGUMENTS.get(arg_name)) is None:\n logger.error(\"unrecognised keyword argument\", location=arg.source_location)\n else:\n transaction_fields[params.field] = params.validate_and_convert(arg).resolve()\n return transaction_fields\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/transaction\/inner_params.py","language":"Python","license":"NOASSERTION","size":5292} {"code":"from collections.abc import Mapping\n\nimport attrs\nfrom immutabledict import immutabledict\n\nfrom puya import log\nfrom puya.awst.txn_fields import TxnField\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb.bytes import BytesExpressionBuilder\nfrom puyapy.awst_build.eb.interface import (\n InstanceBuilder,\n NodeBuilder,\n StaticSizedCollectionBuilder,\n)\nfrom puyapy.awst_build.eb.tuple import TupleLiteralBuilder\nfrom puyapy.awst_build.utils import resolve_literal\n\nlogger = log.get_logger(__name__)\n\n\n@attrs.frozen(kw_only=True)\nclass PythonITxnArgument:\n field: TxnField\n type: pytypes.PyType\n \"\"\"the primary type of the field - will be called to convert literals,\n expect for special cases explicitly overridden in literal_overrides\n for array fields, this is the type of the items\"\"\"\n additional_types: tuple[pytypes.PyType, ...] = ()\n \"\"\"any extra types that are acceptable, will be carried through without validation\n (so don't put literals in here)\"\"\"\n literal_overrides: Mapping[pytypes.LiteralOnlyType, pytypes.PyType] = attrs.field(\n converter=immutabledict, factory=immutabledict\n )\n array_promote: bool = False\n \"\"\"if the field is an array, accept individual arguments and convert to array format\"\"\"\n auto_serialize_bytes: bool = False\n \"\"\"rely on to_bytes() - only valid if the type is pytypes.BytesType\"\"\"\n\n def __attrs_post_init__(self) -> None:\n assert self.field.is_inner_param\n assert self.type not in self.additional_types\n if self.array_promote:\n assert self.field.is_array\n if self.auto_serialize_bytes:\n assert self.type is pytypes.BytesType\n assert not self.additional_types\n assert not self.literal_overrides\n\n def validate_and_convert(self, builder: NodeBuilder) -> InstanceBuilder:\n if not self.field.is_array:\n dummy_pytype = self.type\n else:\n dummy_pytype = pytypes.GenericTupleType.parameterise(\n [self.type] * self.field.num_values, builder.source_location\n )\n\n dummy_default = expect.default_dummy_value(dummy_pytype)\n eb = expect.instance_builder(builder, default=dummy_default)\n if not self.field.is_array:\n return self._validate_and_convert_item(eb)\n elif isinstance(eb, StaticSizedCollectionBuilder):\n return TupleLiteralBuilder(\n [self._validate_and_convert_item(item) for item in eb.iterate_static()],\n eb.source_location,\n )\n elif self.array_promote:\n # TODO: split bytes literals >= 4096\n item = self._validate_and_convert_item(eb)\n return TupleLiteralBuilder([item], item.source_location)\n else:\n return expect.argument_of_type(\n eb, pytypes.VariadicTupleType(items=self.type), default=dummy_default\n )\n\n def _validate_and_convert_item(self, item: InstanceBuilder) -> InstanceBuilder:\n if self.field == TxnField.ApplicationArgs:\n if pytypes.AccountType <= item.pytype:\n logger.warning(\n f\"{item.pytype} will not be added to foreign array,\"\n f\" use .bytes to suppress this warning\",\n location=item.source_location,\n )\n elif item.pytype.is_type_or_subtype(pytypes.AssetType, pytypes.ApplicationType):\n logger.warning(\n f\"{item.pytype} will not be added to foreign array,\"\n f\" use .id to suppress this warning\",\n location=item.source_location,\n )\n\n if self.auto_serialize_bytes:\n return BytesExpressionBuilder(item.to_bytes(item.source_location))\n\n override_literal_type = self.literal_overrides.get(item.pytype) # type: ignore[call-overload]\n if override_literal_type is not None:\n item = resolve_literal(item, override_literal_type)\n return expect.argument_of_type_else_dummy(\n item, self.type, *self.additional_types, resolve_literal=True\n )\n\n\nPYTHON_ITXN_ARGUMENTS = {\n # type(:) TransactionType = ...,\n \"type\": PythonITxnArgument(\n field=TxnField.TypeEnum,\n type=pytypes.TransactionTypeType,\n ),\n # ## payment\n # receiver: Account | str = ...,\n \"receiver\": PythonITxnArgument(\n field=TxnField.Receiver,\n type=pytypes.AccountType,\n ),\n # amount: UInt64 | int = ...,\n \"amount\": PythonITxnArgument(\n field=TxnField.Amount,\n type=pytypes.UInt64Type,\n ),\n # close_remainder_to: Account | str = ...,\n \"close_remainder_to\": PythonITxnArgument(\n field=TxnField.CloseRemainderTo,\n type=pytypes.AccountType,\n ),\n # ## key registration\n # vote_key: Bytes | bytes = ...,\n \"vote_key\": PythonITxnArgument(\n field=TxnField.VotePK,\n type=pytypes.BytesType,\n ),\n # selection_key: Bytes | bytes = ...,\n \"selection_key\": PythonITxnArgument(\n field=TxnField.SelectionPK,\n type=pytypes.BytesType,\n ),\n # vote_first: UInt64 | int = ...,\n \"vote_first\": PythonITxnArgument(\n field=TxnField.VoteFirst,\n type=pytypes.UInt64Type,\n ),\n # vote_last: UInt64 | int = ...,\n \"vote_last\": PythonITxnArgument(\n field=TxnField.VoteLast,\n type=pytypes.UInt64Type,\n ),\n # vote_key_dilution: UInt64 | int = ...,\n \"vote_key_dilution\": PythonITxnArgument(\n field=TxnField.VoteKeyDilution,\n type=pytypes.UInt64Type,\n ),\n # non_participation: UInt64 | int | bool = ...,\n \"non_participation\": PythonITxnArgument(\n field=TxnField.Nonparticipation,\n type=pytypes.UInt64Type,\n additional_types=(pytypes.BoolType,),\n ),\n # state_proof_key: Bytes | bytes = ...,\n \"state_proof_key\": PythonITxnArgument(\n field=TxnField.StateProofPK,\n type=pytypes.BytesType,\n ),\n # ## asset config\n # config_asset: Asset | UInt64 | int = ...,\n \"config_asset\": PythonITxnArgument(\n field=TxnField.ConfigAsset,\n type=pytypes.AssetType,\n additional_types=(pytypes.UInt64Type,),\n ),\n # total: UInt64 | int = ...,\n \"total\": PythonITxnArgument(\n field=TxnField.ConfigAssetTotal,\n type=pytypes.UInt64Type,\n ),\n # unit_name: String | Bytes | str | bytes = ...,\n \"unit_name\": PythonITxnArgument(\n field=TxnField.ConfigAssetUnitName,\n type=pytypes.BytesType,\n additional_types=(pytypes.StringType,),\n literal_overrides={pytypes.StrLiteralType: pytypes.StringType},\n ),\n # asset_name: String | Bytes | str | bytes = ...,\n \"asset_name\": PythonITxnArgument(\n field=TxnField.ConfigAssetName,\n type=pytypes.BytesType,\n additional_types=(pytypes.StringType,),\n literal_overrides={pytypes.StrLiteralType: pytypes.StringType},\n ),\n # decimals: UInt64 | int = ...,\n \"decimals\": PythonITxnArgument(\n field=TxnField.ConfigAssetDecimals,\n type=pytypes.UInt64Type,\n ),\n # default_frozen: bool = ...,\n \"default_frozen\": PythonITxnArgument(\n field=TxnField.ConfigAssetDefaultFrozen,\n type=pytypes.BoolType,\n ),\n # url: String | Bytes | bytes | str = ...,\n \"url\": PythonITxnArgument(\n field=TxnField.ConfigAssetURL,\n type=pytypes.BytesType,\n additional_types=(pytypes.StringType,),\n literal_overrides={pytypes.StrLiteralType: pytypes.StringType},\n ),\n # metadata_hash: Bytes | bytes = ...,\n \"metadata_hash\": PythonITxnArgument(\n field=TxnField.ConfigAssetMetadataHash,\n type=pytypes.BytesType,\n ),\n # manager: Account | str = ...,\n \"manager\": PythonITxnArgument(\n field=TxnField.ConfigAssetManager,\n type=pytypes.AccountType,\n ),\n # reserve: Account | str = ...,\n \"reserve\": PythonITxnArgument(\n field=TxnField.ConfigAssetReserve,\n type=pytypes.AccountType,\n ),\n # freeze: Account | str = ...,\n \"freeze\": PythonITxnArgument(\n field=TxnField.ConfigAssetFreeze,\n type=pytypes.AccountType,\n ),\n # clawback: Account | str = ...,\n \"clawback\": PythonITxnArgument(\n field=TxnField.ConfigAssetClawback,\n type=pytypes.AccountType,\n ),\n # ## asset transfer\n # xfer_asset: Asset | UInt64 | int = ...,\n \"xfer_asset\": PythonITxnArgument(\n field=TxnField.XferAsset,\n type=pytypes.AssetType,\n additional_types=(pytypes.UInt64Type,),\n ),\n # asset_amount: UInt64 | int = ...,\n \"asset_amount\": PythonITxnArgument(\n field=TxnField.AssetAmount,\n type=pytypes.UInt64Type,\n ),\n # asset_sender: Account | str = ...,\n \"asset_sender\": PythonITxnArgument(\n field=TxnField.AssetSender,\n type=pytypes.AccountType,\n ),\n # asset_receiver: Account | str = ...,\n \"asset_receiver\": PythonITxnArgument(\n field=TxnField.AssetReceiver,\n type=pytypes.AccountType,\n ),\n # asset_close_to: Account | str = ...,\n \"asset_close_to\": PythonITxnArgument(\n field=TxnField.AssetCloseTo,\n type=pytypes.AccountType,\n ),\n # ## asset freeze\n # freeze_asset: Asset | UInt64 | int = ...,\n \"freeze_asset\": PythonITxnArgument(\n field=TxnField.FreezeAsset,\n type=pytypes.AssetType,\n additional_types=(pytypes.UInt64Type,),\n ),\n # freeze_account: Account | str = ...,\n \"freeze_account\": PythonITxnArgument(\n field=TxnField.FreezeAssetAccount,\n type=pytypes.AccountType,\n ),\n # frozen: bool = ...,\n \"frozen\": PythonITxnArgument(\n field=TxnField.FreezeAssetFrozen,\n type=pytypes.BoolType,\n ),\n # ## application call\n # app_id: Application | UInt64 | int = ...,\n \"app_id\": PythonITxnArgument(\n field=TxnField.ApplicationID,\n type=pytypes.ApplicationType,\n additional_types=(pytypes.UInt64Type,),\n ),\n # approval_program: Bytes | bytes | tuple[Bytes, ...] = ...,\n \"approval_program\": PythonITxnArgument(\n field=TxnField.ApprovalProgramPages,\n type=pytypes.BytesType,\n array_promote=True,\n ),\n # clear_state_program: Bytes | bytes | tuple[Bytes, ...] = ...,\n \"clear_state_program\": PythonITxnArgument(\n field=TxnField.ClearStateProgramPages,\n type=pytypes.BytesType,\n array_promote=True,\n ),\n # on_completion: OnCompleteAction | UInt64 | int = ...,\n \"on_completion\": PythonITxnArgument(\n field=TxnField.OnCompletion,\n type=pytypes.OnCompleteActionType,\n additional_types=(pytypes.UInt64Type,),\n ),\n # global_num_uint: UInt64 | int = ...,\n \"global_num_uint\": PythonITxnArgument(\n field=TxnField.GlobalNumUint,\n type=pytypes.UInt64Type,\n ),\n # global_num_bytes: UInt64 | int = ...,\n \"global_num_bytes\": PythonITxnArgument(\n field=TxnField.GlobalNumByteSlice,\n type=pytypes.UInt64Type,\n ),\n # local_num_uint: UInt64 | int = ...,\n \"local_num_uint\": PythonITxnArgument(\n field=TxnField.LocalNumUint,\n type=pytypes.UInt64Type,\n ),\n # local_num_bytes: UInt64 | int = ...,\n \"local_num_bytes\": PythonITxnArgument(\n field=TxnField.LocalNumByteSlice,\n type=pytypes.UInt64Type,\n ),\n # extra_program_pages: UInt64 | int = ...,\n \"extra_program_pages\": PythonITxnArgument(\n field=TxnField.ExtraProgramPages,\n type=pytypes.UInt64Type,\n ),\n # app_args: tuple[object, ...] = ...,\n \"app_args\": PythonITxnArgument(\n field=TxnField.ApplicationArgs,\n type=pytypes.BytesType,\n auto_serialize_bytes=True,\n ),\n # accounts: tuple[Account, ...] = ...,\n \"accounts\": PythonITxnArgument(\n field=TxnField.Accounts,\n type=pytypes.AccountType,\n ),\n # assets: tuple[Asset, ...] = ...,\n \"assets\": PythonITxnArgument(\n field=TxnField.Assets,\n type=pytypes.AssetType,\n ),\n # apps: tuple[Application, ...] = ...,\n \"apps\": PythonITxnArgument(\n field=TxnField.Applications,\n type=pytypes.ApplicationType,\n ),\n # ## shared\n # sender: Account | str = ...,\n \"sender\": PythonITxnArgument(\n field=TxnField.Sender,\n type=pytypes.AccountType,\n ),\n # fee: UInt64 | int = 0,\n \"fee\": PythonITxnArgument(\n field=TxnField.Fee,\n type=pytypes.UInt64Type,\n ),\n # note: String | Bytes | str | bytes = ...,\n \"note\": PythonITxnArgument(\n field=TxnField.Note,\n type=pytypes.BytesType,\n additional_types=(pytypes.StringType,),\n literal_overrides={pytypes.StrLiteralType: pytypes.StringType},\n ),\n # rekey_to: Account | str = ...,\n \"rekey_to\": PythonITxnArgument(\n field=TxnField.RekeyTo,\n type=pytypes.AccountType,\n ),\n}\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/transaction\/itxn_args.py","language":"Python","license":"NOASSERTION","size":12901} {"code":"import attrs\n\nfrom puya import log\nfrom puya.awst.txn_fields import TxnField\nfrom puyapy.awst_build import pytypes\n\nlogger = log.get_logger(__name__)\n\n\n@attrs.frozen\nclass PythonTxnField:\n field: TxnField\n type: pytypes.RuntimeType\n\n\nPYTHON_TXN_FIELDS = {\n \"sender\": PythonTxnField(TxnField.Sender, pytypes.AccountType),\n \"fee\": PythonTxnField(TxnField.Fee, pytypes.UInt64Type),\n \"first_valid\": PythonTxnField(TxnField.FirstValid, pytypes.UInt64Type),\n \"first_valid_time\": PythonTxnField(TxnField.FirstValidTime, pytypes.UInt64Type),\n \"last_valid\": PythonTxnField(TxnField.LastValid, pytypes.UInt64Type),\n \"note\": PythonTxnField(TxnField.Note, pytypes.BytesType),\n \"lease\": PythonTxnField(TxnField.Lease, pytypes.BytesType),\n \"receiver\": PythonTxnField(TxnField.Receiver, pytypes.AccountType),\n \"amount\": PythonTxnField(TxnField.Amount, pytypes.UInt64Type),\n \"close_remainder_to\": PythonTxnField(TxnField.CloseRemainderTo, pytypes.AccountType),\n \"vote_key\": PythonTxnField(TxnField.VotePK, pytypes.BytesType),\n \"selection_key\": PythonTxnField(TxnField.SelectionPK, pytypes.BytesType),\n \"vote_first\": PythonTxnField(TxnField.VoteFirst, pytypes.UInt64Type),\n \"vote_last\": PythonTxnField(TxnField.VoteLast, pytypes.UInt64Type),\n \"vote_key_dilution\": PythonTxnField(TxnField.VoteKeyDilution, pytypes.UInt64Type),\n \"type_bytes\": PythonTxnField(TxnField.Type, pytypes.BytesType),\n \"type\": PythonTxnField(TxnField.TypeEnum, pytypes.TransactionTypeType),\n \"xfer_asset\": PythonTxnField(TxnField.XferAsset, pytypes.AssetType),\n \"asset_amount\": PythonTxnField(TxnField.AssetAmount, pytypes.UInt64Type),\n \"asset_sender\": PythonTxnField(TxnField.AssetSender, pytypes.AccountType),\n \"asset_receiver\": PythonTxnField(TxnField.AssetReceiver, pytypes.AccountType),\n \"asset_close_to\": PythonTxnField(TxnField.AssetCloseTo, pytypes.AccountType),\n \"group_index\": PythonTxnField(TxnField.GroupIndex, pytypes.UInt64Type),\n \"txn_id\": PythonTxnField(TxnField.TxID, pytypes.BytesType),\n \"app_id\": PythonTxnField(TxnField.ApplicationID, pytypes.ApplicationType),\n \"on_completion\": PythonTxnField(TxnField.OnCompletion, pytypes.OnCompleteActionType),\n \"num_app_args\": PythonTxnField(TxnField.NumAppArgs, pytypes.UInt64Type),\n \"num_accounts\": PythonTxnField(TxnField.NumAccounts, pytypes.UInt64Type),\n \"approval_program\": PythonTxnField(TxnField.ApprovalProgram, pytypes.BytesType),\n \"clear_state_program\": PythonTxnField(TxnField.ClearStateProgram, pytypes.BytesType),\n \"rekey_to\": PythonTxnField(TxnField.RekeyTo, pytypes.AccountType),\n \"config_asset\": PythonTxnField(TxnField.ConfigAsset, pytypes.AssetType),\n \"total\": PythonTxnField(TxnField.ConfigAssetTotal, pytypes.UInt64Type),\n \"decimals\": PythonTxnField(TxnField.ConfigAssetDecimals, pytypes.UInt64Type),\n \"default_frozen\": PythonTxnField(TxnField.ConfigAssetDefaultFrozen, pytypes.BoolType),\n \"unit_name\": PythonTxnField(TxnField.ConfigAssetUnitName, pytypes.BytesType),\n \"asset_name\": PythonTxnField(TxnField.ConfigAssetName, pytypes.BytesType),\n \"url\": PythonTxnField(TxnField.ConfigAssetURL, pytypes.BytesType),\n \"metadata_hash\": PythonTxnField(TxnField.ConfigAssetMetadataHash, pytypes.BytesType),\n \"manager\": PythonTxnField(TxnField.ConfigAssetManager, pytypes.AccountType),\n \"reserve\": PythonTxnField(TxnField.ConfigAssetReserve, pytypes.AccountType),\n \"freeze\": PythonTxnField(TxnField.ConfigAssetFreeze, pytypes.AccountType),\n \"clawback\": PythonTxnField(TxnField.ConfigAssetClawback, pytypes.AccountType),\n \"freeze_asset\": PythonTxnField(TxnField.FreezeAsset, pytypes.AssetType),\n \"freeze_account\": PythonTxnField(TxnField.FreezeAssetAccount, pytypes.AccountType),\n \"frozen\": PythonTxnField(TxnField.FreezeAssetFrozen, pytypes.BoolType),\n \"num_assets\": PythonTxnField(TxnField.NumAssets, pytypes.UInt64Type),\n \"num_apps\": PythonTxnField(TxnField.NumApplications, pytypes.UInt64Type),\n \"global_num_uint\": PythonTxnField(TxnField.GlobalNumUint, pytypes.UInt64Type),\n \"global_num_bytes\": PythonTxnField(TxnField.GlobalNumByteSlice, pytypes.UInt64Type),\n \"local_num_uint\": PythonTxnField(TxnField.LocalNumUint, pytypes.UInt64Type),\n \"local_num_bytes\": PythonTxnField(TxnField.LocalNumByteSlice, pytypes.UInt64Type),\n \"extra_program_pages\": PythonTxnField(TxnField.ExtraProgramPages, pytypes.UInt64Type),\n \"non_participation\": PythonTxnField(TxnField.Nonparticipation, pytypes.BoolType),\n \"num_logs\": PythonTxnField(TxnField.NumLogs, pytypes.UInt64Type),\n \"created_asset\": PythonTxnField(TxnField.CreatedAssetID, pytypes.AssetType),\n \"created_app\": PythonTxnField(TxnField.CreatedApplicationID, pytypes.ApplicationType),\n \"last_log\": PythonTxnField(TxnField.LastLog, pytypes.BytesType),\n \"state_proof_key\": PythonTxnField(TxnField.StateProofPK, pytypes.BytesType),\n \"num_approval_program_pages\": PythonTxnField(\n TxnField.NumApprovalProgramPages, pytypes.UInt64Type\n ),\n \"num_clear_state_program_pages\": PythonTxnField(\n TxnField.NumClearStateProgramPages,\n pytypes.UInt64Type,\n ),\n \"app_args\": PythonTxnField(TxnField.ApplicationArgs, pytypes.BytesType),\n \"accounts\": PythonTxnField(TxnField.Accounts, pytypes.AccountType),\n \"assets\": PythonTxnField(TxnField.Assets, pytypes.AssetType),\n \"apps\": PythonTxnField(TxnField.Applications, pytypes.ApplicationType),\n \"logs\": PythonTxnField(TxnField.Logs, pytypes.BytesType),\n \"approval_program_pages\": PythonTxnField(TxnField.ApprovalProgramPages, pytypes.BytesType),\n \"clear_state_program_pages\": PythonTxnField(\n TxnField.ClearStateProgramPages, pytypes.BytesType\n ),\n}\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/transaction\/txn_fields.py","language":"Python","license":"NOASSERTION","size":5699} {"code":"import itertools\nimport typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import (\n BinaryBooleanOperator,\n BooleanBinaryOperation,\n Expression,\n FieldExpression,\n IntegerConstant,\n IntrinsicCall,\n Lvalue,\n SliceExpression,\n Statement,\n TupleExpression,\n TupleItemExpression,\n UInt64Constant,\n)\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puya.utils import clamp, positive_index\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import (\n FunctionBuilder,\n GenericTypeBuilder,\n InstanceExpressionBuilder,\n)\nfrom puyapy.awst_build.eb._literals import LiteralBuilderImpl\nfrom puyapy.awst_build.eb._utils import constant_bool_and_error, dummy_value\nfrom puyapy.awst_build.eb.bool import BoolExpressionBuilder\nfrom puyapy.awst_build.eb.factories import builder_for_instance\nfrom puyapy.awst_build.eb.interface import (\n BuilderBinaryOp,\n BuilderComparisonOp,\n BuilderUnaryOp,\n InstanceBuilder,\n LiteralBuilder,\n NodeBuilder,\n StaticSizedCollectionBuilder,\n TypeBuilder,\n)\nfrom puyapy.awst_build.utils import determine_base_type, get_arg_mapping\n\nlogger = log.get_logger(__name__)\n\n\n_TUPLE_MEMBERS: typing.Final = frozenset((\"count\", \"index\"))\n_NAMED_TUPLE_MEMBERS: typing.Final = frozenset((\"_asdict\", \"_replace\"))\n_NAMED_TUPLE_CLASS_MEMBERS: typing.Final = frozenset((\"_make\", \"_fields\", \"_field_defaults\"))\n\n\nclass GenericTupleTypeBuilder(GenericTypeBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n return _init(args, location)\n\n\nclass TupleTypeBuilder(TypeBuilder[pytypes.TupleType]):\n def __init__(self, typ: pytypes.PyType, location: SourceLocation):\n assert isinstance(typ, pytypes.TupleType)\n assert typ.generic == pytypes.GenericTupleType\n super().__init__(typ, location)\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n result = _init(args, location)\n # equality comparison okay because type constrained to TupleType\n if result.pytype != self.produces():\n raise CodeError(\"type mismatch between tuple parameters and argument types\", location)\n return result\n\n\ndef _init(args: Sequence[NodeBuilder], location: SourceLocation) -> InstanceBuilder:\n arg = expect.at_most_one_arg(args, location)\n if arg is None:\n return TupleLiteralBuilder(items=[], location=location)\n\n match arg:\n case StaticSizedCollectionBuilder() as static_builder:\n return TupleLiteralBuilder(items=static_builder.iterate_static(), location=location)\n # TODO: maybe LiteralBuilderImpl should be split for str and bytes, so it can\n # implement StaticSizedCollectionBuilder?\n case LiteralBuilder(value=bytes() | str() as bytes_or_str):\n return TupleLiteralBuilder(\n items=[\n LiteralBuilderImpl(value=item, source_location=arg.source_location)\n for item in bytes_or_str\n ],\n location=location,\n )\n case _:\n raise CodeError(\"unhandled argument type\", arg.source_location)\n\n\nclass NamedTupleTypeBuilder(TypeBuilder[pytypes.NamedTupleType]):\n def __init__(self, typ: pytypes.PyType, location: SourceLocation):\n assert isinstance(typ, pytypes.NamedTupleType)\n super().__init__(typ, location)\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n pytype = self.produces()\n field_mapping, any_missing = get_arg_mapping(\n required_positional_names=list(pytype.fields),\n args=args,\n arg_names=arg_names,\n call_location=location,\n raise_on_missing=False,\n )\n if any_missing:\n return dummy_value(pytype, location)\n\n values = [\n expect.argument_of_type_else_dummy(field_mapping[field_name], field_type).resolve()\n for field_name, field_type in pytype.fields.items()\n ]\n expr = TupleExpression(\n items=values,\n wtype=pytype.wtype,\n source_location=location,\n )\n return TupleExpressionBuilder(expr, pytype)\n\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n if name in _NAMED_TUPLE_CLASS_MEMBERS:\n raise CodeError(\"unsupported member access\", location)\n return super().member_access(name, location)\n\n\nclass TupleLiteralBuilder(InstanceBuilder[pytypes.TupleType], StaticSizedCollectionBuilder):\n def __init__(self, items: Sequence[InstanceBuilder], location: SourceLocation):\n super().__init__(location)\n self._items = tuple(items)\n self._pytype = pytypes.GenericTupleType.parameterise([i.pytype for i in items], location)\n\n @typing.override\n @property\n def pytype(self) -> pytypes.TupleType:\n return self._pytype\n\n @typing.override\n def iterate_static(self) -> Sequence[InstanceBuilder]:\n return self._items\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> typing.Never:\n if name in _TUPLE_MEMBERS:\n raise CodeError(\"unsupported member access\", location)\n raise CodeError(\"unrecognised member access\", location)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n op = BuilderComparisonOp.eq if negate else BuilderComparisonOp.ne\n return _compare(\n self,\n TupleLiteralBuilder([], location),\n op,\n location,\n )\n\n @typing.override\n def to_bytes(self, location: SourceLocation) -> Expression:\n raise CodeError(f\"cannot serialize {self.pytype}\", location)\n\n @typing.override\n def resolve(self) -> TupleExpression:\n item_exprs = [i.resolve() for i in self.iterate_static()]\n return TupleExpression.from_items(item_exprs, self.source_location)\n\n @typing.override\n def resolve_lvalue(self) -> Lvalue:\n return self.resolve()\n\n @typing.override\n def resolve_literal(self, converter: TypeBuilder) -> InstanceBuilder:\n return self.try_resolve_literal(converter)\n\n @typing.override\n def try_resolve_literal(self, converter: TypeBuilder) -> InstanceBuilder:\n # even though this may contain literals, it's not homogenous, so we can't really\n # resolve with a single converter currently...?\n return self\n\n @typing.override\n def delete(self, location: SourceLocation) -> Statement:\n raise CodeError(\"cannot delete tuple literal\", location)\n\n @typing.override\n def unary_op(self, op: BuilderUnaryOp, location: SourceLocation) -> InstanceBuilder:\n raise CodeError(f\"bad operand type for unary {op.value}: 'tuple'\", location)\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n return _compare(self, other, op, location)\n\n @typing.override\n def binary_op(\n self,\n other: InstanceBuilder,\n op: BuilderBinaryOp,\n location: SourceLocation,\n *,\n reverse: bool,\n ) -> InstanceBuilder:\n match op:\n case BuilderBinaryOp.add:\n return _concat(self, other, location, reverse=reverse)\n case BuilderBinaryOp.mult:\n match other:\n # can't handle non-simple literals here\n case LiteralBuilder(value=int(mult_literal)):\n return TupleLiteralBuilder(self._items * mult_literal, location)\n case _:\n raise CodeError(\"can't multiply sequence by non-int-literal\", location)\n case _:\n return NotImplemented\n\n @typing.override\n def bool_binary_op(\n self, other: InstanceBuilder, op: BinaryBooleanOperator, location: SourceLocation\n ) -> InstanceBuilder:\n return super().bool_binary_op(other, op, location)\n\n @typing.override\n def augmented_assignment(\n self, op: BuilderBinaryOp, rhs: InstanceBuilder, location: SourceLocation\n ) -> Statement:\n raise CodeError(\"'tuple' is an illegal expression for augmented assignment\", location)\n\n @typing.override\n def iterate(self) -> Expression:\n return self.resolve()\n\n @typing.override\n def iterable_item_type(self) -> pytypes.PyType:\n return _iterable_item_type(self.pytype, self.source_location)\n\n def _expr_builder(self) -> InstanceBuilder:\n # used to maintain semantic compatibility, we must resolve this so all elements\n # get evaluated, we can't handle literal indexing or literal containment specially\n return TupleExpressionBuilder(self.resolve(), self.pytype)\n\n @typing.override\n def contains(self, item: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n return self._expr_builder().contains(item, location)\n\n @typing.override\n def index(self, index: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n return self._expr_builder().index(index, location)\n\n @typing.override\n def slice_index(\n self,\n begin_index: InstanceBuilder | None,\n end_index: InstanceBuilder | None,\n stride: InstanceBuilder | None,\n location: SourceLocation,\n ) -> InstanceBuilder:\n return self._expr_builder().slice_index(begin_index, end_index, stride, location)\n\n @typing.override\n def single_eval(self) -> InstanceBuilder:\n return TupleLiteralBuilder(\n items=[item.single_eval() for item in self._items], location=self.source_location\n )\n\n\nclass TupleExpressionBuilder(\n InstanceExpressionBuilder[pytypes.TupleType], StaticSizedCollectionBuilder\n):\n def __init__(self, expr: Expression, typ: pytypes.PyType):\n assert isinstance(typ, pytypes.TupleType)\n super().__init__(typ, expr)\n\n @typing.override\n def to_bytes(self, location: SourceLocation) -> Expression:\n raise CodeError(f\"cannot serialize {self.pytype}\", location)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n if isinstance(self.pytype, pytypes.NamedTupleType):\n item_typ = self.pytype.fields.get(name)\n if item_typ is not None:\n item_expr = FieldExpression(\n base=self.resolve(),\n name=name,\n source_location=location,\n )\n return builder_for_instance(item_typ, item_expr)\n elif name == \"_replace\":\n return _Replace(self, self.pytype, location)\n elif name in _NAMED_TUPLE_MEMBERS:\n raise CodeError(\"unsupported member access\", location)\n elif name in _NAMED_TUPLE_CLASS_MEMBERS:\n type_builder = NamedTupleTypeBuilder(self.pytype, self.source_location)\n return type_builder.member_access(name, location)\n if name in _TUPLE_MEMBERS:\n raise CodeError(\"unsupported member access\", location)\n raise CodeError(\"unrecognised member access\", location)\n\n @typing.override\n def binary_op(\n self,\n other: InstanceBuilder,\n op: BuilderBinaryOp,\n location: SourceLocation,\n *,\n reverse: bool,\n ) -> InstanceBuilder:\n match op:\n case BuilderBinaryOp.add:\n return _concat(self, other, location, reverse=reverse)\n case BuilderBinaryOp.mult:\n match other:\n # can't handle non-simple literals here\n case LiteralBuilder(value=int(mult_literal)):\n items = tuple(self.iterate_static())\n return TupleLiteralBuilder(items * mult_literal, location)\n case _:\n raise CodeError(\"can't multiply sequence by non-int-literal\", location)\n case _:\n return NotImplemented\n\n @typing.override\n def index(self, index: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n # special handling of tuples, they can be indexed by int literal only,\n # mostly because they can be non-homogenous so we need to be able to resolve the\n # result type, but also we can statically validate that value\n match index:\n case LiteralBuilder(value=int(index_value)):\n pass\n case _:\n raise CodeError(\n \"tuples can only be indexed by int constants\",\n index.source_location,\n )\n try:\n item_typ = self.pytype.items[index_value]\n except IndexError as ex:\n raise CodeError(\"tuple index out of range\", location) from ex\n item_expr = TupleItemExpression(\n base=self.resolve(),\n index=index_value,\n source_location=location,\n )\n return builder_for_instance(item_typ, item_expr)\n\n @typing.override\n def slice_index(\n self,\n begin_index: InstanceBuilder | None,\n end_index: InstanceBuilder | None,\n stride: InstanceBuilder | None,\n location: SourceLocation,\n ) -> InstanceBuilder:\n if stride is not None:\n raise CodeError(\"stride is not supported\", location=stride.source_location)\n\n start_expr, start_idx = self._clamp_slice_index(begin_index)\n end_expr, end_idx = self._clamp_slice_index(end_index)\n slice_types = self.pytype.items[start_idx:end_idx]\n if not slice_types:\n raise CodeError(\"empty slices are not supported\", location)\n\n updated_type = pytypes.GenericTupleType.parameterise(slice_types, location)\n updated_wtype = updated_type.checked_wtype(location)\n return TupleExpressionBuilder(\n SliceExpression(\n source_location=location,\n base=self.resolve(),\n begin_index=start_expr,\n end_index=end_expr,\n wtype=updated_wtype,\n ),\n updated_type,\n )\n\n def _clamp_slice_index(\n self, index: NodeBuilder | None\n ) -> tuple[IntegerConstant | None, int | None]:\n match index:\n case None:\n expr = None\n idx = None\n case LiteralBuilder(value=int(idx), source_location=start_loc):\n positive_idx = positive_index(idx, self.pytype.items)\n positive_idx_clamped = clamp(positive_idx, low=0, high=len(self.pytype.items) - 1)\n expr = UInt64Constant(value=positive_idx_clamped, source_location=start_loc)\n case _:\n raise CodeError(\n \"tuples can only be indexed with literal values\", index.source_location\n )\n return expr, idx\n\n @typing.override\n def iterate(self) -> Expression:\n return self.resolve()\n\n @typing.override\n def iterate_static(self) -> Sequence[InstanceBuilder]:\n base = self.single_eval().resolve()\n return [\n builder_for_instance(\n item_type,\n TupleItemExpression(base=base, index=idx, source_location=self.source_location),\n )\n for idx, item_type in enumerate(self.pytype.items)\n ]\n\n @typing.override\n def iterable_item_type(self) -> pytypes.PyType:\n return _iterable_item_type(self.pytype, self.source_location)\n\n @typing.override\n def contains(self, item: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n contains_expr = None\n if isinstance(item.pytype, pytypes.LiteralOnlyType):\n logger.error(\n \"a Python literal is not valid at this location\", location=self.source_location\n )\n return dummy_value(pytypes.BoolType, location)\n item = item.single_eval()\n # note: iterate_static single_evals the sequence and is the only usage of self\n for compare_to in self.iterate_static():\n eq_compare = item.compare(compare_to, BuilderComparisonOp.eq, location)\n if eq_compare is NotImplemented:\n eq_compare = compare_to.compare(item, BuilderComparisonOp.eq, location)\n if eq_compare is NotImplemented:\n # if types don't support comparison, then skip\n continue\n if contains_expr is None:\n contains_expr = eq_compare.resolve()\n else:\n contains_expr = BooleanBinaryOperation(\n left=contains_expr,\n op=BinaryBooleanOperator.or_,\n right=eq_compare.resolve(),\n source_location=location,\n )\n if contains_expr is None:\n return constant_bool_and_error(value=False, location=location)\n else:\n return BoolExpressionBuilder(contains_expr)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n op = BuilderComparisonOp.eq if negate else BuilderComparisonOp.ne\n return _compare(\n self,\n TupleLiteralBuilder([], location),\n op,\n location,\n )\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n return _compare(self, other, op, location)\n\n\nclass _Replace(FunctionBuilder):\n def __init__(\n self,\n instance: TupleExpressionBuilder,\n named_tuple_type: pytypes.NamedTupleType,\n location: SourceLocation,\n ):\n super().__init__(location)\n self.instance = instance\n self.named_tuple_type = named_tuple_type\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n pytype = self.named_tuple_type\n field_mapping, _ = get_arg_mapping(\n optional_kw_only=list(pytype.fields),\n args=args,\n arg_names=arg_names,\n call_location=location,\n raise_on_missing=False,\n )\n base_expr = self.instance.single_eval().resolve()\n items = list[Expression]()\n for idx, (field_name, field_pytype) in enumerate(pytype.fields.items()):\n new_value = field_mapping.get(field_name)\n if new_value is not None:\n item_builder = expect.argument_of_type_else_dummy(new_value, field_pytype)\n item = item_builder.resolve()\n else:\n item = TupleItemExpression(base=base_expr, index=idx, source_location=location)\n items.append(item)\n new_tuple = TupleExpression(items=items, wtype=pytype.wtype, source_location=location)\n return TupleExpressionBuilder(new_tuple, pytype)\n\n\ndef _compare(\n lhs: InstanceBuilder[pytypes.TupleType],\n rhs: InstanceBuilder,\n op: BuilderComparisonOp,\n location: SourceLocation,\n) -> InstanceBuilder:\n if not isinstance(rhs.pytype, pytypes.TupleType):\n return NotImplemented\n\n match op:\n case BuilderComparisonOp.eq:\n chain_op = \"&&\"\n inverse = BuilderComparisonOp.ne\n result_if_both_empty = True\n case BuilderComparisonOp.ne:\n chain_op = \"||\"\n inverse = BuilderComparisonOp.eq\n result_if_both_empty = False\n case _:\n raise CodeError(\n f\"the {op.value!r} operator is not currently supported with tuples\", location\n )\n\n assert isinstance(lhs, StaticSizedCollectionBuilder)\n lhs_items = lhs.iterate_static()\n assert isinstance(rhs, StaticSizedCollectionBuilder)\n rhs_items = rhs.iterate_static()\n\n result_exprs = []\n for idx, (lhs_item, rhs_item) in enumerate(itertools.zip_longest(lhs_items, rhs_items)):\n if lhs_item is None:\n # if lhs is shorter than rhs, use the rhs item to compare against itself,\n # so that rhs is still fully evaluated to maintain semantic compatibility,\n # and we don't create typing errors trying to invent a different eval.\n # make sure it's evaluated once though, because it only appears on one side.\n # also, to make the comparison correct, we need to invert the overall op,\n # if we're doing tup1 == tup2, then things get &&'d together, and we need to use !=\n # if we're doing tup1 != tup2, then things get ||'d together, and we need to use ==\n lhs_item = rhs_item = rhs_item.single_eval()\n op_at = inverse\n elif rhs_item is None:\n rhs_item = lhs_item = lhs_item.single_eval()\n op_at = inverse\n else:\n op_at = op\n cmp_builder = lhs_item.compare(rhs_item, op=op_at, location=location)\n if cmp_builder is NotImplemented:\n cmp_builder = rhs_item.compare(lhs_item, op=op_at.reversed(), location=location)\n if cmp_builder is NotImplemented:\n raise CodeError(\n f\"items at index {idx} do not support comparison with operator {op_at.value!r}\",\n location,\n )\n result_exprs.append(cmp_builder.resolve())\n\n if not result_exprs:\n return LiteralBuilderImpl(value=result_if_both_empty, source_location=location)\n\n result = result_exprs[0]\n for result_expr in result_exprs[1:]:\n result = IntrinsicCall(\n op_code=chain_op,\n stack_args=[result, result_expr],\n wtype=wtypes.bool_wtype,\n source_location=location,\n )\n return BoolExpressionBuilder(result)\n\n\ndef _concat(\n this: InstanceBuilder[pytypes.TupleType],\n other: InstanceBuilder,\n location: SourceLocation,\n *,\n reverse: bool,\n) -> InstanceBuilder:\n if not isinstance(other.pytype, pytypes.TupleType):\n raise CodeError(\"can only concatenate tuple with other tuples\", location)\n other = typing.cast(InstanceBuilder[pytypes.TupleType], other)\n if not reverse:\n lhs, rhs = this, other\n else:\n lhs, rhs = other, this\n\n assert isinstance(lhs, StaticSizedCollectionBuilder)\n lhs_items = lhs.iterate_static()\n assert isinstance(rhs, StaticSizedCollectionBuilder)\n rhs_items = rhs.iterate_static()\n\n items = [*lhs_items, *rhs_items]\n return TupleLiteralBuilder(items, location)\n\n\ndef _iterable_item_type(\n pytype: pytypes.TupleType, source_location: SourceLocation\n) -> pytypes.PyType:\n base_type = determine_base_type(*pytype.items, location=source_location)\n if isinstance(base_type, pytypes.UnionType):\n raise CodeError(\n \"unable to iterate heterogeneous tuple without common base type\", source_location\n )\n return base_type\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/tuple.py","language":"Python","license":"NOASSERTION","size":23640} {"code":"import typing\nfrom collections.abc import Sequence\n\nimport attrs\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst import wtypes\nfrom puya.awst.nodes import (\n Expression,\n NumericComparison,\n NumericComparisonExpression,\n ReinterpretCast,\n Statement,\n UInt64AugmentedAssignment,\n UInt64BinaryOperation,\n UInt64BinaryOperator,\n UInt64Constant,\n UInt64UnaryOperation,\n UInt64UnaryOperator,\n)\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import intrinsic_factory, pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import NotIterableInstanceExpressionBuilder\nfrom puyapy.awst_build.eb._utils import dummy_statement\nfrom puyapy.awst_build.eb.bool import BoolExpressionBuilder\nfrom puyapy.awst_build.eb.interface import (\n BuilderBinaryOp,\n BuilderComparisonOp,\n BuilderUnaryOp,\n InstanceBuilder,\n LiteralBuilder,\n NodeBuilder,\n TypeBuilder,\n)\n\nlogger = log.get_logger(__name__)\n\n\nclass UInt64TypeBuilder(TypeBuilder):\n def __init__(self, location: SourceLocation):\n super().__init__(pytypes.UInt64Type, location)\n\n @typing.override\n def try_convert_literal(\n self, literal: LiteralBuilder, location: SourceLocation\n ) -> InstanceBuilder | None:\n match literal.value:\n case int(int_value):\n pytype = self.produces()\n if int_value < 0 or int_value.bit_length() > 64:\n logger.error(f\"invalid {pytype} value\", location=literal.source_location)\n # take int() of the value since it could match a bool also\n expr = UInt64Constant(value=int(int_value), source_location=location)\n return UInt64ExpressionBuilder(expr)\n return None\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n arg = expect.at_most_one_arg_of_type(\n args, [pytypes.IntLiteralType, pytypes.BoolType], location\n )\n match arg:\n case InstanceBuilder(pytype=pytypes.IntLiteralType):\n return arg.resolve_literal(converter=UInt64TypeBuilder(location))\n case InstanceBuilder(pytype=pytypes.BoolType):\n return _upcast_bool(arg, location)\n case _:\n return UInt64ExpressionBuilder(UInt64Constant(value=0, source_location=location))\n\n\nclass UInt64ExpressionBuilder(NotIterableInstanceExpressionBuilder):\n def __init__(self, expr: Expression, enum_type: pytypes.UInt64EnumType | None = None):\n if enum_type is None:\n pytype = pytypes.UInt64Type\n else:\n pytype = enum_type\n super().__init__(pytype, expr)\n\n @typing.override\n def to_bytes(self, location: SourceLocation) -> Expression:\n return intrinsic_factory.itob(self.resolve(), location)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n cmp_expr = NumericComparisonExpression(\n lhs=self.resolve(),\n operator=NumericComparison.eq if negate else NumericComparison.ne,\n rhs=UInt64Constant(value=0, source_location=location),\n source_location=location,\n )\n return BoolExpressionBuilder(cmp_expr)\n\n @typing.override\n def unary_op(self, op: BuilderUnaryOp, location: SourceLocation) -> InstanceBuilder:\n match op:\n case BuilderUnaryOp.positive:\n # unary + is allowed, but for the current types it has no real impact\n # so just expand the existing expression to include the unary operator\n return UInt64ExpressionBuilder(\n attrs.evolve(self.resolve(), source_location=location)\n )\n case BuilderUnaryOp.bit_invert:\n return UInt64ExpressionBuilder(\n UInt64UnaryOperation(\n expr=self.resolve(),\n op=UInt64UnaryOperator.bit_invert,\n source_location=location,\n )\n )\n case _:\n return super().unary_op(op, location)\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n other = _resolve_literal_and_upcast_bool(other)\n if not (pytypes.UInt64Type <= other.pytype):\n return NotImplemented\n cmp_expr = NumericComparisonExpression(\n source_location=location,\n lhs=self.resolve(),\n operator=NumericComparison(op.value),\n rhs=other.resolve(),\n )\n return BoolExpressionBuilder(cmp_expr)\n\n @typing.override\n def binary_op(\n self,\n other: InstanceBuilder,\n op: BuilderBinaryOp,\n location: SourceLocation,\n *,\n reverse: bool,\n ) -> InstanceBuilder:\n uint64_op = _translate_uint64_math_operator(op, location)\n if uint64_op is None:\n return NotImplemented\n other = _resolve_literal_and_upcast_bool(other)\n if not (pytypes.UInt64Type <= other.pytype):\n return NotImplemented\n\n lhs = self.resolve()\n rhs = other.resolve()\n if reverse:\n (lhs, rhs) = (rhs, lhs)\n bin_op_expr = UInt64BinaryOperation(\n left=lhs, op=uint64_op, right=rhs, source_location=location\n )\n return UInt64ExpressionBuilder(bin_op_expr)\n\n @typing.override\n def augmented_assignment(\n self, op: BuilderBinaryOp, rhs: InstanceBuilder, location: SourceLocation\n ) -> Statement:\n uint64_op = _translate_uint64_math_operator(op, location)\n if uint64_op is None:\n logger.error(f\"unsupported operator for type: {op.value!r}\", location=location)\n return dummy_statement(location)\n rhs = _resolve_literal_and_upcast_bool(rhs)\n # note: don't check for enum types here, mypy errors anyway\n rhs = expect.argument_of_type_else_dummy(rhs, pytypes.UInt64Type)\n target = self.resolve_lvalue()\n return UInt64AugmentedAssignment(\n target=target, op=uint64_op, value=rhs.resolve(), source_location=location\n )\n\n\ndef _translate_uint64_math_operator(\n operator: BuilderBinaryOp, loc: SourceLocation\n) -> UInt64BinaryOperator | None:\n if operator is BuilderBinaryOp.div:\n logger.error(\n (\n \"To maintain semantic compatibility with Python, \"\n \"only the truncating division operator (\/\/) is supported \"\n ),\n location=loc,\n )\n # continue traversing code to generate any further errors\n operator = BuilderBinaryOp.floor_div\n try:\n return UInt64BinaryOperator(operator.value)\n except ValueError:\n return None\n\n\ndef _resolve_literal_and_upcast_bool(other: InstanceBuilder) -> InstanceBuilder:\n other = other.resolve_literal(converter=UInt64TypeBuilder(other.source_location))\n if other.pytype == pytypes.BoolType:\n return _upcast_bool(other)\n return other\n\n\ndef _upcast_bool(\n builder: InstanceBuilder, location: SourceLocation | None = None\n) -> InstanceBuilder:\n assert builder.pytype == pytypes.BoolType\n expr = ReinterpretCast(\n expr=builder.resolve(),\n wtype=wtypes.uint64_wtype,\n source_location=location or builder.source_location,\n )\n return UInt64ExpressionBuilder(expr)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/uint64.py","language":"Python","license":"NOASSERTION","size":7641} {"code":"import enum\nimport typing\nfrom collections.abc import Mapping, Sequence\n\nimport mypy.nodes\n\nfrom puya.avm import OnCompletionAction, TransactionType\nfrom puya.awst.nodes import UInt64Constant\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb.interface import InstanceBuilder, NodeBuilder, TypeBuilder\nfrom puyapy.awst_build.eb.uint64 import UInt64ExpressionBuilder\n\n\nclass _UInt64EnumTypeBuilder(TypeBuilder):\n enum_type: typing.ClassVar[pytypes.UInt64EnumType]\n enum_data: typing.ClassVar[Mapping[str, enum.IntEnum] | Mapping[str, int]]\n\n def __init_subclass__(\n cls,\n enum_type: pytypes.UInt64EnumType,\n enum_data: Mapping[str, enum.IntEnum] | Mapping[str, int],\n **kwargs: typing.Any,\n ):\n super().__init_subclass__(**kwargs)\n cls.enum_type = enum_type\n cls.enum_data = enum_data\n\n def __init__(self, location: SourceLocation):\n super().__init__(self.enum_type, location)\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n raise CodeError(\"cannot instantiate enumeration type\", location)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n if (data := self.enum_data.get(name)) is None:\n return super().member_access(name, location)\n if isinstance(data, enum.IntEnum):\n teal_alias = data.name\n value = data.value\n else:\n teal_alias = None\n value = data\n\n const_expr = UInt64Constant(value=value, teal_alias=teal_alias, source_location=location)\n return UInt64ExpressionBuilder(const_expr, self.enum_type)\n\n\nclass OnCompletionActionTypeBuilder(\n _UInt64EnumTypeBuilder,\n enum_type=pytypes.OnCompleteActionType,\n enum_data={oca.name: oca for oca in OnCompletionAction},\n):\n pass\n\n\nclass TransactionTypeTypeBuilder(\n _UInt64EnumTypeBuilder,\n enum_type=pytypes.TransactionTypeType,\n enum_data={\n \"Payment\": TransactionType.pay,\n \"KeyRegistration\": TransactionType.keyreg,\n \"AssetConfig\": TransactionType.acfg,\n \"AssetTransfer\": TransactionType.axfer,\n \"AssetFreeze\": TransactionType.afrz,\n \"ApplicationCall\": TransactionType.appl,\n },\n):\n pass\n\n\nclass OpUpFeeSourceTypeBuilder(\n _UInt64EnumTypeBuilder,\n enum_type=pytypes.OpUpFeeSourceType,\n enum_data={\n \"GroupCredit\": 0,\n \"AppAccount\": 1,\n \"Any\": 2,\n },\n):\n pass\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/uint64_enums.py","language":"Python","license":"NOASSERTION","size":2704} {"code":"import abc\nimport typing\nfrom collections.abc import Sequence\n\nimport mypy.nodes\n\nfrom puya import log\nfrom puya.awst.nodes import (\n BinaryBooleanOperator,\n Enumeration,\n Expression,\n IntegerConstant,\n Lvalue,\n Range,\n Reversed,\n Statement,\n UInt64Constant,\n)\nfrom puya.errors import CodeError, InternalError\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._base import GenericTypeBuilder\nfrom puyapy.awst_build.eb.interface import (\n BuilderBinaryOp,\n BuilderComparisonOp,\n BuilderUnaryOp,\n InstanceBuilder,\n NodeBuilder,\n TypeBuilder,\n)\nfrom puyapy.awst_build.eb.uint64 import UInt64ExpressionBuilder\n\nlogger = log.get_logger(__name__)\n\n\nclass UnsignedRangeBuilder(TypeBuilder):\n def __init__(self, location: SourceLocation):\n super().__init__(pytypes.urangeType, location)\n\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n assert set(arg_names) == {None}\n uint64_args = [\n expect.argument_of_type_else_dummy(in_arg, pytypes.UInt64Type, resolve_literal=True)\n for in_arg in args\n ]\n first, rest = expect.at_least_one_arg(\n uint64_args, location, default=expect.default_dummy_value(pytypes.UInt64Type)\n )\n match rest:\n case []:\n range_stop = first\n range_start: InstanceBuilder = UInt64ExpressionBuilder(\n UInt64Constant(value=0, source_location=location)\n )\n range_step: InstanceBuilder = UInt64ExpressionBuilder(\n UInt64Constant(value=1, source_location=location)\n )\n case [range_stop]:\n range_start = first\n range_step = UInt64ExpressionBuilder(\n UInt64Constant(value=1, source_location=location)\n )\n case [range_stop, range_step, *extra]:\n range_start = first\n if isinstance(range_step, IntegerConstant) and range_step.value == 0:\n logger.error(\n \"urange step size cannot be zero\", location=range_step.source_location\n )\n if extra:\n logger.error(\n f\"expected at most 3 arguments, got {len(args)}\", location=location\n )\n case _:\n raise InternalError(\"UH OH SPAGHETTI-O's !!! \ud83e\udd20\ud83c\udf5d\ud83c\udf35\ufe0f\", location)\n\n return _RangeIterBuilder(\n source_location=location,\n start=range_start,\n stop=range_stop,\n step=range_step,\n )\n\n\nclass UnsignedEnumerateBuilder(GenericTypeBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n # note: we actually expect exactly 1, but want to provide special error message\n # in case of extra params\n sequence, extra = expect.at_least_one_arg(args, location, default=expect.default_raise)\n if extra:\n logger.error(\n \"unlike enumerate(), uenumerate() does not support a start parameter \"\n \"(ie, start must always be zero)\",\n location=location,\n )\n return _EnumerateIterBuilder(sequence, location)\n\n\nclass ReversedFunctionExpressionBuilder(GenericTypeBuilder):\n @typing.override\n def call(\n self,\n args: Sequence[NodeBuilder],\n arg_kinds: list[mypy.nodes.ArgKind],\n arg_names: list[str | None],\n location: SourceLocation,\n ) -> InstanceBuilder:\n sequence = expect.exactly_one_arg(args, location, default=expect.default_raise)\n return _ReversedIterBuilder(sequence, location)\n\n\nclass _IterableOnlyBuilder(InstanceBuilder, abc.ABC):\n @typing.override\n def resolve_literal(self, converter: TypeBuilder) -> InstanceBuilder:\n return self.try_resolve_literal(converter)\n\n @typing.override\n def try_resolve_literal(self, converter: TypeBuilder) -> InstanceBuilder:\n return self\n\n @typing.override\n def to_bytes(self, location: SourceLocation) -> Expression:\n return self._iterable_only(location)\n\n @typing.override\n def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:\n return self._iterable_only(location)\n\n @typing.override\n def resolve(self) -> Expression:\n return self._iterable_only(self.source_location)\n\n @typing.override\n def resolve_lvalue(self) -> Lvalue:\n return self._iterable_only(self.source_location)\n\n @typing.override\n def delete(self, location: SourceLocation) -> Statement:\n return self._iterable_only(location)\n\n @typing.override\n def unary_op(self, op: BuilderUnaryOp, location: SourceLocation) -> InstanceBuilder:\n return self._iterable_only(location)\n\n @typing.override\n def contains(self, item: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n return self._iterable_only(location)\n\n @typing.override\n def index(self, index: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:\n return self._iterable_only(location)\n\n @typing.override\n def slice_index(\n self,\n begin_index: InstanceBuilder | None,\n end_index: InstanceBuilder | None,\n stride: InstanceBuilder | None,\n location: SourceLocation,\n ) -> InstanceBuilder:\n return self._iterable_only(location)\n\n @typing.override\n def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:\n return self._iterable_only(location)\n\n @typing.override\n def compare(\n self, other: InstanceBuilder, op: BuilderComparisonOp, location: SourceLocation\n ) -> InstanceBuilder:\n return self._iterable_only(location)\n\n @typing.override\n def binary_op(\n self,\n other: InstanceBuilder,\n op: BuilderBinaryOp,\n location: SourceLocation,\n *,\n reverse: bool,\n ) -> InstanceBuilder:\n return self._iterable_only(location)\n\n @typing.override\n def bool_binary_op(\n self, other: InstanceBuilder, op: BinaryBooleanOperator, location: SourceLocation\n ) -> InstanceBuilder:\n return self._iterable_only(location)\n\n @typing.override\n def augmented_assignment(\n self, op: BuilderBinaryOp, rhs: InstanceBuilder, location: SourceLocation\n ) -> Statement:\n return self._iterable_only(location)\n\n def _iterable_only(self, location: SourceLocation) -> typing.Never:\n raise CodeError(\"expression is only usable as the source of a for-loop\", location)\n\n\nclass _RangeIterBuilder(_IterableOnlyBuilder):\n def __init__(\n self,\n start: InstanceBuilder,\n stop: InstanceBuilder,\n step: InstanceBuilder,\n source_location: SourceLocation,\n ):\n super().__init__(source_location)\n self._start = start\n self._stop = stop\n self._step = step\n\n @typing.override\n @property\n def pytype(self) -> pytypes.PyType:\n return pytypes.urangeType\n\n @typing.override\n def iterate(self) -> Expression:\n return Range(\n start=self._start.resolve(),\n stop=self._stop.resolve(),\n step=self._step.resolve(),\n source_location=self.source_location,\n )\n\n @typing.override\n def iterable_item_type(self) -> pytypes.PyType:\n return pytypes.UInt64Type\n\n @typing.override\n def single_eval(self) -> InstanceBuilder:\n return _RangeIterBuilder(\n start=self._start.single_eval(),\n stop=self._stop.single_eval(),\n step=self._step.single_eval(),\n source_location=self.source_location,\n )\n\n\nclass _EnumerateIterBuilder(_IterableOnlyBuilder):\n def __init__(self, sequence: InstanceBuilder, source_location: SourceLocation):\n super().__init__(source_location)\n self._sequence = sequence\n\n @typing.override\n @property\n def pytype(self) -> pytypes.PyType:\n # TODO: this should be parametrised using the sequence item pytype\n return pytypes.uenumerateGenericType\n\n @typing.override\n def iterate(self) -> Expression:\n return Enumeration(expr=self._sequence.iterate(), source_location=self.source_location)\n\n @typing.override\n def iterable_item_type(self) -> pytypes.PyType:\n item_type = self._sequence.iterable_item_type()\n return pytypes.GenericTupleType.parameterise(\n [pytypes.UInt64Type, item_type], self.source_location\n )\n\n @typing.override\n def single_eval(self) -> InstanceBuilder:\n return _EnumerateIterBuilder(self._sequence.single_eval(), self.source_location)\n\n\nclass _ReversedIterBuilder(_IterableOnlyBuilder):\n def __init__(self, sequence: InstanceBuilder, source_location: SourceLocation):\n super().__init__(source_location)\n self._sequence = sequence\n\n @typing.override\n @property\n def pytype(self) -> pytypes.PyType:\n # TODO: this should be parametrised using the sequence item pytype\n return pytypes.reversedGenericType\n\n @typing.override\n def iterate(self) -> Expression:\n return Reversed(expr=self._sequence.iterate(), source_location=self.source_location)\n\n @typing.override\n def iterable_item_type(self) -> pytypes.PyType:\n return self._sequence.iterable_item_type()\n\n @typing.override\n def single_eval(self) -> InstanceBuilder:\n return _ReversedIterBuilder(self._sequence.single_eval(), self.source_location)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/eb\/unsigned_builtins.py","language":"Python","license":"NOASSERTION","size":9974} {"code":"import mypy.nodes\n\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\n\n\nclass UnsupportedASTError(CodeError):\n def __init__(\n self, node: mypy.nodes.Context, location: SourceLocation, *, details: str | None = None\n ):\n msg = f\"Unsupported construct {type(node).__name__}\"\n if details:\n msg += f\": {details}\"\n super().__init__(msg, location=location)\n self.details = details\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/exceptions.py","language":"Python","license":"NOASSERTION","size":447} {"code":"import typing\nfrom collections.abc import Mapping\n\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.intrinsic_models import (\n FunctionOpMapping,\n OpMappingWithOverloads,\n PropertyOpMapping,\n)\n\nENUM_CLASSES: typing.Final[Mapping[str, Mapping[str, str]]] = dict(\n EC=dict(\n BN254g1=\"BN254g1\",\n BN254g2=\"BN254g2\",\n BLS12_381g1=\"BLS12_381g1\",\n BLS12_381g2=\"BLS12_381g2\",\n ),\n Base64=dict(\n URLEncoding=\"URLEncoding\",\n StdEncoding=\"StdEncoding\",\n ),\n ECDSA=dict(\n Secp256k1=\"Secp256k1\",\n Secp256r1=\"Secp256r1\",\n ),\n MiMCConfigurations=dict(\n BN254Mp110=\"BN254Mp110\",\n BLS12_381Mp111=\"BLS12_381Mp111\",\n ),\n VrfVerify=dict(\n VrfAlgorand=\"VrfAlgorand\",\n ),\n)\n\nFUNC_TO_AST_MAPPER: typing.Final[Mapping[str, OpMappingWithOverloads]] = dict(\n addw=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.UInt64Type), source_location=None\n ),\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"addw\",\n args=[(pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n ],\n ),\n app_opted_in=OpMappingWithOverloads(\n result=pytypes.BoolType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"app_opted_in\",\n args=[\n (pytypes.AccountType, pytypes.UInt64Type),\n (pytypes.ApplicationType, pytypes.UInt64Type),\n ],\n ),\n ],\n ),\n arg=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"args\",\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"arg\",\n immediates=[int],\n args=[0],\n ),\n ],\n ),\n balance=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"balance\",\n args=[(pytypes.AccountType, pytypes.UInt64Type)],\n ),\n ],\n ),\n base64_decode=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"base64_decode\",\n immediates=[str],\n args=[0, (pytypes.BytesType,)],\n ),\n ],\n ),\n bitlen=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"bitlen\",\n args=[(pytypes.BytesType, pytypes.UInt64Type)],\n ),\n ],\n ),\n bsqrt=OpMappingWithOverloads(\n result=pytypes.BigUIntType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"bsqrt\",\n args=[(pytypes.BigUIntType,)],\n ),\n ],\n ),\n btoi=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"btoi\",\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n bzero=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"bzero\",\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n concat=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"concat\",\n args=[(pytypes.BytesType,), (pytypes.BytesType,)],\n ),\n ],\n ),\n divmodw=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.UInt64Type, pytypes.UInt64Type, pytypes.UInt64Type),\n source_location=None,\n ),\n arity=4,\n overloads=[\n FunctionOpMapping(\n \"divmodw\",\n args=[\n (pytypes.UInt64Type,),\n (pytypes.UInt64Type,),\n (pytypes.UInt64Type,),\n (pytypes.UInt64Type,),\n ],\n ),\n ],\n ),\n divw=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=3,\n overloads=[\n FunctionOpMapping(\n \"divw\",\n args=[(pytypes.UInt64Type,), (pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n ],\n ),\n ecdsa_pk_decompress=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.BytesType, pytypes.BytesType), source_location=None\n ),\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"ecdsa_pk_decompress\",\n immediates=[str],\n args=[0, (pytypes.BytesType,)],\n ),\n ],\n ),\n ecdsa_pk_recover=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.BytesType, pytypes.BytesType), source_location=None\n ),\n arity=5,\n overloads=[\n FunctionOpMapping(\n \"ecdsa_pk_recover\",\n immediates=[str],\n args=[\n 0,\n (pytypes.BytesType,),\n (pytypes.UInt64Type,),\n (pytypes.BytesType,),\n (pytypes.BytesType,),\n ],\n ),\n ],\n ),\n ecdsa_verify=OpMappingWithOverloads(\n result=pytypes.BoolType,\n arity=6,\n overloads=[\n FunctionOpMapping(\n \"ecdsa_verify\",\n immediates=[str],\n args=[\n 0,\n (pytypes.BytesType,),\n (pytypes.BytesType,),\n (pytypes.BytesType,),\n (pytypes.BytesType,),\n (pytypes.BytesType,),\n ],\n ),\n ],\n ),\n ed25519verify=OpMappingWithOverloads(\n result=pytypes.BoolType,\n arity=3,\n overloads=[\n FunctionOpMapping(\n \"ed25519verify\",\n args=[(pytypes.BytesType,), (pytypes.BytesType,), (pytypes.BytesType,)],\n ),\n ],\n ),\n ed25519verify_bare=OpMappingWithOverloads(\n result=pytypes.BoolType,\n arity=3,\n overloads=[\n FunctionOpMapping(\n \"ed25519verify_bare\",\n args=[(pytypes.BytesType,), (pytypes.BytesType,), (pytypes.BytesType,)],\n ),\n ],\n ),\n err=OpMappingWithOverloads(\n result=pytypes.NeverType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"err\",\n ),\n ],\n ),\n exit=OpMappingWithOverloads(\n result=pytypes.NeverType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"return\",\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n exp=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"exp\",\n args=[(pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n ],\n ),\n expw=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.UInt64Type), source_location=None\n ),\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"expw\",\n args=[(pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n ],\n ),\n extract=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=3,\n overloads=[\n FunctionOpMapping(\n \"extract3\",\n args=[(pytypes.BytesType,), (pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"extract\",\n immediates=[int, int],\n args=[(pytypes.BytesType,), 0, 1],\n ),\n ],\n ),\n extract_uint16=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"extract_uint16\",\n args=[(pytypes.BytesType,), (pytypes.UInt64Type,)],\n ),\n ],\n ),\n extract_uint32=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"extract_uint32\",\n args=[(pytypes.BytesType,), (pytypes.UInt64Type,)],\n ),\n ],\n ),\n extract_uint64=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"extract_uint64\",\n args=[(pytypes.BytesType,), (pytypes.UInt64Type,)],\n ),\n ],\n ),\n falcon_verify=OpMappingWithOverloads(\n result=pytypes.BoolType,\n arity=3,\n overloads=[\n FunctionOpMapping(\n \"falcon_verify\",\n args=[(pytypes.BytesType,), (pytypes.BytesType,), (pytypes.BytesType,)],\n ),\n ],\n ),\n gaid=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gaids\",\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gaid\",\n immediates=[int],\n args=[0],\n ),\n ],\n ),\n getbit=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"getbit\",\n args=[(pytypes.BytesType, pytypes.UInt64Type), (pytypes.UInt64Type,)],\n ),\n ],\n ),\n getbyte=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"getbyte\",\n args=[(pytypes.BytesType,), (pytypes.UInt64Type,)],\n ),\n ],\n ),\n gload_bytes=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"gloadss\",\n args=[(pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gload\",\n immediates=[int, int],\n args=[0, 1],\n ),\n FunctionOpMapping(\n \"gloads\",\n immediates=[int],\n args=[(pytypes.UInt64Type,), 0],\n ),\n ],\n ),\n gload_uint64=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"gloadss\",\n args=[(pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gload\",\n immediates=[int, int],\n args=[0, 1],\n ),\n FunctionOpMapping(\n \"gloads\",\n immediates=[int],\n args=[(pytypes.UInt64Type,), 0],\n ),\n ],\n ),\n itob=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itob\",\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n keccak256=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"keccak256\",\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n mimc=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"mimc\",\n immediates=[str],\n args=[0, (pytypes.BytesType,)],\n ),\n ],\n ),\n min_balance=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"min_balance\",\n args=[(pytypes.AccountType, pytypes.UInt64Type)],\n ),\n ],\n ),\n mulw=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.UInt64Type), source_location=None\n ),\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"mulw\",\n args=[(pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n ],\n ),\n online_stake=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"online_stake\",\n ),\n ],\n ),\n replace=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=3,\n overloads=[\n FunctionOpMapping(\n \"replace3\",\n args=[(pytypes.BytesType,), (pytypes.UInt64Type,), (pytypes.BytesType,)],\n ),\n FunctionOpMapping(\n \"replace2\",\n immediates=[int],\n args=[(pytypes.BytesType,), 0, (pytypes.BytesType,)],\n ),\n ],\n ),\n select_bytes=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=3,\n overloads=[\n FunctionOpMapping(\n \"select\",\n args=[\n (pytypes.BytesType,),\n (pytypes.BytesType,),\n (pytypes.BoolType, pytypes.UInt64Type),\n ],\n ),\n ],\n ),\n select_uint64=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=3,\n overloads=[\n FunctionOpMapping(\n \"select\",\n args=[\n (pytypes.UInt64Type,),\n (pytypes.UInt64Type,),\n (pytypes.BoolType, pytypes.UInt64Type),\n ],\n ),\n ],\n ),\n setbit_bytes=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=3,\n overloads=[\n FunctionOpMapping(\n \"setbit\",\n args=[(pytypes.BytesType,), (pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n ],\n ),\n setbit_uint64=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=3,\n overloads=[\n FunctionOpMapping(\n \"setbit\",\n args=[(pytypes.UInt64Type,), (pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n ],\n ),\n setbyte=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=3,\n overloads=[\n FunctionOpMapping(\n \"setbyte\",\n args=[(pytypes.BytesType,), (pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n ],\n ),\n sha256=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"sha256\",\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n sha3_256=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"sha3_256\",\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n sha512_256=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"sha512_256\",\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n shl=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"shl\",\n args=[(pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n ],\n ),\n shr=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"shr\",\n args=[(pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n ],\n ),\n sqrt=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"sqrt\",\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n substring=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=3,\n overloads=[\n FunctionOpMapping(\n \"substring3\",\n args=[(pytypes.BytesType,), (pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"substring\",\n immediates=[int, int],\n args=[(pytypes.BytesType,), 0, 1],\n ),\n ],\n ),\n sumhash512=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"sumhash512\",\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n vrf_verify=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.BytesType, pytypes.BoolType), source_location=None\n ),\n arity=4,\n overloads=[\n FunctionOpMapping(\n \"vrf_verify\",\n immediates=[str],\n args=[0, (pytypes.BytesType,), (pytypes.BytesType,), (pytypes.BytesType,)],\n ),\n ],\n ),\n)\nNAMESPACE_CLASSES: typing.Final[\n Mapping[str, Mapping[str, PropertyOpMapping | OpMappingWithOverloads]]\n] = dict(\n AcctParamsGet=dict(\n acct_balance=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"acct_params_get\",\n immediates=[\"AcctBalance\"],\n args=[(pytypes.AccountType, pytypes.UInt64Type)],\n ),\n ],\n ),\n acct_min_balance=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"acct_params_get\",\n immediates=[\"AcctMinBalance\"],\n args=[(pytypes.AccountType, pytypes.UInt64Type)],\n ),\n ],\n ),\n acct_auth_addr=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.AccountType, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"acct_params_get\",\n immediates=[\"AcctAuthAddr\"],\n args=[(pytypes.AccountType, pytypes.UInt64Type)],\n ),\n ],\n ),\n acct_total_num_uint=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"acct_params_get\",\n immediates=[\"AcctTotalNumUint\"],\n args=[(pytypes.AccountType, pytypes.UInt64Type)],\n ),\n ],\n ),\n acct_total_num_byte_slice=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"acct_params_get\",\n immediates=[\"AcctTotalNumByteSlice\"],\n args=[(pytypes.AccountType, pytypes.UInt64Type)],\n ),\n ],\n ),\n acct_total_extra_app_pages=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"acct_params_get\",\n immediates=[\"AcctTotalExtraAppPages\"],\n args=[(pytypes.AccountType, pytypes.UInt64Type)],\n ),\n ],\n ),\n acct_total_apps_created=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"acct_params_get\",\n immediates=[\"AcctTotalAppsCreated\"],\n args=[(pytypes.AccountType, pytypes.UInt64Type)],\n ),\n ],\n ),\n acct_total_apps_opted_in=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"acct_params_get\",\n immediates=[\"AcctTotalAppsOptedIn\"],\n args=[(pytypes.AccountType, pytypes.UInt64Type)],\n ),\n ],\n ),\n acct_total_assets_created=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"acct_params_get\",\n immediates=[\"AcctTotalAssetsCreated\"],\n args=[(pytypes.AccountType, pytypes.UInt64Type)],\n ),\n ],\n ),\n acct_total_assets=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"acct_params_get\",\n immediates=[\"AcctTotalAssets\"],\n args=[(pytypes.AccountType, pytypes.UInt64Type)],\n ),\n ],\n ),\n acct_total_boxes=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"acct_params_get\",\n immediates=[\"AcctTotalBoxes\"],\n args=[(pytypes.AccountType, pytypes.UInt64Type)],\n ),\n ],\n ),\n acct_total_box_bytes=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"acct_params_get\",\n immediates=[\"AcctTotalBoxBytes\"],\n args=[(pytypes.AccountType, pytypes.UInt64Type)],\n ),\n ],\n ),\n acct_incentive_eligible=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.BoolType, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"acct_params_get\",\n immediates=[\"AcctIncentiveEligible\"],\n args=[(pytypes.AccountType, pytypes.UInt64Type)],\n ),\n ],\n ),\n acct_last_proposed=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"acct_params_get\",\n immediates=[\"AcctLastProposed\"],\n args=[(pytypes.AccountType, pytypes.UInt64Type)],\n ),\n ],\n ),\n acct_last_heartbeat=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"acct_params_get\",\n immediates=[\"AcctLastHeartbeat\"],\n args=[(pytypes.AccountType, pytypes.UInt64Type)],\n ),\n ],\n ),\n ),\n AppGlobal=dict(\n get_bytes=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"app_global_get\",\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n get_uint64=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"app_global_get\",\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n get_ex_bytes=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.BytesType, pytypes.BoolType), source_location=None\n ),\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"app_global_get_ex\",\n args=[(pytypes.ApplicationType, pytypes.UInt64Type), (pytypes.BytesType,)],\n ),\n ],\n ),\n get_ex_uint64=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"app_global_get_ex\",\n args=[(pytypes.ApplicationType, pytypes.UInt64Type), (pytypes.BytesType,)],\n ),\n ],\n ),\n delete=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"app_global_del\",\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n put=OpMappingWithOverloads(\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"app_global_put\",\n args=[(pytypes.BytesType,), (pytypes.BytesType, pytypes.UInt64Type)],\n ),\n ],\n ),\n ),\n AppLocal=dict(\n get_bytes=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"app_local_get\",\n args=[(pytypes.AccountType, pytypes.UInt64Type), (pytypes.BytesType,)],\n ),\n ],\n ),\n get_uint64=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"app_local_get\",\n args=[(pytypes.AccountType, pytypes.UInt64Type), (pytypes.BytesType,)],\n ),\n ],\n ),\n get_ex_bytes=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.BytesType, pytypes.BoolType), source_location=None\n ),\n arity=3,\n overloads=[\n FunctionOpMapping(\n \"app_local_get_ex\",\n args=[\n (pytypes.AccountType, pytypes.UInt64Type),\n (pytypes.ApplicationType, pytypes.UInt64Type),\n (pytypes.BytesType,),\n ],\n ),\n ],\n ),\n get_ex_uint64=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=3,\n overloads=[\n FunctionOpMapping(\n \"app_local_get_ex\",\n args=[\n (pytypes.AccountType, pytypes.UInt64Type),\n (pytypes.ApplicationType, pytypes.UInt64Type),\n (pytypes.BytesType,),\n ],\n ),\n ],\n ),\n delete=OpMappingWithOverloads(\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"app_local_del\",\n args=[(pytypes.AccountType, pytypes.UInt64Type), (pytypes.BytesType,)],\n ),\n ],\n ),\n put=OpMappingWithOverloads(\n arity=3,\n overloads=[\n FunctionOpMapping(\n \"app_local_put\",\n args=[\n (pytypes.AccountType, pytypes.UInt64Type),\n (pytypes.BytesType,),\n (pytypes.BytesType, pytypes.UInt64Type),\n ],\n ),\n ],\n ),\n ),\n AppParamsGet=dict(\n app_approval_program=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.BytesType, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"app_params_get\",\n immediates=[\"AppApprovalProgram\"],\n args=[(pytypes.ApplicationType, pytypes.UInt64Type)],\n ),\n ],\n ),\n app_clear_state_program=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.BytesType, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"app_params_get\",\n immediates=[\"AppClearStateProgram\"],\n args=[(pytypes.ApplicationType, pytypes.UInt64Type)],\n ),\n ],\n ),\n app_global_num_uint=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"app_params_get\",\n immediates=[\"AppGlobalNumUint\"],\n args=[(pytypes.ApplicationType, pytypes.UInt64Type)],\n ),\n ],\n ),\n app_global_num_byte_slice=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"app_params_get\",\n immediates=[\"AppGlobalNumByteSlice\"],\n args=[(pytypes.ApplicationType, pytypes.UInt64Type)],\n ),\n ],\n ),\n app_local_num_uint=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"app_params_get\",\n immediates=[\"AppLocalNumUint\"],\n args=[(pytypes.ApplicationType, pytypes.UInt64Type)],\n ),\n ],\n ),\n app_local_num_byte_slice=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"app_params_get\",\n immediates=[\"AppLocalNumByteSlice\"],\n args=[(pytypes.ApplicationType, pytypes.UInt64Type)],\n ),\n ],\n ),\n app_extra_program_pages=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"app_params_get\",\n immediates=[\"AppExtraProgramPages\"],\n args=[(pytypes.ApplicationType, pytypes.UInt64Type)],\n ),\n ],\n ),\n app_creator=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.AccountType, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"app_params_get\",\n immediates=[\"AppCreator\"],\n args=[(pytypes.ApplicationType, pytypes.UInt64Type)],\n ),\n ],\n ),\n app_address=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.AccountType, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"app_params_get\",\n immediates=[\"AppAddress\"],\n args=[(pytypes.ApplicationType, pytypes.UInt64Type)],\n ),\n ],\n ),\n ),\n AssetHoldingGet=dict(\n asset_balance=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"asset_holding_get\",\n immediates=[\"AssetBalance\"],\n args=[\n (pytypes.AccountType, pytypes.UInt64Type),\n (pytypes.AssetType, pytypes.UInt64Type),\n ],\n ),\n ],\n ),\n asset_frozen=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.BoolType, pytypes.BoolType), source_location=None\n ),\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"asset_holding_get\",\n immediates=[\"AssetFrozen\"],\n args=[\n (pytypes.AccountType, pytypes.UInt64Type),\n (pytypes.AssetType, pytypes.UInt64Type),\n ],\n ),\n ],\n ),\n ),\n AssetParamsGet=dict(\n asset_total=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"asset_params_get\",\n immediates=[\"AssetTotal\"],\n args=[(pytypes.AssetType, pytypes.UInt64Type)],\n ),\n ],\n ),\n asset_decimals=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"asset_params_get\",\n immediates=[\"AssetDecimals\"],\n args=[(pytypes.AssetType, pytypes.UInt64Type)],\n ),\n ],\n ),\n asset_default_frozen=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.BoolType, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"asset_params_get\",\n immediates=[\"AssetDefaultFrozen\"],\n args=[(pytypes.AssetType, pytypes.UInt64Type)],\n ),\n ],\n ),\n asset_unit_name=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.BytesType, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"asset_params_get\",\n immediates=[\"AssetUnitName\"],\n args=[(pytypes.AssetType, pytypes.UInt64Type)],\n ),\n ],\n ),\n asset_name=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.BytesType, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"asset_params_get\",\n immediates=[\"AssetName\"],\n args=[(pytypes.AssetType, pytypes.UInt64Type)],\n ),\n ],\n ),\n asset_url=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.BytesType, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"asset_params_get\",\n immediates=[\"AssetURL\"],\n args=[(pytypes.AssetType, pytypes.UInt64Type)],\n ),\n ],\n ),\n asset_metadata_hash=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.BytesType, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"asset_params_get\",\n immediates=[\"AssetMetadataHash\"],\n args=[(pytypes.AssetType, pytypes.UInt64Type)],\n ),\n ],\n ),\n asset_manager=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.AccountType, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"asset_params_get\",\n immediates=[\"AssetManager\"],\n args=[(pytypes.AssetType, pytypes.UInt64Type)],\n ),\n ],\n ),\n asset_reserve=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.AccountType, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"asset_params_get\",\n immediates=[\"AssetReserve\"],\n args=[(pytypes.AssetType, pytypes.UInt64Type)],\n ),\n ],\n ),\n asset_freeze=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.AccountType, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"asset_params_get\",\n immediates=[\"AssetFreeze\"],\n args=[(pytypes.AssetType, pytypes.UInt64Type)],\n ),\n ],\n ),\n asset_clawback=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.AccountType, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"asset_params_get\",\n immediates=[\"AssetClawback\"],\n args=[(pytypes.AssetType, pytypes.UInt64Type)],\n ),\n ],\n ),\n asset_creator=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.AccountType, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"asset_params_get\",\n immediates=[\"AssetCreator\"],\n args=[(pytypes.AssetType, pytypes.UInt64Type)],\n ),\n ],\n ),\n ),\n Block=dict(\n blk_seed=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"block\",\n immediates=[\"BlkSeed\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n blk_timestamp=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"block\",\n immediates=[\"BlkTimestamp\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n blk_proposer=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"block\",\n immediates=[\"BlkProposer\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n blk_fees_collected=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"block\",\n immediates=[\"BlkFeesCollected\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n blk_bonus=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"block\",\n immediates=[\"BlkBonus\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n blk_branch=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"block\",\n immediates=[\"BlkBranch\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n blk_fee_sink=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"block\",\n immediates=[\"BlkFeeSink\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n blk_protocol=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"block\",\n immediates=[\"BlkProtocol\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n blk_txn_counter=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"block\",\n immediates=[\"BlkTxnCounter\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n blk_proposer_payout=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"block\",\n immediates=[\"BlkProposerPayout\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n ),\n Box=dict(\n create=OpMappingWithOverloads(\n result=pytypes.BoolType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"box_create\",\n args=[(pytypes.BytesType,), (pytypes.UInt64Type,)],\n ),\n ],\n ),\n delete=OpMappingWithOverloads(\n result=pytypes.BoolType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"box_del\",\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n extract=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=3,\n overloads=[\n FunctionOpMapping(\n \"box_extract\",\n args=[(pytypes.BytesType,), (pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n ],\n ),\n get=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.BytesType, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"box_get\",\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n length=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"box_len\",\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n put=OpMappingWithOverloads(\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"box_put\",\n args=[(pytypes.BytesType,), (pytypes.BytesType,)],\n ),\n ],\n ),\n replace=OpMappingWithOverloads(\n arity=3,\n overloads=[\n FunctionOpMapping(\n \"box_replace\",\n args=[(pytypes.BytesType,), (pytypes.UInt64Type,), (pytypes.BytesType,)],\n ),\n ],\n ),\n resize=OpMappingWithOverloads(\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"box_resize\",\n args=[(pytypes.BytesType,), (pytypes.UInt64Type,)],\n ),\n ],\n ),\n splice=OpMappingWithOverloads(\n arity=4,\n overloads=[\n FunctionOpMapping(\n \"box_splice\",\n args=[\n (pytypes.BytesType,),\n (pytypes.UInt64Type,),\n (pytypes.UInt64Type,),\n (pytypes.BytesType,),\n ],\n ),\n ],\n ),\n ),\n EllipticCurve=dict(\n add=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=3,\n overloads=[\n FunctionOpMapping(\n \"ec_add\",\n immediates=[str],\n args=[0, (pytypes.BytesType,), (pytypes.BytesType,)],\n ),\n ],\n ),\n map_to=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"ec_map_to\",\n immediates=[str],\n args=[0, (pytypes.BytesType,)],\n ),\n ],\n ),\n scalar_mul_multi=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=3,\n overloads=[\n FunctionOpMapping(\n \"ec_multi_scalar_mul\",\n immediates=[str],\n args=[0, (pytypes.BytesType,), (pytypes.BytesType,)],\n ),\n ],\n ),\n pairing_check=OpMappingWithOverloads(\n result=pytypes.BoolType,\n arity=3,\n overloads=[\n FunctionOpMapping(\n \"ec_pairing_check\",\n immediates=[str],\n args=[0, (pytypes.BytesType,), (pytypes.BytesType,)],\n ),\n ],\n ),\n scalar_mul=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=3,\n overloads=[\n FunctionOpMapping(\n \"ec_scalar_mul\",\n immediates=[str],\n args=[0, (pytypes.BytesType,), (pytypes.BytesType,)],\n ),\n ],\n ),\n subgroup_check=OpMappingWithOverloads(\n result=pytypes.BoolType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"ec_subgroup_check\",\n immediates=[str],\n args=[0, (pytypes.BytesType,)],\n ),\n ],\n ),\n ),\n GITxn=dict(\n sender=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"Sender\"],\n args=[0],\n ),\n ],\n ),\n fee=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"Fee\"],\n args=[0],\n ),\n ],\n ),\n first_valid=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"FirstValid\"],\n args=[0],\n ),\n ],\n ),\n first_valid_time=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"FirstValidTime\"],\n args=[0],\n ),\n ],\n ),\n last_valid=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"LastValid\"],\n args=[0],\n ),\n ],\n ),\n note=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"Note\"],\n args=[0],\n ),\n ],\n ),\n lease=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"Lease\"],\n args=[0],\n ),\n ],\n ),\n receiver=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"Receiver\"],\n args=[0],\n ),\n ],\n ),\n amount=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"Amount\"],\n args=[0],\n ),\n ],\n ),\n close_remainder_to=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"CloseRemainderTo\"],\n args=[0],\n ),\n ],\n ),\n vote_pk=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"VotePK\"],\n args=[0],\n ),\n ],\n ),\n selection_pk=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"SelectionPK\"],\n args=[0],\n ),\n ],\n ),\n vote_first=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"VoteFirst\"],\n args=[0],\n ),\n ],\n ),\n vote_last=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"VoteLast\"],\n args=[0],\n ),\n ],\n ),\n vote_key_dilution=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"VoteKeyDilution\"],\n args=[0],\n ),\n ],\n ),\n type=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"Type\"],\n args=[0],\n ),\n ],\n ),\n type_enum=OpMappingWithOverloads(\n result=pytypes.TransactionTypeType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"TypeEnum\"],\n args=[0],\n ),\n ],\n ),\n xfer_asset=OpMappingWithOverloads(\n result=pytypes.AssetType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"XferAsset\"],\n args=[0],\n ),\n ],\n ),\n asset_amount=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"AssetAmount\"],\n args=[0],\n ),\n ],\n ),\n asset_sender=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"AssetSender\"],\n args=[0],\n ),\n ],\n ),\n asset_receiver=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"AssetReceiver\"],\n args=[0],\n ),\n ],\n ),\n asset_close_to=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"AssetCloseTo\"],\n args=[0],\n ),\n ],\n ),\n group_index=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"GroupIndex\"],\n args=[0],\n ),\n ],\n ),\n tx_id=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"TxID\"],\n args=[0],\n ),\n ],\n ),\n application_id=OpMappingWithOverloads(\n result=pytypes.ApplicationType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"ApplicationID\"],\n args=[0],\n ),\n ],\n ),\n on_completion=OpMappingWithOverloads(\n result=pytypes.OnCompleteActionType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"OnCompletion\"],\n args=[0],\n ),\n ],\n ),\n application_args=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"gitxnas\",\n immediates=[int, \"ApplicationArgs\"],\n args=[0, (pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gitxna\",\n immediates=[int, \"ApplicationArgs\", int],\n args=[0, 2],\n ),\n ],\n ),\n num_app_args=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"NumAppArgs\"],\n args=[0],\n ),\n ],\n ),\n accounts=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"gitxnas\",\n immediates=[int, \"Accounts\"],\n args=[0, (pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gitxna\",\n immediates=[int, \"Accounts\", int],\n args=[0, 2],\n ),\n ],\n ),\n num_accounts=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"NumAccounts\"],\n args=[0],\n ),\n ],\n ),\n approval_program=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"ApprovalProgram\"],\n args=[0],\n ),\n ],\n ),\n clear_state_program=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"ClearStateProgram\"],\n args=[0],\n ),\n ],\n ),\n rekey_to=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"RekeyTo\"],\n args=[0],\n ),\n ],\n ),\n config_asset=OpMappingWithOverloads(\n result=pytypes.AssetType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"ConfigAsset\"],\n args=[0],\n ),\n ],\n ),\n config_asset_total=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"ConfigAssetTotal\"],\n args=[0],\n ),\n ],\n ),\n config_asset_decimals=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"ConfigAssetDecimals\"],\n args=[0],\n ),\n ],\n ),\n config_asset_default_frozen=OpMappingWithOverloads(\n result=pytypes.BoolType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"ConfigAssetDefaultFrozen\"],\n args=[0],\n ),\n ],\n ),\n config_asset_unit_name=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"ConfigAssetUnitName\"],\n args=[0],\n ),\n ],\n ),\n config_asset_name=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"ConfigAssetName\"],\n args=[0],\n ),\n ],\n ),\n config_asset_url=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"ConfigAssetURL\"],\n args=[0],\n ),\n ],\n ),\n config_asset_metadata_hash=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"ConfigAssetMetadataHash\"],\n args=[0],\n ),\n ],\n ),\n config_asset_manager=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"ConfigAssetManager\"],\n args=[0],\n ),\n ],\n ),\n config_asset_reserve=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"ConfigAssetReserve\"],\n args=[0],\n ),\n ],\n ),\n config_asset_freeze=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"ConfigAssetFreeze\"],\n args=[0],\n ),\n ],\n ),\n config_asset_clawback=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"ConfigAssetClawback\"],\n args=[0],\n ),\n ],\n ),\n freeze_asset=OpMappingWithOverloads(\n result=pytypes.AssetType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"FreezeAsset\"],\n args=[0],\n ),\n ],\n ),\n freeze_asset_account=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"FreezeAssetAccount\"],\n args=[0],\n ),\n ],\n ),\n freeze_asset_frozen=OpMappingWithOverloads(\n result=pytypes.BoolType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"FreezeAssetFrozen\"],\n args=[0],\n ),\n ],\n ),\n assets=OpMappingWithOverloads(\n result=pytypes.AssetType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"gitxnas\",\n immediates=[int, \"Assets\"],\n args=[0, (pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gitxna\",\n immediates=[int, \"Assets\", int],\n args=[0, 2],\n ),\n ],\n ),\n num_assets=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"NumAssets\"],\n args=[0],\n ),\n ],\n ),\n applications=OpMappingWithOverloads(\n result=pytypes.ApplicationType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"gitxnas\",\n immediates=[int, \"Applications\"],\n args=[0, (pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gitxna\",\n immediates=[int, \"Applications\", int],\n args=[0, 2],\n ),\n ],\n ),\n num_applications=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"NumApplications\"],\n args=[0],\n ),\n ],\n ),\n global_num_uint=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"GlobalNumUint\"],\n args=[0],\n ),\n ],\n ),\n global_num_byte_slice=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"GlobalNumByteSlice\"],\n args=[0],\n ),\n ],\n ),\n local_num_uint=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"LocalNumUint\"],\n args=[0],\n ),\n ],\n ),\n local_num_byte_slice=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"LocalNumByteSlice\"],\n args=[0],\n ),\n ],\n ),\n extra_program_pages=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"ExtraProgramPages\"],\n args=[0],\n ),\n ],\n ),\n nonparticipation=OpMappingWithOverloads(\n result=pytypes.BoolType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"Nonparticipation\"],\n args=[0],\n ),\n ],\n ),\n logs=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"gitxnas\",\n immediates=[int, \"Logs\"],\n args=[0, (pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gitxna\",\n immediates=[int, \"Logs\", int],\n args=[0, 2],\n ),\n ],\n ),\n num_logs=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"NumLogs\"],\n args=[0],\n ),\n ],\n ),\n created_asset_id=OpMappingWithOverloads(\n result=pytypes.AssetType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"CreatedAssetID\"],\n args=[0],\n ),\n ],\n ),\n created_application_id=OpMappingWithOverloads(\n result=pytypes.ApplicationType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"CreatedApplicationID\"],\n args=[0],\n ),\n ],\n ),\n last_log=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"LastLog\"],\n args=[0],\n ),\n ],\n ),\n state_proof_pk=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"StateProofPK\"],\n args=[0],\n ),\n ],\n ),\n approval_program_pages=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"gitxnas\",\n immediates=[int, \"ApprovalProgramPages\"],\n args=[0, (pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gitxna\",\n immediates=[int, \"ApprovalProgramPages\", int],\n args=[0, 2],\n ),\n ],\n ),\n num_approval_program_pages=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"NumApprovalProgramPages\"],\n args=[0],\n ),\n ],\n ),\n clear_state_program_pages=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"gitxnas\",\n immediates=[int, \"ClearStateProgramPages\"],\n args=[0, (pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gitxna\",\n immediates=[int, \"ClearStateProgramPages\", int],\n args=[0, 2],\n ),\n ],\n ),\n num_clear_state_program_pages=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gitxn\",\n immediates=[int, \"NumClearStateProgramPages\"],\n args=[0],\n ),\n ],\n ),\n ),\n GTxn=dict(\n sender=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"Sender\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"Sender\"],\n args=[0],\n ),\n ],\n ),\n fee=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"Fee\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"Fee\"],\n args=[0],\n ),\n ],\n ),\n first_valid=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"FirstValid\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"FirstValid\"],\n args=[0],\n ),\n ],\n ),\n first_valid_time=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"FirstValidTime\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"FirstValidTime\"],\n args=[0],\n ),\n ],\n ),\n last_valid=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"LastValid\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"LastValid\"],\n args=[0],\n ),\n ],\n ),\n note=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"Note\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"Note\"],\n args=[0],\n ),\n ],\n ),\n lease=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"Lease\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"Lease\"],\n args=[0],\n ),\n ],\n ),\n receiver=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"Receiver\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"Receiver\"],\n args=[0],\n ),\n ],\n ),\n amount=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"Amount\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"Amount\"],\n args=[0],\n ),\n ],\n ),\n close_remainder_to=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"CloseRemainderTo\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"CloseRemainderTo\"],\n args=[0],\n ),\n ],\n ),\n vote_pk=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"VotePK\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"VotePK\"],\n args=[0],\n ),\n ],\n ),\n selection_pk=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"SelectionPK\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"SelectionPK\"],\n args=[0],\n ),\n ],\n ),\n vote_first=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"VoteFirst\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"VoteFirst\"],\n args=[0],\n ),\n ],\n ),\n vote_last=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"VoteLast\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"VoteLast\"],\n args=[0],\n ),\n ],\n ),\n vote_key_dilution=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"VoteKeyDilution\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"VoteKeyDilution\"],\n args=[0],\n ),\n ],\n ),\n type=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"Type\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"Type\"],\n args=[0],\n ),\n ],\n ),\n type_enum=OpMappingWithOverloads(\n result=pytypes.TransactionTypeType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"TypeEnum\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"TypeEnum\"],\n args=[0],\n ),\n ],\n ),\n xfer_asset=OpMappingWithOverloads(\n result=pytypes.AssetType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"XferAsset\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"XferAsset\"],\n args=[0],\n ),\n ],\n ),\n asset_amount=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"AssetAmount\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"AssetAmount\"],\n args=[0],\n ),\n ],\n ),\n asset_sender=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"AssetSender\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"AssetSender\"],\n args=[0],\n ),\n ],\n ),\n asset_receiver=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"AssetReceiver\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"AssetReceiver\"],\n args=[0],\n ),\n ],\n ),\n asset_close_to=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"AssetCloseTo\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"AssetCloseTo\"],\n args=[0],\n ),\n ],\n ),\n group_index=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"GroupIndex\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"GroupIndex\"],\n args=[0],\n ),\n ],\n ),\n tx_id=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"TxID\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"TxID\"],\n args=[0],\n ),\n ],\n ),\n application_id=OpMappingWithOverloads(\n result=pytypes.ApplicationType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"ApplicationID\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"ApplicationID\"],\n args=[0],\n ),\n ],\n ),\n on_completion=OpMappingWithOverloads(\n result=pytypes.OnCompleteActionType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"OnCompletion\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"OnCompletion\"],\n args=[0],\n ),\n ],\n ),\n application_args=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"gtxnsas\",\n immediates=[\"ApplicationArgs\"],\n args=[(pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxnsa\",\n immediates=[\"ApplicationArgs\", int],\n args=[(pytypes.UInt64Type,), 1],\n ),\n FunctionOpMapping(\n \"gtxna\",\n immediates=[int, \"ApplicationArgs\", int],\n args=[0, 2],\n ),\n FunctionOpMapping(\n \"gtxnas\",\n immediates=[int, \"ApplicationArgs\"],\n args=[0, (pytypes.UInt64Type,)],\n ),\n ],\n ),\n num_app_args=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"NumAppArgs\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"NumAppArgs\"],\n args=[0],\n ),\n ],\n ),\n accounts=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"gtxnsas\",\n immediates=[\"Accounts\"],\n args=[(pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxnsa\",\n immediates=[\"Accounts\", int],\n args=[(pytypes.UInt64Type,), 1],\n ),\n FunctionOpMapping(\n \"gtxna\",\n immediates=[int, \"Accounts\", int],\n args=[0, 2],\n ),\n FunctionOpMapping(\n \"gtxnas\",\n immediates=[int, \"Accounts\"],\n args=[0, (pytypes.UInt64Type,)],\n ),\n ],\n ),\n num_accounts=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"NumAccounts\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"NumAccounts\"],\n args=[0],\n ),\n ],\n ),\n approval_program=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"ApprovalProgram\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"ApprovalProgram\"],\n args=[0],\n ),\n ],\n ),\n clear_state_program=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"ClearStateProgram\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"ClearStateProgram\"],\n args=[0],\n ),\n ],\n ),\n rekey_to=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"RekeyTo\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"RekeyTo\"],\n args=[0],\n ),\n ],\n ),\n config_asset=OpMappingWithOverloads(\n result=pytypes.AssetType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"ConfigAsset\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"ConfigAsset\"],\n args=[0],\n ),\n ],\n ),\n config_asset_total=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"ConfigAssetTotal\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"ConfigAssetTotal\"],\n args=[0],\n ),\n ],\n ),\n config_asset_decimals=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"ConfigAssetDecimals\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"ConfigAssetDecimals\"],\n args=[0],\n ),\n ],\n ),\n config_asset_default_frozen=OpMappingWithOverloads(\n result=pytypes.BoolType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"ConfigAssetDefaultFrozen\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"ConfigAssetDefaultFrozen\"],\n args=[0],\n ),\n ],\n ),\n config_asset_unit_name=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"ConfigAssetUnitName\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"ConfigAssetUnitName\"],\n args=[0],\n ),\n ],\n ),\n config_asset_name=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"ConfigAssetName\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"ConfigAssetName\"],\n args=[0],\n ),\n ],\n ),\n config_asset_url=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"ConfigAssetURL\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"ConfigAssetURL\"],\n args=[0],\n ),\n ],\n ),\n config_asset_metadata_hash=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"ConfigAssetMetadataHash\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"ConfigAssetMetadataHash\"],\n args=[0],\n ),\n ],\n ),\n config_asset_manager=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"ConfigAssetManager\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"ConfigAssetManager\"],\n args=[0],\n ),\n ],\n ),\n config_asset_reserve=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"ConfigAssetReserve\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"ConfigAssetReserve\"],\n args=[0],\n ),\n ],\n ),\n config_asset_freeze=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"ConfigAssetFreeze\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"ConfigAssetFreeze\"],\n args=[0],\n ),\n ],\n ),\n config_asset_clawback=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"ConfigAssetClawback\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"ConfigAssetClawback\"],\n args=[0],\n ),\n ],\n ),\n freeze_asset=OpMappingWithOverloads(\n result=pytypes.AssetType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"FreezeAsset\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"FreezeAsset\"],\n args=[0],\n ),\n ],\n ),\n freeze_asset_account=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"FreezeAssetAccount\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"FreezeAssetAccount\"],\n args=[0],\n ),\n ],\n ),\n freeze_asset_frozen=OpMappingWithOverloads(\n result=pytypes.BoolType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"FreezeAssetFrozen\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"FreezeAssetFrozen\"],\n args=[0],\n ),\n ],\n ),\n assets=OpMappingWithOverloads(\n result=pytypes.AssetType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"gtxnsas\",\n immediates=[\"Assets\"],\n args=[(pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxnsa\",\n immediates=[\"Assets\", int],\n args=[(pytypes.UInt64Type,), 1],\n ),\n FunctionOpMapping(\n \"gtxna\",\n immediates=[int, \"Assets\", int],\n args=[0, 2],\n ),\n FunctionOpMapping(\n \"gtxnas\",\n immediates=[int, \"Assets\"],\n args=[0, (pytypes.UInt64Type,)],\n ),\n ],\n ),\n num_assets=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"NumAssets\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"NumAssets\"],\n args=[0],\n ),\n ],\n ),\n applications=OpMappingWithOverloads(\n result=pytypes.ApplicationType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"gtxnsas\",\n immediates=[\"Applications\"],\n args=[(pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxnsa\",\n immediates=[\"Applications\", int],\n args=[(pytypes.UInt64Type,), 1],\n ),\n FunctionOpMapping(\n \"gtxna\",\n immediates=[int, \"Applications\", int],\n args=[0, 2],\n ),\n FunctionOpMapping(\n \"gtxnas\",\n immediates=[int, \"Applications\"],\n args=[0, (pytypes.UInt64Type,)],\n ),\n ],\n ),\n num_applications=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"NumApplications\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"NumApplications\"],\n args=[0],\n ),\n ],\n ),\n global_num_uint=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"GlobalNumUint\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"GlobalNumUint\"],\n args=[0],\n ),\n ],\n ),\n global_num_byte_slice=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"GlobalNumByteSlice\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"GlobalNumByteSlice\"],\n args=[0],\n ),\n ],\n ),\n local_num_uint=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"LocalNumUint\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"LocalNumUint\"],\n args=[0],\n ),\n ],\n ),\n local_num_byte_slice=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"LocalNumByteSlice\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"LocalNumByteSlice\"],\n args=[0],\n ),\n ],\n ),\n extra_program_pages=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"ExtraProgramPages\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"ExtraProgramPages\"],\n args=[0],\n ),\n ],\n ),\n nonparticipation=OpMappingWithOverloads(\n result=pytypes.BoolType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"Nonparticipation\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"Nonparticipation\"],\n args=[0],\n ),\n ],\n ),\n logs=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"gtxnsas\",\n immediates=[\"Logs\"],\n args=[(pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxnsa\",\n immediates=[\"Logs\", int],\n args=[(pytypes.UInt64Type,), 1],\n ),\n FunctionOpMapping(\n \"gtxna\",\n immediates=[int, \"Logs\", int],\n args=[0, 2],\n ),\n FunctionOpMapping(\n \"gtxnas\",\n immediates=[int, \"Logs\"],\n args=[0, (pytypes.UInt64Type,)],\n ),\n ],\n ),\n num_logs=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"NumLogs\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"NumLogs\"],\n args=[0],\n ),\n ],\n ),\n created_asset_id=OpMappingWithOverloads(\n result=pytypes.AssetType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"CreatedAssetID\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"CreatedAssetID\"],\n args=[0],\n ),\n ],\n ),\n created_application_id=OpMappingWithOverloads(\n result=pytypes.ApplicationType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"CreatedApplicationID\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"CreatedApplicationID\"],\n args=[0],\n ),\n ],\n ),\n last_log=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"LastLog\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"LastLog\"],\n args=[0],\n ),\n ],\n ),\n state_proof_pk=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"StateProofPK\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"StateProofPK\"],\n args=[0],\n ),\n ],\n ),\n approval_program_pages=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"gtxnsas\",\n immediates=[\"ApprovalProgramPages\"],\n args=[(pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxnsa\",\n immediates=[\"ApprovalProgramPages\", int],\n args=[(pytypes.UInt64Type,), 1],\n ),\n FunctionOpMapping(\n \"gtxna\",\n immediates=[int, \"ApprovalProgramPages\", int],\n args=[0, 2],\n ),\n FunctionOpMapping(\n \"gtxnas\",\n immediates=[int, \"ApprovalProgramPages\"],\n args=[0, (pytypes.UInt64Type,)],\n ),\n ],\n ),\n num_approval_program_pages=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"NumApprovalProgramPages\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"NumApprovalProgramPages\"],\n args=[0],\n ),\n ],\n ),\n clear_state_program_pages=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"gtxnsas\",\n immediates=[\"ClearStateProgramPages\"],\n args=[(pytypes.UInt64Type,), (pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxnsa\",\n immediates=[\"ClearStateProgramPages\", int],\n args=[(pytypes.UInt64Type,), 1],\n ),\n FunctionOpMapping(\n \"gtxna\",\n immediates=[int, \"ClearStateProgramPages\", int],\n args=[0, 2],\n ),\n FunctionOpMapping(\n \"gtxnas\",\n immediates=[int, \"ClearStateProgramPages\"],\n args=[0, (pytypes.UInt64Type,)],\n ),\n ],\n ),\n num_clear_state_program_pages=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"gtxns\",\n immediates=[\"NumClearStateProgramPages\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"gtxn\",\n immediates=[int, \"NumClearStateProgramPages\"],\n args=[0],\n ),\n ],\n ),\n ),\n Global=dict(\n min_txn_fee=PropertyOpMapping(\n \"global\",\n \"MinTxnFee\",\n pytypes.UInt64Type,\n ),\n min_balance=PropertyOpMapping(\n \"global\",\n \"MinBalance\",\n pytypes.UInt64Type,\n ),\n max_txn_life=PropertyOpMapping(\n \"global\",\n \"MaxTxnLife\",\n pytypes.UInt64Type,\n ),\n zero_address=PropertyOpMapping(\n \"global\",\n \"ZeroAddress\",\n pytypes.AccountType,\n ),\n group_size=PropertyOpMapping(\n \"global\",\n \"GroupSize\",\n pytypes.UInt64Type,\n ),\n logic_sig_version=PropertyOpMapping(\n \"global\",\n \"LogicSigVersion\",\n pytypes.UInt64Type,\n ),\n round=PropertyOpMapping(\n \"global\",\n \"Round\",\n pytypes.UInt64Type,\n ),\n latest_timestamp=PropertyOpMapping(\n \"global\",\n \"LatestTimestamp\",\n pytypes.UInt64Type,\n ),\n current_application_id=PropertyOpMapping(\n \"global\",\n \"CurrentApplicationID\",\n pytypes.ApplicationType,\n ),\n creator_address=PropertyOpMapping(\n \"global\",\n \"CreatorAddress\",\n pytypes.AccountType,\n ),\n current_application_address=PropertyOpMapping(\n \"global\",\n \"CurrentApplicationAddress\",\n pytypes.AccountType,\n ),\n group_id=PropertyOpMapping(\n \"global\",\n \"GroupID\",\n pytypes.BytesType,\n ),\n opcode_budget=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"global\",\n immediates=[\"OpcodeBudget\"],\n ),\n ],\n ),\n caller_application_id=PropertyOpMapping(\n \"global\",\n \"CallerApplicationID\",\n pytypes.UInt64Type,\n ),\n caller_application_address=PropertyOpMapping(\n \"global\",\n \"CallerApplicationAddress\",\n pytypes.AccountType,\n ),\n asset_create_min_balance=PropertyOpMapping(\n \"global\",\n \"AssetCreateMinBalance\",\n pytypes.UInt64Type,\n ),\n asset_opt_in_min_balance=PropertyOpMapping(\n \"global\",\n \"AssetOptInMinBalance\",\n pytypes.UInt64Type,\n ),\n genesis_hash=PropertyOpMapping(\n \"global\",\n \"GenesisHash\",\n pytypes.BytesType,\n ),\n payouts_enabled=PropertyOpMapping(\n \"global\",\n \"PayoutsEnabled\",\n pytypes.BoolType,\n ),\n payouts_go_online_fee=PropertyOpMapping(\n \"global\",\n \"PayoutsGoOnlineFee\",\n pytypes.UInt64Type,\n ),\n payouts_percent=PropertyOpMapping(\n \"global\",\n \"PayoutsPercent\",\n pytypes.UInt64Type,\n ),\n payouts_min_balance=PropertyOpMapping(\n \"global\",\n \"PayoutsMinBalance\",\n pytypes.UInt64Type,\n ),\n payouts_max_balance=PropertyOpMapping(\n \"global\",\n \"PayoutsMaxBalance\",\n pytypes.UInt64Type,\n ),\n ),\n ITxn=dict(\n sender=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"Sender\"],\n ),\n ],\n ),\n fee=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"Fee\"],\n ),\n ],\n ),\n first_valid=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"FirstValid\"],\n ),\n ],\n ),\n first_valid_time=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"FirstValidTime\"],\n ),\n ],\n ),\n last_valid=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"LastValid\"],\n ),\n ],\n ),\n note=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"Note\"],\n ),\n ],\n ),\n lease=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"Lease\"],\n ),\n ],\n ),\n receiver=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"Receiver\"],\n ),\n ],\n ),\n amount=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"Amount\"],\n ),\n ],\n ),\n close_remainder_to=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"CloseRemainderTo\"],\n ),\n ],\n ),\n vote_pk=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"VotePK\"],\n ),\n ],\n ),\n selection_pk=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"SelectionPK\"],\n ),\n ],\n ),\n vote_first=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"VoteFirst\"],\n ),\n ],\n ),\n vote_last=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"VoteLast\"],\n ),\n ],\n ),\n vote_key_dilution=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"VoteKeyDilution\"],\n ),\n ],\n ),\n type=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"Type\"],\n ),\n ],\n ),\n type_enum=OpMappingWithOverloads(\n result=pytypes.TransactionTypeType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"TypeEnum\"],\n ),\n ],\n ),\n xfer_asset=OpMappingWithOverloads(\n result=pytypes.AssetType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"XferAsset\"],\n ),\n ],\n ),\n asset_amount=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"AssetAmount\"],\n ),\n ],\n ),\n asset_sender=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"AssetSender\"],\n ),\n ],\n ),\n asset_receiver=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"AssetReceiver\"],\n ),\n ],\n ),\n asset_close_to=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"AssetCloseTo\"],\n ),\n ],\n ),\n group_index=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"GroupIndex\"],\n ),\n ],\n ),\n tx_id=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"TxID\"],\n ),\n ],\n ),\n application_id=OpMappingWithOverloads(\n result=pytypes.ApplicationType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"ApplicationID\"],\n ),\n ],\n ),\n on_completion=OpMappingWithOverloads(\n result=pytypes.OnCompleteActionType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"OnCompletion\"],\n ),\n ],\n ),\n application_args=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxnas\",\n immediates=[\"ApplicationArgs\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"itxna\",\n immediates=[\"ApplicationArgs\", int],\n args=[1],\n ),\n ],\n ),\n num_app_args=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"NumAppArgs\"],\n ),\n ],\n ),\n accounts=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxnas\",\n immediates=[\"Accounts\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"itxna\",\n immediates=[\"Accounts\", int],\n args=[1],\n ),\n ],\n ),\n num_accounts=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"NumAccounts\"],\n ),\n ],\n ),\n approval_program=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"ApprovalProgram\"],\n ),\n ],\n ),\n clear_state_program=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"ClearStateProgram\"],\n ),\n ],\n ),\n rekey_to=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"RekeyTo\"],\n ),\n ],\n ),\n config_asset=OpMappingWithOverloads(\n result=pytypes.AssetType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"ConfigAsset\"],\n ),\n ],\n ),\n config_asset_total=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"ConfigAssetTotal\"],\n ),\n ],\n ),\n config_asset_decimals=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"ConfigAssetDecimals\"],\n ),\n ],\n ),\n config_asset_default_frozen=OpMappingWithOverloads(\n result=pytypes.BoolType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"ConfigAssetDefaultFrozen\"],\n ),\n ],\n ),\n config_asset_unit_name=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"ConfigAssetUnitName\"],\n ),\n ],\n ),\n config_asset_name=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"ConfigAssetName\"],\n ),\n ],\n ),\n config_asset_url=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"ConfigAssetURL\"],\n ),\n ],\n ),\n config_asset_metadata_hash=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"ConfigAssetMetadataHash\"],\n ),\n ],\n ),\n config_asset_manager=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"ConfigAssetManager\"],\n ),\n ],\n ),\n config_asset_reserve=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"ConfigAssetReserve\"],\n ),\n ],\n ),\n config_asset_freeze=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"ConfigAssetFreeze\"],\n ),\n ],\n ),\n config_asset_clawback=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"ConfigAssetClawback\"],\n ),\n ],\n ),\n freeze_asset=OpMappingWithOverloads(\n result=pytypes.AssetType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"FreezeAsset\"],\n ),\n ],\n ),\n freeze_asset_account=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"FreezeAssetAccount\"],\n ),\n ],\n ),\n freeze_asset_frozen=OpMappingWithOverloads(\n result=pytypes.BoolType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"FreezeAssetFrozen\"],\n ),\n ],\n ),\n assets=OpMappingWithOverloads(\n result=pytypes.AssetType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxnas\",\n immediates=[\"Assets\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"itxna\",\n immediates=[\"Assets\", int],\n args=[1],\n ),\n ],\n ),\n num_assets=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"NumAssets\"],\n ),\n ],\n ),\n applications=OpMappingWithOverloads(\n result=pytypes.ApplicationType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxnas\",\n immediates=[\"Applications\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"itxna\",\n immediates=[\"Applications\", int],\n args=[1],\n ),\n ],\n ),\n num_applications=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"NumApplications\"],\n ),\n ],\n ),\n global_num_uint=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"GlobalNumUint\"],\n ),\n ],\n ),\n global_num_byte_slice=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"GlobalNumByteSlice\"],\n ),\n ],\n ),\n local_num_uint=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"LocalNumUint\"],\n ),\n ],\n ),\n local_num_byte_slice=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"LocalNumByteSlice\"],\n ),\n ],\n ),\n extra_program_pages=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"ExtraProgramPages\"],\n ),\n ],\n ),\n nonparticipation=OpMappingWithOverloads(\n result=pytypes.BoolType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"Nonparticipation\"],\n ),\n ],\n ),\n logs=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxnas\",\n immediates=[\"Logs\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"itxna\",\n immediates=[\"Logs\", int],\n args=[1],\n ),\n ],\n ),\n num_logs=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"NumLogs\"],\n ),\n ],\n ),\n created_asset_id=OpMappingWithOverloads(\n result=pytypes.AssetType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"CreatedAssetID\"],\n ),\n ],\n ),\n created_application_id=OpMappingWithOverloads(\n result=pytypes.ApplicationType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"CreatedApplicationID\"],\n ),\n ],\n ),\n last_log=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"LastLog\"],\n ),\n ],\n ),\n state_proof_pk=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"StateProofPK\"],\n ),\n ],\n ),\n approval_program_pages=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxnas\",\n immediates=[\"ApprovalProgramPages\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"itxna\",\n immediates=[\"ApprovalProgramPages\", int],\n args=[1],\n ),\n ],\n ),\n num_approval_program_pages=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"NumApprovalProgramPages\"],\n ),\n ],\n ),\n clear_state_program_pages=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxnas\",\n immediates=[\"ClearStateProgramPages\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"itxna\",\n immediates=[\"ClearStateProgramPages\", int],\n args=[1],\n ),\n ],\n ),\n num_clear_state_program_pages=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn\",\n immediates=[\"NumClearStateProgramPages\"],\n ),\n ],\n ),\n ),\n ITxnCreate=dict(\n begin=OpMappingWithOverloads(\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn_begin\",\n ),\n ],\n ),\n next=OpMappingWithOverloads(\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn_next\",\n ),\n ],\n ),\n submit=OpMappingWithOverloads(\n arity=0,\n overloads=[\n FunctionOpMapping(\n \"itxn_submit\",\n ),\n ],\n ),\n set_sender=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"Sender\"],\n args=[(pytypes.AccountType,)],\n ),\n ],\n ),\n set_fee=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"Fee\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n set_note=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"Note\"],\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n set_receiver=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"Receiver\"],\n args=[(pytypes.AccountType,)],\n ),\n ],\n ),\n set_amount=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"Amount\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n set_close_remainder_to=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"CloseRemainderTo\"],\n args=[(pytypes.AccountType,)],\n ),\n ],\n ),\n set_vote_pk=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"VotePK\"],\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n set_selection_pk=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"SelectionPK\"],\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n set_vote_first=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"VoteFirst\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n set_vote_last=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"VoteLast\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n set_vote_key_dilution=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"VoteKeyDilution\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n set_type=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"Type\"],\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n set_type_enum=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"TypeEnum\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n set_xfer_asset=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"XferAsset\"],\n args=[(pytypes.AssetType, pytypes.UInt64Type)],\n ),\n ],\n ),\n set_asset_amount=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"AssetAmount\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n set_asset_sender=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"AssetSender\"],\n args=[(pytypes.AccountType,)],\n ),\n ],\n ),\n set_asset_receiver=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"AssetReceiver\"],\n args=[(pytypes.AccountType,)],\n ),\n ],\n ),\n set_asset_close_to=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"AssetCloseTo\"],\n args=[(pytypes.AccountType,)],\n ),\n ],\n ),\n set_application_id=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"ApplicationID\"],\n args=[(pytypes.ApplicationType, pytypes.UInt64Type)],\n ),\n ],\n ),\n set_on_completion=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"OnCompletion\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n set_application_args=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"ApplicationArgs\"],\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n set_accounts=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"Accounts\"],\n args=[(pytypes.AccountType,)],\n ),\n ],\n ),\n set_approval_program=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"ApprovalProgram\"],\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n set_clear_state_program=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"ClearStateProgram\"],\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n set_rekey_to=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"RekeyTo\"],\n args=[(pytypes.AccountType,)],\n ),\n ],\n ),\n set_config_asset=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"ConfigAsset\"],\n args=[(pytypes.AssetType, pytypes.UInt64Type)],\n ),\n ],\n ),\n set_config_asset_total=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"ConfigAssetTotal\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n set_config_asset_decimals=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"ConfigAssetDecimals\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n set_config_asset_default_frozen=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"ConfigAssetDefaultFrozen\"],\n args=[(pytypes.BoolType, pytypes.UInt64Type)],\n ),\n ],\n ),\n set_config_asset_unit_name=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"ConfigAssetUnitName\"],\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n set_config_asset_name=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"ConfigAssetName\"],\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n set_config_asset_url=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"ConfigAssetURL\"],\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n set_config_asset_metadata_hash=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"ConfigAssetMetadataHash\"],\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n set_config_asset_manager=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"ConfigAssetManager\"],\n args=[(pytypes.AccountType,)],\n ),\n ],\n ),\n set_config_asset_reserve=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"ConfigAssetReserve\"],\n args=[(pytypes.AccountType,)],\n ),\n ],\n ),\n set_config_asset_freeze=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"ConfigAssetFreeze\"],\n args=[(pytypes.AccountType,)],\n ),\n ],\n ),\n set_config_asset_clawback=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"ConfigAssetClawback\"],\n args=[(pytypes.AccountType,)],\n ),\n ],\n ),\n set_freeze_asset=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"FreezeAsset\"],\n args=[(pytypes.AssetType, pytypes.UInt64Type)],\n ),\n ],\n ),\n set_freeze_asset_account=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"FreezeAssetAccount\"],\n args=[(pytypes.AccountType,)],\n ),\n ],\n ),\n set_freeze_asset_frozen=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"FreezeAssetFrozen\"],\n args=[(pytypes.BoolType, pytypes.UInt64Type)],\n ),\n ],\n ),\n set_assets=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"Assets\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n set_applications=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"Applications\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n set_global_num_uint=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"GlobalNumUint\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n set_global_num_byte_slice=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"GlobalNumByteSlice\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n set_local_num_uint=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"LocalNumUint\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n set_local_num_byte_slice=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"LocalNumByteSlice\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n set_extra_program_pages=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"ExtraProgramPages\"],\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n set_nonparticipation=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"Nonparticipation\"],\n args=[(pytypes.BoolType, pytypes.UInt64Type)],\n ),\n ],\n ),\n set_state_proof_pk=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"StateProofPK\"],\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n set_approval_program_pages=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"ApprovalProgramPages\"],\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n set_clear_state_program_pages=OpMappingWithOverloads(\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"itxn_field\",\n immediates=[\"ClearStateProgramPages\"],\n args=[(pytypes.BytesType,)],\n ),\n ],\n ),\n ),\n JsonRef=dict(\n json_string=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"json_ref\",\n immediates=[\"JSONString\"],\n args=[(pytypes.BytesType,), (pytypes.BytesType,)],\n ),\n ],\n ),\n json_uint64=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"json_ref\",\n immediates=[\"JSONUint64\"],\n args=[(pytypes.BytesType,), (pytypes.BytesType,)],\n ),\n ],\n ),\n json_object=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"json_ref\",\n immediates=[\"JSONObject\"],\n args=[(pytypes.BytesType,), (pytypes.BytesType,)],\n ),\n ],\n ),\n ),\n Scratch=dict(\n load_bytes=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"loads\",\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n load_uint64=OpMappingWithOverloads(\n result=pytypes.UInt64Type,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"loads\",\n args=[(pytypes.UInt64Type,)],\n ),\n ],\n ),\n store=OpMappingWithOverloads(\n arity=2,\n overloads=[\n FunctionOpMapping(\n \"stores\",\n args=[(pytypes.UInt64Type,), (pytypes.BytesType, pytypes.UInt64Type)],\n ),\n ],\n ),\n ),\n Txn=dict(\n sender=PropertyOpMapping(\n \"txn\",\n \"Sender\",\n pytypes.AccountType,\n ),\n fee=PropertyOpMapping(\n \"txn\",\n \"Fee\",\n pytypes.UInt64Type,\n ),\n first_valid=PropertyOpMapping(\n \"txn\",\n \"FirstValid\",\n pytypes.UInt64Type,\n ),\n first_valid_time=PropertyOpMapping(\n \"txn\",\n \"FirstValidTime\",\n pytypes.UInt64Type,\n ),\n last_valid=PropertyOpMapping(\n \"txn\",\n \"LastValid\",\n pytypes.UInt64Type,\n ),\n note=PropertyOpMapping(\n \"txn\",\n \"Note\",\n pytypes.BytesType,\n ),\n lease=PropertyOpMapping(\n \"txn\",\n \"Lease\",\n pytypes.BytesType,\n ),\n receiver=PropertyOpMapping(\n \"txn\",\n \"Receiver\",\n pytypes.AccountType,\n ),\n amount=PropertyOpMapping(\n \"txn\",\n \"Amount\",\n pytypes.UInt64Type,\n ),\n close_remainder_to=PropertyOpMapping(\n \"txn\",\n \"CloseRemainderTo\",\n pytypes.AccountType,\n ),\n vote_pk=PropertyOpMapping(\n \"txn\",\n \"VotePK\",\n pytypes.BytesType,\n ),\n selection_pk=PropertyOpMapping(\n \"txn\",\n \"SelectionPK\",\n pytypes.BytesType,\n ),\n vote_first=PropertyOpMapping(\n \"txn\",\n \"VoteFirst\",\n pytypes.UInt64Type,\n ),\n vote_last=PropertyOpMapping(\n \"txn\",\n \"VoteLast\",\n pytypes.UInt64Type,\n ),\n vote_key_dilution=PropertyOpMapping(\n \"txn\",\n \"VoteKeyDilution\",\n pytypes.UInt64Type,\n ),\n type=PropertyOpMapping(\n \"txn\",\n \"Type\",\n pytypes.BytesType,\n ),\n type_enum=PropertyOpMapping(\n \"txn\",\n \"TypeEnum\",\n pytypes.TransactionTypeType,\n ),\n xfer_asset=PropertyOpMapping(\n \"txn\",\n \"XferAsset\",\n pytypes.AssetType,\n ),\n asset_amount=PropertyOpMapping(\n \"txn\",\n \"AssetAmount\",\n pytypes.UInt64Type,\n ),\n asset_sender=PropertyOpMapping(\n \"txn\",\n \"AssetSender\",\n pytypes.AccountType,\n ),\n asset_receiver=PropertyOpMapping(\n \"txn\",\n \"AssetReceiver\",\n pytypes.AccountType,\n ),\n asset_close_to=PropertyOpMapping(\n \"txn\",\n \"AssetCloseTo\",\n pytypes.AccountType,\n ),\n group_index=PropertyOpMapping(\n \"txn\",\n \"GroupIndex\",\n pytypes.UInt64Type,\n ),\n tx_id=PropertyOpMapping(\n \"txn\",\n \"TxID\",\n pytypes.BytesType,\n ),\n application_id=PropertyOpMapping(\n \"txn\",\n \"ApplicationID\",\n pytypes.ApplicationType,\n ),\n on_completion=PropertyOpMapping(\n \"txn\",\n \"OnCompletion\",\n pytypes.OnCompleteActionType,\n ),\n application_args=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"txnas\",\n immediates=[\"ApplicationArgs\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"txna\",\n immediates=[\"ApplicationArgs\", int],\n args=[1],\n ),\n ],\n ),\n num_app_args=PropertyOpMapping(\n \"txn\",\n \"NumAppArgs\",\n pytypes.UInt64Type,\n ),\n accounts=OpMappingWithOverloads(\n result=pytypes.AccountType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"txnas\",\n immediates=[\"Accounts\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"txna\",\n immediates=[\"Accounts\", int],\n args=[1],\n ),\n ],\n ),\n num_accounts=PropertyOpMapping(\n \"txn\",\n \"NumAccounts\",\n pytypes.UInt64Type,\n ),\n approval_program=PropertyOpMapping(\n \"txn\",\n \"ApprovalProgram\",\n pytypes.BytesType,\n ),\n clear_state_program=PropertyOpMapping(\n \"txn\",\n \"ClearStateProgram\",\n pytypes.BytesType,\n ),\n rekey_to=PropertyOpMapping(\n \"txn\",\n \"RekeyTo\",\n pytypes.AccountType,\n ),\n config_asset=PropertyOpMapping(\n \"txn\",\n \"ConfigAsset\",\n pytypes.AssetType,\n ),\n config_asset_total=PropertyOpMapping(\n \"txn\",\n \"ConfigAssetTotal\",\n pytypes.UInt64Type,\n ),\n config_asset_decimals=PropertyOpMapping(\n \"txn\",\n \"ConfigAssetDecimals\",\n pytypes.UInt64Type,\n ),\n config_asset_default_frozen=PropertyOpMapping(\n \"txn\",\n \"ConfigAssetDefaultFrozen\",\n pytypes.BoolType,\n ),\n config_asset_unit_name=PropertyOpMapping(\n \"txn\",\n \"ConfigAssetUnitName\",\n pytypes.BytesType,\n ),\n config_asset_name=PropertyOpMapping(\n \"txn\",\n \"ConfigAssetName\",\n pytypes.BytesType,\n ),\n config_asset_url=PropertyOpMapping(\n \"txn\",\n \"ConfigAssetURL\",\n pytypes.BytesType,\n ),\n config_asset_metadata_hash=PropertyOpMapping(\n \"txn\",\n \"ConfigAssetMetadataHash\",\n pytypes.BytesType,\n ),\n config_asset_manager=PropertyOpMapping(\n \"txn\",\n \"ConfigAssetManager\",\n pytypes.AccountType,\n ),\n config_asset_reserve=PropertyOpMapping(\n \"txn\",\n \"ConfigAssetReserve\",\n pytypes.AccountType,\n ),\n config_asset_freeze=PropertyOpMapping(\n \"txn\",\n \"ConfigAssetFreeze\",\n pytypes.AccountType,\n ),\n config_asset_clawback=PropertyOpMapping(\n \"txn\",\n \"ConfigAssetClawback\",\n pytypes.AccountType,\n ),\n freeze_asset=PropertyOpMapping(\n \"txn\",\n \"FreezeAsset\",\n pytypes.AssetType,\n ),\n freeze_asset_account=PropertyOpMapping(\n \"txn\",\n \"FreezeAssetAccount\",\n pytypes.AccountType,\n ),\n freeze_asset_frozen=PropertyOpMapping(\n \"txn\",\n \"FreezeAssetFrozen\",\n pytypes.BoolType,\n ),\n assets=OpMappingWithOverloads(\n result=pytypes.AssetType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"txnas\",\n immediates=[\"Assets\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"txna\",\n immediates=[\"Assets\", int],\n args=[1],\n ),\n ],\n ),\n num_assets=PropertyOpMapping(\n \"txn\",\n \"NumAssets\",\n pytypes.UInt64Type,\n ),\n applications=OpMappingWithOverloads(\n result=pytypes.ApplicationType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"txnas\",\n immediates=[\"Applications\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"txna\",\n immediates=[\"Applications\", int],\n args=[1],\n ),\n ],\n ),\n num_applications=PropertyOpMapping(\n \"txn\",\n \"NumApplications\",\n pytypes.UInt64Type,\n ),\n global_num_uint=PropertyOpMapping(\n \"txn\",\n \"GlobalNumUint\",\n pytypes.UInt64Type,\n ),\n global_num_byte_slice=PropertyOpMapping(\n \"txn\",\n \"GlobalNumByteSlice\",\n pytypes.UInt64Type,\n ),\n local_num_uint=PropertyOpMapping(\n \"txn\",\n \"LocalNumUint\",\n pytypes.UInt64Type,\n ),\n local_num_byte_slice=PropertyOpMapping(\n \"txn\",\n \"LocalNumByteSlice\",\n pytypes.UInt64Type,\n ),\n extra_program_pages=PropertyOpMapping(\n \"txn\",\n \"ExtraProgramPages\",\n pytypes.UInt64Type,\n ),\n nonparticipation=PropertyOpMapping(\n \"txn\",\n \"Nonparticipation\",\n pytypes.BoolType,\n ),\n logs=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"txnas\",\n immediates=[\"Logs\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"txna\",\n immediates=[\"Logs\", int],\n args=[1],\n ),\n ],\n ),\n num_logs=PropertyOpMapping(\n \"txn\",\n \"NumLogs\",\n pytypes.UInt64Type,\n ),\n created_asset_id=PropertyOpMapping(\n \"txn\",\n \"CreatedAssetID\",\n pytypes.AssetType,\n ),\n created_application_id=PropertyOpMapping(\n \"txn\",\n \"CreatedApplicationID\",\n pytypes.ApplicationType,\n ),\n last_log=PropertyOpMapping(\n \"txn\",\n \"LastLog\",\n pytypes.BytesType,\n ),\n state_proof_pk=PropertyOpMapping(\n \"txn\",\n \"StateProofPK\",\n pytypes.BytesType,\n ),\n approval_program_pages=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"txnas\",\n immediates=[\"ApprovalProgramPages\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"txna\",\n immediates=[\"ApprovalProgramPages\", int],\n args=[1],\n ),\n ],\n ),\n num_approval_program_pages=PropertyOpMapping(\n \"txn\",\n \"NumApprovalProgramPages\",\n pytypes.UInt64Type,\n ),\n clear_state_program_pages=OpMappingWithOverloads(\n result=pytypes.BytesType,\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"txnas\",\n immediates=[\"ClearStateProgramPages\"],\n args=[(pytypes.UInt64Type,)],\n ),\n FunctionOpMapping(\n \"txna\",\n immediates=[\"ClearStateProgramPages\", int],\n args=[1],\n ),\n ],\n ),\n num_clear_state_program_pages=PropertyOpMapping(\n \"txn\",\n \"NumClearStateProgramPages\",\n pytypes.UInt64Type,\n ),\n ),\n VoterParamsGet=dict(\n voter_balance=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.UInt64Type, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"voter_params_get\",\n immediates=[\"VoterBalance\"],\n args=[(pytypes.AccountType, pytypes.UInt64Type)],\n ),\n ],\n ),\n voter_incentive_eligible=OpMappingWithOverloads(\n result=pytypes.GenericTupleType.parameterise(\n (pytypes.BoolType, pytypes.BoolType), source_location=None\n ),\n arity=1,\n overloads=[\n FunctionOpMapping(\n \"voter_params_get\",\n immediates=[\"VoterIncentiveEligible\"],\n args=[(pytypes.AccountType, pytypes.UInt64Type)],\n ),\n ],\n ),\n ),\n)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/intrinsic_data.py","language":"Python","license":"NOASSERTION","size":166831} {"code":"from puya.awst import wtypes\nfrom puya.awst.nodes import Expression, IntrinsicCall\nfrom puya.errors import InternalError\nfrom puya.parse import SourceLocation\n\n\ndef bytes_len(expr: Expression, loc: SourceLocation | None = None) -> IntrinsicCall:\n loc = loc or expr.source_location\n return IntrinsicCall(\n op_code=\"len\",\n stack_args=[expr],\n wtype=wtypes.uint64_wtype,\n source_location=loc,\n )\n\n\ndef concat(\n a: Expression,\n b: Expression,\n loc: SourceLocation,\n result_type: wtypes.WType = wtypes.bytes_wtype,\n) -> IntrinsicCall:\n return IntrinsicCall(\n op_code=\"concat\",\n stack_args=[a, b],\n wtype=result_type,\n source_location=loc,\n )\n\n\ndef itob(expr: Expression, loc: SourceLocation | None = None) -> IntrinsicCall:\n return itob_as(expr, wtypes.bytes_wtype, loc)\n\n\ndef itob_as(\n expr: Expression, wtype: wtypes.WType, loc: SourceLocation | None = None\n) -> IntrinsicCall:\n return IntrinsicCall(\n op_code=\"itob\",\n stack_args=[expr],\n wtype=wtype,\n source_location=loc or expr.source_location,\n )\n\n\ndef txn(immediate: str, wtype: wtypes.WType, location: SourceLocation) -> IntrinsicCall:\n return IntrinsicCall(\n op_code=\"txn\",\n immediates=[immediate],\n wtype=wtype,\n source_location=location,\n )\n\n\ndef log(to_log: Expression, loc: SourceLocation) -> IntrinsicCall:\n return IntrinsicCall(\n op_code=\"log\",\n stack_args=[to_log],\n wtype=wtypes.void_wtype,\n source_location=loc,\n )\n\n\ndef select(\n *, condition: Expression, false: Expression, true: Expression, loc: SourceLocation\n) -> IntrinsicCall:\n if false.wtype != true.wtype:\n raise InternalError(f\"false WType ({false}) does not match true WType ({true})\", loc)\n return IntrinsicCall(\n op_code=\"select\",\n stack_args=[\n false,\n true,\n condition,\n ],\n wtype=false.wtype,\n source_location=loc,\n )\n\n\ndef extract(\n value: Expression,\n start: int,\n length: int = 0,\n loc: SourceLocation | None = None,\n result_type: wtypes.WType = wtypes.bytes_wtype,\n) -> IntrinsicCall:\n return IntrinsicCall(\n op_code=\"extract\",\n immediates=[start, length],\n wtype=result_type,\n stack_args=[value],\n source_location=loc or value.source_location,\n )\n\n\ndef extract3(\n value: Expression,\n start: Expression,\n length: Expression,\n loc: SourceLocation | None = None,\n result_type: wtypes.WType = wtypes.bytes_wtype,\n) -> IntrinsicCall:\n return IntrinsicCall(\n op_code=\"extract3\",\n wtype=result_type,\n stack_args=[value, start, length],\n source_location=loc or value.source_location,\n )\n\n\ndef zero_address(\n loc: SourceLocation, *, as_type: wtypes.WType = wtypes.account_wtype\n) -> IntrinsicCall:\n return IntrinsicCall(\n wtype=as_type,\n op_code=\"global\",\n immediates=[\"ZeroAddress\"],\n source_location=loc,\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/intrinsic_factory.py","language":"Python","license":"NOASSERTION","size":3054} {"code":"\"\"\"\nUsed to map algopy\/_gen.pyi stubs to AWST.\nReferenced by both scripts\/generate_stubs.py and src\/puya\/awst_build\/eb\/intrinsics.py\n\"\"\"\n\nfrom collections.abc import Sequence, Set\nfrom functools import cached_property\n\nimport attrs\n\nfrom puya.awst import wtypes\nfrom puya.errors import InternalError\nfrom puyapy.awst_build import pytypes\n\n\n@attrs.frozen\nclass PropertyOpMapping:\n op_code: str\n immediate: str\n typ: pytypes.PyType = attrs.field(\n validator=attrs.validators.not_(attrs.validators.in_([pytypes.NoneType]))\n )\n wtype: wtypes.WType = attrs.field(init=False)\n\n @wtype.default\n def _wtype(self) -> wtypes.WType:\n return self.typ.checked_wtype(location=None)\n\n\n@attrs.frozen\nclass FunctionOpMapping:\n op_code: str\n immediates: Sequence[str | int | type[str | int]] = attrs.field(\n default=(), converter=tuple[str | int | type[str | int], ...]\n )\n \"\"\"A list of immediate literals, or expected type\"\"\"\n args: Sequence[Sequence[pytypes.PyType] | int] = attrs.field(\n default=(), converter=tuple[Sequence[pytypes.PyType] | int, ...]\n )\n \"\"\"A list of allowed argument types, or an index into the immediates sequence\"\"\"\n\n @cached_property\n def literal_arg_positions(self) -> Set[int]:\n return {idx for idx, arg in enumerate(self.args) if isinstance(arg, int)}\n\n def __attrs_post_init__(self) -> None:\n for idx, imm in enumerate(self.immediates):\n if isinstance(imm, type) and idx not in self.args:\n raise InternalError(\"expected immediate type to be reference by arg index\")\n\n for idx, arg in enumerate(self.args):\n if isinstance(arg, int):\n try:\n immediate = self.immediates[arg]\n except IndexError:\n raise InternalError(\n f\"intrinsic {self.op_code!r} argument {idx}: immediates index out of range\"\n ) from None\n if immediate not in (str, int):\n raise InternalError(\n f\"intrinsic {self.op_code!r} argument {idx}:\"\n \" immediate index does not point to a type\"\n )\n else:\n if not arg:\n raise InternalError(\n f\"intrinsic {self.op_code!r} argument {idx}: no stack input types provided\"\n )\n if (pytypes.BigUIntType.is_type_or_supertype(*arg)) and (\n pytypes.UInt64Type.is_type_or_supertype(*arg)\n ):\n raise InternalError(\n f\"intrinsic {self.op_code!r} argument {idx}: overlap in integer types\"\n )\n\n\n@attrs.frozen(kw_only=True)\nclass OpMappingWithOverloads:\n arity: int = attrs.field(validator=attrs.validators.ge(0))\n result: pytypes.PyType = pytypes.NoneType\n \"\"\"Types output by TEAL op\"\"\"\n result_wtype: wtypes.WType = attrs.field(init=False)\n overloads: Sequence[FunctionOpMapping] = attrs.field(\n validator=attrs.validators.min_len(1), converter=tuple[FunctionOpMapping, ...]\n )\n\n @result_wtype.default\n def _result_wtype(self) -> wtypes.WType:\n return self.result.checked_wtype(location=None)\n\n @arity.validator\n def _arity_matches(self, _attribute: object, arity: int) -> None:\n if any(len(o.args) != arity for o in self.overloads):\n raise InternalError(\"arity does not match all overloads\")\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/intrinsic_models.py","language":"Python","license":"NOASSERTION","size":3501} {"code":"from collections.abc import Sequence\n\nfrom puya import log\nfrom puya.awst.nodes import Contract, LogicSignature, RootNode\nfrom puya.program_refs import ContractReference, LogicSigReference\nfrom puya.utils import make_path_relative_to_cwd\nfrom puyapy.awst_build.context import ASTConversionContext\nfrom puyapy.awst_build.module import ModuleASTConverter\nfrom puyapy.parse import TYPESHED_PATH, ParseResult, SourceDiscoveryMechanism\n\nlogger = log.get_logger(__name__)\n\n\ndef transform_ast(\n parse_result: ParseResult,\n) -> tuple[Sequence[RootNode], Sequence[ContractReference | LogicSigReference]]:\n ctx = ASTConversionContext(parse_result=parse_result)\n user_modules = []\n\n for module_name, src in parse_result.ordered_modules.items():\n module_rel_path = make_path_relative_to_cwd(src.path)\n if src.node.is_stub:\n if module_name in (\"abc\", \"typing\", \"collections.abc\"):\n logger.debug(f\"Skipping stdlib stub {module_rel_path}\") # TODO: lowercase\n elif module_name.startswith(\"algopy\"):\n logger.debug(f\"Skipping algopy stub {module_rel_path}\")\n elif src.path.is_relative_to(TYPESHED_PATH):\n logger.debug(f\"Skipping typeshed stub {module_rel_path}\")\n else:\n logger.warning(f\"Skipping stub: {module_rel_path}\")\n else:\n logger.debug(f\"Discovered user module {module_name} at {module_rel_path}\")\n module_ctx = ctx.for_module(src.path)\n user_modules.append((src, ModuleASTConverter(module_ctx, src.node)))\n\n compilation_set = list[ContractReference | LogicSigReference]()\n awst = list[RootNode]()\n for src, converter in user_modules:\n logger.debug(f\"Building AWST for module {src.name}\")\n root_nodes = converter.convert()\n awst.extend(root_nodes)\n if src.discovery_mechanism != SourceDiscoveryMechanism.dependency:\n for root_node in root_nodes:\n if isinstance(root_node, Contract | LogicSignature):\n compilation_set.append(root_node.id)\n return awst, compilation_set\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/main.py","language":"Python","license":"NOASSERTION","size":2114} {"code":"import typing\nfrom collections.abc import Callable\n\nimport attrs\nimport mypy.nodes\nimport mypy.types\nimport mypy.visitor\n\nfrom puya import log\nfrom puya.algo_constants import MAX_SCRATCH_SLOT_NUMBER\nfrom puya.awst.nodes import AWST, LogicSignature, RootNode, StateTotals\nfrom puya.errors import CodeError, InternalError\nfrom puya.program_refs import LogicSigReference\nfrom puya.utils import coalesce\nfrom puyapy.awst_build import constants, pytypes\nfrom puyapy.awst_build.arc4_client import ARC4ClientASTVisitor\nfrom puyapy.awst_build.base_mypy_visitor import (\n BaseMyPyExpressionVisitor,\n BaseMyPyStatementVisitor,\n)\nfrom puyapy.awst_build.context import ASTConversionModuleContext\nfrom puyapy.awst_build.contract import ContractASTConverter\nfrom puyapy.awst_build.exceptions import UnsupportedASTError\nfrom puyapy.awst_build.subroutine import FunctionASTConverter\nfrom puyapy.awst_build.utils import (\n extract_bytes_literal_from_mypy,\n fold_binary_expr,\n fold_unary_expr,\n get_decorators_by_fullname,\n get_subroutine_decorator_inline_arg,\n get_unaliased_fullname,\n)\nfrom puyapy.models import ConstantValue, ContractClassOptions\n\nlogger = log.get_logger(__name__)\n\n\nDeferredRootNode: typing.TypeAlias = Callable[[ASTConversionModuleContext], RootNode | None]\n\nStatementResult: typing.TypeAlias = list[DeferredRootNode]\n\n\n@attrs.frozen(kw_only=True)\nclass _LogicSigDecoratorInfo:\n name_override: str | None\n avm_version: int | None\n\n\n_BUILTIN_INHERITABLE: typing.Final = frozenset(\n (\"builtins.object\", \"abc.ABC\", *mypy.types.PROTOCOL_NAMES)\n)\n\n\nclass ModuleASTConverter(\n BaseMyPyStatementVisitor[StatementResult], BaseMyPyExpressionVisitor[ConstantValue]\n):\n \"\"\"This does basic validation, and traversal of valid module scope elements, collecting\n and folding constants.\"\"\"\n\n def __init__(self, context: ASTConversionModuleContext, module: mypy.nodes.MypyFile):\n super().__init__(context)\n self.module_name: typing.Final = module.fullname\n self._pre_parse_result = list[tuple[mypy.nodes.Context, StatementResult]]()\n for node in module.defs:\n with self.context.log_exceptions(fallback_location=node):\n items = node.accept(self)\n self._pre_parse_result.append((node, items))\n\n def convert(self) -> AWST:\n awst = []\n for location, deferrals in self._pre_parse_result:\n with self.context.log_exceptions(fallback_location=location):\n for deferred in deferrals:\n awst_node = deferred(self.context)\n if awst_node is not None:\n awst.append(awst_node)\n return awst\n\n # Supported Statements\n\n def empty_statement(self, _stmt: mypy.nodes.Statement) -> StatementResult:\n return []\n\n def visit_function(\n self, func_def: mypy.nodes.FuncDef, decorator: mypy.nodes.Decorator | None\n ) -> StatementResult:\n self._precondition(\n func_def.abstract_status == mypy.nodes.NOT_ABSTRACT,\n \"module level functions should not be classified as abstract by mypy\",\n decorator or func_def,\n )\n dec_by_fullname = get_decorators_by_fullname(self.context, decorator) if decorator else {}\n source_location = self._location(decorator or func_def)\n logicsig_dec = dec_by_fullname.pop(constants.LOGICSIG_DECORATOR, None)\n if logicsig_dec:\n for dec_fullname, dec in dec_by_fullname.items():\n self._error(f'Unsupported logicsig decorator \"{dec_fullname}\"', dec)\n info = self._process_logic_sig_decorator(logicsig_dec)\n\n def deferred(ctx: ASTConversionModuleContext) -> RootNode:\n program = FunctionASTConverter.convert(\n ctx, func_def, source_location, inline=False\n )\n ctx.register_pytype(pytypes.LogicSigType, alias=func_def.fullname)\n return LogicSignature(\n id=LogicSigReference(func_def.fullname),\n program=program,\n short_name=coalesce(info.name_override, program.name),\n docstring=func_def.docstring,\n source_location=self._location(logicsig_dec),\n avm_version=info.avm_version,\n )\n\n return [deferred]\n subroutine_dec = dec_by_fullname.pop(constants.SUBROUTINE_HINT, None)\n if subroutine_dec is None:\n self._error(\n f\"free functions must be annotated with @{constants.SUBROUTINE_HINT_ALIAS}\",\n func_def,\n )\n inline = None\n else:\n inline = get_subroutine_decorator_inline_arg(self.context, subroutine_dec)\n abimethod_dec = dec_by_fullname.pop(constants.ABIMETHOD_DECORATOR, None)\n if abimethod_dec is not None:\n self._error(\"free functions cannot be ARC4 ABI methods\", abimethod_dec)\n # any further decorators are unsupported\n for dec_fullname, dec in dec_by_fullname.items():\n self._error(f'unsupported function decorator \"{dec_fullname}\"', dec)\n\n return [\n lambda ctx: FunctionASTConverter.convert(ctx, func_def, source_location, inline=inline)\n ]\n\n def _process_logic_sig_decorator(\n self, decorator: mypy.nodes.Expression\n ) -> _LogicSigDecoratorInfo:\n name_override = None\n avm_version = None\n match decorator:\n case mypy.nodes.NameExpr():\n pass\n case mypy.nodes.CallExpr(arg_names=arg_names, args=args):\n for arg_name, arg in zip(arg_names, args, strict=True):\n match arg_name:\n case \"name\":\n name_const = arg.accept(self)\n if isinstance(name_const, str):\n name_override = name_const\n else:\n self.context.error(\"expected a str\", arg)\n case \"avm_version\":\n version_const = arg.accept(self)\n if isinstance(version_const, int):\n avm_version = version_const\n else:\n self.context.error(\"expected an int\", arg)\n case _:\n self.context.error(\"unexpected argument\", arg)\n case _:\n self.context.error(\n f\"invalid {constants.LOGICSIG_DECORATOR_ALIAS} usage\", decorator\n )\n return _LogicSigDecoratorInfo(name_override=name_override, avm_version=avm_version)\n\n def visit_class_def(self, cdef: mypy.nodes.ClassDef) -> StatementResult:\n self.check_fatal_decorators(cdef.decorators)\n cdef_loc = self._location(cdef)\n match cdef.analyzed:\n case None:\n pass\n case mypy.nodes.TypedDictExpr():\n self._unsupported(cdef, \"TypedDict classes are not supported\")\n case mypy.nodes.NamedTupleExpr():\n return _process_named_tuple(self.context, cdef)\n case unrecognised_analysis_expression:\n self.context.warning(\n \"Analyzed class expression of type\"\n f\" {type(unrecognised_analysis_expression).__name__},\"\n \" please report this issue and check the compilation results carefully\",\n cdef_loc,\n )\n for decorator in cdef.decorators:\n self._error(\n (\n \"Unsupported decorator \"\n \"(note: *all* class decorators are currently unsupported)\"\n ),\n location=decorator,\n )\n info: mypy.nodes.TypeInfo = cdef.info\n if info.bad_mro:\n self._error(\"Bad MRO\", location=cdef_loc)\n return []\n if info.metaclass_type and info.metaclass_type.type.fullname not in (\n \"abc.ABCMeta\",\n \"typing._ProtocolMeta\",\n \"typing_extensions._ProtocolMeta\",\n constants.CLS_ARC4_STRUCT_META,\n constants.STRUCT_META,\n ):\n self._error(\n f\"Unsupported metaclass: {info.metaclass_type.type.fullname}\",\n location=cdef_loc,\n )\n return []\n\n direct_base_types = [\n self.context.require_ptype(ti.fullname, cdef_loc)\n for ti in info.direct_base_classes()\n if ti.fullname not in _BUILTIN_INHERITABLE\n ]\n mro_types = [\n self.context.require_ptype(ti.fullname, cdef_loc)\n for ti in info.mro[1:]\n if ti.fullname not in _BUILTIN_INHERITABLE\n ]\n # create a static type, but don't register it yet,\n # it might end up being a struct instead\n static_type = pytypes.StaticType(\n name=cdef.fullname, bases=direct_base_types, mro=mro_types\n )\n for struct_base in (pytypes.StructBaseType, pytypes.ARC4StructBaseType):\n # note that since these struct bases aren't protocols, any subclasses\n # cannot be protocols\n if struct_base < static_type:\n if direct_base_types != [struct_base]:\n self._error(\n f\"{struct_base} classes must only inherit directly from {struct_base}\",\n cdef_loc,\n )\n return _process_struct(self.context, struct_base, cdef)\n\n if pytypes.ContractBaseType < static_type:\n module_name = cdef.info.module_name\n class_name = cdef.name\n assert \".\" not in class_name\n assert cdef.fullname == f\"{module_name}.{class_name}\"\n contract_type = pytypes.ContractType(\n module_name=module_name,\n class_name=class_name,\n bases=direct_base_types,\n mro=mro_types,\n source_location=cdef_loc,\n )\n self.context.register_pytype(contract_type)\n\n class_options = _process_contract_class_options(self.context, self, cdef)\n converter = ContractASTConverter(self.context, cdef, class_options, contract_type)\n return [converter.build]\n\n if info.is_protocol:\n self.context.register_pytype(static_type)\n if pytypes.ARC4ClientBaseType in direct_base_types:\n ARC4ClientASTVisitor.visit(self.context, cdef)\n else:\n logger.debug(\n f\"Skipping further processing of protocol class {cdef.fullname}\",\n location=cdef_loc,\n )\n return []\n\n logger.error(\n f\"Unsupported class declaration.\"\n f\" Contract classes must inherit either directly\"\n f\" or indirectly from {pytypes.ContractBaseType}.\",\n location=cdef_loc,\n )\n return []\n\n def visit_operator_assignment_stmt(\n self, stmt: mypy.nodes.OperatorAssignmentStmt\n ) -> StatementResult:\n match stmt.lvalue:\n case mypy.nodes.NameExpr(name=\"__all__\"):\n return self.empty_statement(stmt)\n case _:\n self._unsupported(stmt)\n\n def visit_if_stmt(self, stmt: mypy.nodes.IfStmt) -> StatementResult:\n for expr, block in zip(stmt.expr, stmt.body, strict=True):\n if self._evaluate_compile_time_constant_condition(expr):\n return block.accept(self)\n # if we didn't return, we end up here, which means the user code\n # should evaluate to the else body (if present)\n if stmt.else_body:\n return stmt.else_body.accept(self)\n else:\n return []\n\n def visit_assignment_stmt(self, stmt: mypy.nodes.AssignmentStmt) -> StatementResult:\n stmt_loc = self._location(stmt)\n self._precondition(\n bool(stmt.lvalues), \"assignment statements should have at least one lvalue\", stmt_loc\n )\n self._precondition(\n not stmt.invalid_recursive_alias,\n \"assignment statement with invalid_recursive_alias\",\n stmt_loc,\n )\n lvalues = stmt.lvalues\n if not self._check_assignment_lvalues(lvalues):\n return []\n if stmt.is_alias_def:\n match stmt.rvalue:\n case mypy.nodes.RefExpr(\n is_alias_rvalue=True, node=mypy.nodes.TypeInfo(fullname=alias_fullname)\n ):\n maybe_aliased_pytype = self.context.lookup_pytype(alias_fullname)\n if maybe_aliased_pytype is None:\n self.context.error(\n f\"Unknown type for type alias: {alias_fullname}\", stmt_loc\n )\n return []\n aliased_pytype = maybe_aliased_pytype\n case mypy.nodes.IndexExpr(\n analyzed=mypy.nodes.TypeAliasExpr(\n node=mypy.nodes.TypeAlias(alias_tvars=[], target=alias_type)\n )\n ):\n aliased_pytype = self.context.type_to_pytype(\n alias_type, source_location=stmt_loc\n )\n case _:\n self._error(\"Unsupported type-alias format\", stmt_loc)\n return []\n for lvalue in lvalues:\n self.context.register_pytype(aliased_pytype, alias=lvalue.fullname)\n # We don't include type aliases in AWST since they're Python specific\n return []\n if any(lvalue.is_special_form for lvalue in lvalues):\n self._error(\"Unsupported type-form\", stmt_loc)\n\n constant_value = stmt.rvalue.accept(self)\n for lvalue in lvalues:\n self.context.constants[lvalue.fullname] = constant_value\n\n return []\n\n def _check_assignment_lvalues(\n self, lvalues: list[mypy.nodes.Lvalue]\n ) -> typing.TypeGuard[list[mypy.nodes.NameExpr]]:\n \"\"\"Does some pre-condition checks, including that all lvalues are simple (ie name-exprs),\n hence the TypeGuard return type. If it returns True, then we should try and handle the\n assignment.\"\"\"\n result = True\n for lvalue in lvalues:\n if not isinstance(lvalue, mypy.nodes.NameExpr):\n self._error(\n \"Only straight-forward assignment targets supported at module level\", lvalue\n )\n result = False\n else:\n if len(lvalues) > 1:\n self._precondition(\n not lvalue.is_special_form, \"special form with multiple lvalues\", lvalue\n )\n if lvalue.name == \"__all__\":\n # Special notation to denote the public members of a file, we don't need to\n # store this as we don't validate star-imports, mypy does, hence the False.\n # We check inside functions if this is attempted to be referenced and produce\n # a specific error message.\n result = False\n if len(lvalues) > 1:\n self._error(\"Multi-assignment with __all__ not supported\", lvalue)\n break\n fullname = \".\".join((self.module_name, lvalue.name))\n # fullname might be unset if this is in\n # a conditional branch that's !TYPE_CHECKING\n if lvalue.fullname:\n self._precondition(\n lvalue.fullname == fullname,\n f\"assignment to module const - expected fullname of {fullname},\"\n f\" but mypy had {lvalue.fullname}\",\n lvalue,\n )\n else:\n # fix it up\n lvalue._fullname = fullname # noqa: SLF001\n return result\n\n def visit_block(self, block: mypy.nodes.Block) -> StatementResult:\n result = StatementResult()\n for stmt in block.body:\n items = stmt.accept(self)\n result.extend(items)\n return result\n\n # Expressions\n\n def visit_name_expr(self, expr: mypy.nodes.NameExpr) -> ConstantValue:\n match expr.name:\n case \"True\":\n return True\n case \"False\":\n return False\n # TODO: is the GDEF check always valid?\n if not isinstance(expr.node, mypy.nodes.Var) or expr.kind != mypy.nodes.GDEF:\n self._unsupported(\n expr,\n \"references to anything other than module-level constants \"\n \"are not supported at module level\",\n )\n value = self.context.constants.get(expr.fullname)\n if value is None:\n raise CodeError(\n f\"not a known constant value: {expr.name}\"\n f\" (qualified source name: {expr.fullname})\",\n self._location(expr),\n )\n return value\n\n def visit_unary_expr(self, expr: mypy.nodes.UnaryExpr) -> ConstantValue:\n value = expr.expr.accept(self)\n return fold_unary_expr(self._location(expr), expr.op, value)\n\n def visit_op_expr(self, expr: mypy.nodes.OpExpr) -> ConstantValue:\n left_value = expr.left.accept(self)\n right_value = expr.right.accept(self)\n return fold_binary_expr(self._location(expr), expr.op, left_value, right_value)\n\n def visit_comparison_expr(self, expr: mypy.nodes.ComparisonExpr) -> ConstantValue:\n match (expr.operators, expr.operands):\n case ([op], [expr_left, expr_right]):\n lhs = expr_left.accept(self)\n rhs = expr_right.accept(self)\n return fold_binary_expr(self._location(expr), op, lhs, rhs)\n case _:\n self._unsupported(\n expr, details=\"chained comparisons not supported at module level\"\n )\n\n def visit_int_expr(self, expr: mypy.nodes.IntExpr) -> ConstantValue:\n return expr.value\n\n def visit_str_expr(self, expr: mypy.nodes.StrExpr) -> ConstantValue:\n return expr.value\n\n def visit_bytes_expr(self, expr: mypy.nodes.BytesExpr) -> ConstantValue:\n return extract_bytes_literal_from_mypy(expr)\n\n def visit_member_expr(self, expr: mypy.nodes.MemberExpr) -> ConstantValue:\n if (\n isinstance(expr.node, mypy.nodes.Var)\n and expr.kind == mypy.nodes.GDEF\n and expr.fullname\n and isinstance(expr.expr, mypy.nodes.RefExpr)\n and isinstance(expr.expr.node, mypy.nodes.MypyFile)\n ):\n try:\n return self.context.constants[expr.fullname]\n except KeyError as ex:\n self._unsupported(\n expr, details=\"could not resolve external module constant\", ex=ex\n )\n else:\n self._unsupported(expr)\n\n def visit_call_expr(self, expr: mypy.nodes.CallExpr) -> ConstantValue:\n # unfortunately, mypy doesn't preserve f-string identification info,\n # they get translated into either a str.join or str.format call at the top level\n # References:\n # https:\/\/github.com\/python\/mypy\/blob\/cb813259c3b9dff6aaa8686793cf6a0634cf1f69\/mypy\/fastparse.py#L1528\n # https:\/\/github.com\/python\/mypy\/blob\/cb813259c3b9dff6aaa8686793cf6a0634cf1f69\/mypy\/fastparse.py#L1550\n match expr:\n case mypy.nodes.CallExpr(\n callee=mypy.nodes.MemberExpr(expr=mypy.nodes.StrExpr(value=joiner), name=\"join\"),\n args=[mypy.nodes.ListExpr() as args_list],\n ):\n args = [arg.accept(self) for arg in args_list.items]\n assert all(isinstance(x, str) for x in args)\n result = joiner.join(map(str, args))\n return result\n case mypy.nodes.CallExpr(\n callee=mypy.nodes.MemberExpr(\n expr=mypy.nodes.StrExpr(value=format_str), name=\"format\"\n )\n ):\n args = [arg.accept(self) for arg in expr.args]\n return format_str.format(*args)\n case mypy.nodes.CallExpr(\n callee=mypy.nodes.MemberExpr(\n expr=mypy.nodes.StrExpr(value=str_value), name=\"encode\"\n ),\n args=[mypy.nodes.StrExpr(value=encoding)],\n arg_names=[(\"encoding\" | None)],\n ):\n return str_value.encode(encoding=encoding)\n case mypy.nodes.CallExpr(\n callee=mypy.nodes.MemberExpr(\n expr=mypy.nodes.StrExpr(value=str_value), name=\"encode\"\n ),\n args=[],\n ):\n return str_value.encode()\n return self._unsupported(expr)\n\n def visit_conditional_expr(self, expr: mypy.nodes.ConditionalExpr) -> ConstantValue:\n if self._evaluate_compile_time_constant_condition(expr.cond):\n return expr.if_expr.accept(self)\n else:\n return expr.else_expr.accept(self)\n\n def _evaluate_compile_time_constant_condition(self, expr: mypy.nodes.Expression) -> bool:\n from mypy import reachability\n\n kind = reachability.infer_condition_value(expr, self.context.mypy_options)\n if kind == reachability.TRUTH_VALUE_UNKNOWN:\n try:\n result = expr.accept(self)\n except UnsupportedASTError as ex:\n self._unsupported(\n expr,\n details=\"only constant valued conditions supported at module level\",\n ex=ex,\n )\n kind = reachability.ALWAYS_TRUE if result else reachability.ALWAYS_FALSE\n if kind in (reachability.ALWAYS_TRUE, reachability.MYPY_FALSE):\n return True\n elif kind in (reachability.ALWAYS_FALSE, reachability.MYPY_TRUE):\n return False\n else:\n raise InternalError(\n f\"Unexpected reachability value: {kind}\", location=self._location(expr)\n )\n\n def _unsupported(\n self,\n node: mypy.nodes.Node,\n details: str = \"not supported at module level\",\n ex: Exception | None = None,\n ) -> typing.Never:\n raise UnsupportedASTError(node, self._location(node), details=details) from ex\n\n # Unsupported Statements\n\n def visit_expression_stmt(self, stmt: mypy.nodes.ExpressionStmt) -> StatementResult:\n if isinstance(stmt.expr, mypy.nodes.StrExpr):\n # ignore any doc-strings at module level\n return []\n else:\n return self._unsupported(stmt)\n\n def visit_while_stmt(self, stmt: mypy.nodes.WhileStmt) -> StatementResult:\n return self._unsupported(stmt)\n\n def visit_for_stmt(self, stmt: mypy.nodes.ForStmt) -> StatementResult:\n return self._unsupported(stmt)\n\n def visit_break_stmt(self, stmt: mypy.nodes.BreakStmt) -> StatementResult:\n return self._unsupported(stmt)\n\n def visit_continue_stmt(self, stmt: mypy.nodes.ContinueStmt) -> StatementResult:\n return self._unsupported(stmt)\n\n def visit_assert_stmt(self, stmt: mypy.nodes.AssertStmt) -> StatementResult:\n return self._unsupported(stmt)\n\n def visit_del_stmt(self, stmt: mypy.nodes.DelStmt) -> StatementResult:\n return self._unsupported(stmt)\n\n def visit_match_stmt(self, stmt: mypy.nodes.MatchStmt) -> StatementResult:\n return self._unsupported(stmt)\n\n def visit_type_alias_stmt(self, stmt: mypy.nodes.TypeAliasStmt) -> StatementResult:\n return self._unsupported(stmt)\n\n # the remaining statements (below) are invalid at the module lexical scope,\n # mypy should have caught these errors already\n def visit_return_stmt(self, stmt: mypy.nodes.ReturnStmt) -> StatementResult:\n raise InternalError(\"encountered return statement at module level\", self._location(stmt))\n\n # Unsupported Expressions\n\n def visit_super_expr(self, expr: mypy.nodes.SuperExpr) -> ConstantValue:\n return self._unsupported(expr)\n\n def visit_index_expr(self, expr: mypy.nodes.IndexExpr) -> ConstantValue:\n return self._unsupported(expr)\n\n def visit_ellipsis(self, expr: mypy.nodes.EllipsisExpr) -> ConstantValue:\n return self._unsupported(expr)\n\n def visit_dict_expr(self, expr: mypy.nodes.DictExpr) -> ConstantValue:\n return self._unsupported(expr)\n\n def visit_list_expr(self, expr: mypy.nodes.ListExpr) -> ConstantValue:\n return self._unsupported(expr)\n\n def visit_tuple_expr(self, expr: mypy.nodes.TupleExpr) -> ConstantValue:\n return self._unsupported(expr)\n\n def visit_list_comprehension(self, expr: mypy.nodes.ListComprehension) -> ConstantValue:\n return self._unsupported(expr)\n\n def visit_slice_expr(self, expr: mypy.nodes.SliceExpr) -> ConstantValue:\n return self._unsupported(expr)\n\n def visit_assignment_expr(self, o: mypy.nodes.AssignmentExpr) -> ConstantValue:\n return self._unsupported(o)\n\n def visit_lambda_expr(self, expr: mypy.nodes.LambdaExpr) -> ConstantValue:\n return self._unsupported(expr)\n\n\ndef _process_contract_class_options(\n context: ASTConversionModuleContext,\n expr_visitor: mypy.visitor.ExpressionVisitor[ConstantValue],\n cdef: mypy.nodes.ClassDef,\n) -> ContractClassOptions:\n name_override: str | None = None\n scratch_slot_reservations = set[int]()\n state_totals = None\n avm_version = None\n for kw_name, kw_expr in cdef.keywords.items():\n with context.log_exceptions(kw_expr):\n match kw_name:\n case \"name\":\n name_value = kw_expr.accept(expr_visitor)\n if isinstance(name_value, str):\n name_override = name_value\n else:\n context.error(\"unexpected argument type\", kw_expr)\n case \"scratch_slots\":\n if isinstance(kw_expr, mypy.nodes.TupleExpr | mypy.nodes.ListExpr):\n slot_items = kw_expr.items\n else:\n slot_items = [kw_expr]\n for item_expr in slot_items:\n slots = _map_scratch_space_reservation(context, expr_visitor, item_expr)\n if not slots:\n context.error(\"range is empty\", item_expr)\n elif (min(slots) < 0) or (max(slots) > MAX_SCRATCH_SLOT_NUMBER):\n context.error(\n \"invalid scratch slot reservation - range must fall\"\n f\" entirely between 0 and {MAX_SCRATCH_SLOT_NUMBER}\",\n item_expr,\n )\n else:\n scratch_slot_reservations.update(slots)\n case \"state_totals\":\n if not isinstance(kw_expr, mypy.nodes.CallExpr):\n context.error(\"unexpected argument type\", kw_expr)\n else:\n arg_map = dict[str, int]()\n for arg_name, arg in zip(kw_expr.arg_names, kw_expr.args, strict=True):\n if arg_name is None:\n context.error(\"unexpected positional argument\", arg)\n else:\n arg_value = arg.accept(expr_visitor)\n if not isinstance(arg_value, int):\n context.error(\"unexpected argument type\", arg)\n else:\n arg_map[arg_name] = arg_value\n state_totals = StateTotals(**arg_map)\n case \"avm_version\":\n version_value = kw_expr.accept(expr_visitor)\n if isinstance(version_value, int):\n avm_version = version_value\n else:\n context.error(\"unexpected argument type\", kw_expr)\n case \"metaclass\":\n context.error(\"metaclass option is unsupported\", kw_expr)\n case _:\n context.error(\"unrecognised class option\", kw_expr)\n return ContractClassOptions(\n name_override=name_override,\n scratch_slot_reservations=scratch_slot_reservations,\n state_totals=state_totals,\n avm_version=avm_version,\n )\n\n\ndef _process_dataclass_like_fields(\n context: ASTConversionModuleContext, cdef: mypy.nodes.ClassDef, base_type: pytypes.PyType\n) -> dict[str, pytypes.PyType] | None:\n fields = dict[str, pytypes.PyType]()\n has_error = False\n for stmt in cdef.defs.body:\n stmt_loc = context.node_location(stmt)\n match stmt:\n case mypy.nodes.ExpressionStmt(expr=mypy.nodes.StrExpr()):\n # ignore class docstring, already extracted\n # TODO: should we capture field \"docstrings\"?\n pass\n case mypy.nodes.AssignmentStmt(\n lvalues=[mypy.nodes.NameExpr(name=field_name)],\n rvalue=mypy.nodes.TempNode(),\n type=mypy.types.Type() as mypy_type,\n ):\n pytype = context.type_to_pytype(mypy_type, source_location=stmt_loc)\n fields[field_name] = pytype\n if isinstance((maybe_err := pytype.wtype), str):\n logger.error(maybe_err, location=stmt_loc)\n has_error = True\n case mypy.nodes.SymbolNode(name=symbol_name) if (\n cdef.info.names[symbol_name].plugin_generated\n ):\n pass\n case mypy.nodes.PassStmt():\n pass\n case _:\n logger.error(\n f\"unsupported syntax for {base_type} member declaration\", location=stmt_loc\n )\n has_error = True\n return fields if not has_error else None\n\n\ndef _process_struct(\n context: ASTConversionModuleContext, base: pytypes.PyType, cdef: mypy.nodes.ClassDef\n) -> StatementResult:\n fields = _process_dataclass_like_fields(context, cdef, base)\n if fields is None:\n return []\n cls_loc = context.node_location(cdef)\n frozen = cdef.info.metadata[\"dataclass\"][\"frozen\"]\n assert isinstance(frozen, bool)\n struct_typ = pytypes.StructType(\n base=base,\n name=cdef.fullname,\n desc=cdef.docstring,\n fields=fields,\n frozen=frozen,\n source_location=cls_loc,\n )\n context.register_pytype(struct_typ)\n return []\n\n\ndef _process_named_tuple(\n context: ASTConversionModuleContext, cdef: mypy.nodes.ClassDef\n) -> StatementResult:\n fields = _process_dataclass_like_fields(context, cdef, pytypes.NamedTupleBaseType)\n if fields is None:\n return []\n cls_loc = context.node_location(cdef)\n named_tuple_type = pytypes.NamedTupleType(\n name=cdef.fullname,\n desc=cdef.docstring,\n fields=fields,\n source_location=cls_loc,\n )\n context.register_pytype(named_tuple_type)\n return []\n\n\ndef _map_scratch_space_reservation(\n context: ASTConversionModuleContext,\n expr_visitor: mypy.visitor.ExpressionVisitor[ConstantValue],\n expr: mypy.nodes.Expression,\n) -> list[int]:\n def get_int_arg(arg_expr: mypy.nodes.Expression, *, error_msg: str) -> int:\n const_value = arg_expr.accept(expr_visitor)\n if isinstance(const_value, int):\n return const_value\n raise CodeError(error_msg, context.node_location(arg_expr))\n\n expr_loc = context.node_location(expr)\n match expr:\n case mypy.nodes.CallExpr(\n callee=mypy.nodes.RefExpr() as callee, args=args\n ) if get_unaliased_fullname(callee) == constants.URANGE:\n if not args:\n raise CodeError(\"Expected at least one argument to urange\", expr_loc)\n if len(args) > 3:\n raise CodeError(\"Expected at most three arguments to urange\", expr_loc)\n int_args = [\n get_int_arg(\n arg_expr,\n error_msg=(\n \"Unexpected argument for urange:\"\n \" expected an in integer literal or module constant reference\"\n ),\n )\n for arg_expr in args\n ]\n if len(int_args) == 3 and int_args[-1] == 0:\n raise CodeError(\"urange arg 3 must not be zero\", context.node_location(args[-1]))\n return list(range(*int_args))\n case _:\n return [\n get_int_arg(\n expr,\n error_msg=(\n \"Unexpected value:\"\n \" Expected int literal, module constant reference, or urange expression\"\n ),\n )\n ]\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/module.py","language":"Python","license":"NOASSERTION","size":33203} {"code":"from __future__ import annotations\n\nimport abc\nimport typing\nfrom collections.abc import Callable, Mapping, Sequence\nfrom functools import cached_property\n\nimport attrs\nimport typing_extensions\nfrom immutabledict import immutabledict\n\nfrom puya import log\nfrom puya.avm import TransactionType\nfrom puya.awst import wtypes\nfrom puya.errors import CodeError, InternalError\nfrom puya.parse import SourceLocation\nfrom puya.program_refs import ContractReference\nfrom puya.utils import lazy_setdefault, unique\nfrom puyapy.awst_build import constants\n\nif typing.TYPE_CHECKING:\n from mypy.nodes import ArgKind\n\n from puyapy.awst_build.intrinsic_models import (\n OpMappingWithOverloads,\n PropertyOpMapping,\n )\n\nlogger = log.get_logger(__name__)\n\n\nErrorMessage = typing.NewType(\"ErrorMessage\", str)\n\n\n@attrs.frozen(kw_only=True, str=False, order=False)\nclass PyType(abc.ABC):\n name: str\n \"\"\"The canonical fully qualified type name\"\"\"\n generic: PyType | None = None\n \"\"\"The generic type that this type was parameterised from, if any.\"\"\"\n bases: tuple[PyType, ...] = attrs.field(default=(), converter=tuple[\"PyType\", ...])\n \"\"\"Direct base classes. probably excluding the implicit builtins.object?\"\"\"\n mro: tuple[PyType, ...] = attrs.field(default=(), converter=tuple[\"PyType\", ...])\n \"\"\"All base cases, in Method Resolution Order\"\"\"\n\n @bases.validator\n def _bases_validate(self, _attribute: object, bases: tuple[PyType, ...]) -> None:\n if len(set(bases)) != len(bases):\n raise InternalError(f\"Duplicate bases in {self}: [{', '.join(map(str, bases))}]\")\n\n @mro.validator\n def _mro_validate(self, _attribute: object, mro: tuple[PyType, ...]) -> None:\n bases_missing_from_mro = set(self.bases).difference(mro)\n if bases_missing_from_mro:\n raise InternalError(\n f\"Bases missing from MRO in {self}:\"\n f\" [{', '.join(map(str, bases_missing_from_mro))}]\"\n )\n\n @cached_property\n def _friendly_name(self) -> str:\n \"\"\"User-friendly fully-qualified name.\n\n Basically just strips \"builtins.\" from types, and removes the private part\n of algopy names.\n \"\"\"\n import re\n\n result, _ = re.subn(r\"\\bbuiltins\\.\", \"\", self.name)\n result, _ = re.subn(r\"algopy\\._[^.]+\", \"algopy\", result)\n result = result.replace(NoneType.name, \"None\")\n return result\n\n def __str__(self) -> str:\n return self._friendly_name\n\n @property\n @abc.abstractmethod\n def wtype(self) -> wtypes.WType | ErrorMessage:\n \"\"\"The WType that this type represents, if any.\"\"\"\n\n def checked_wtype(self, location: SourceLocation | None) -> wtypes.WType:\n match self.wtype:\n case wtypes.WType() as wtype:\n return wtype\n case str(msg):\n raise CodeError(msg, location)\n case _:\n typing.assert_never(self.wtype)\n\n def parameterise(\n self,\n args: Sequence[PyType], # noqa: ARG002\n source_location: SourceLocation | None,\n ) -> PyType:\n \"\"\"Produce parameterised type.\n Throws if not a generic type of if a parameterised generic type.\"\"\"\n if self.generic:\n raise CodeError(f\"type already has parameters: {self}\", source_location)\n raise CodeError(f\"not a generic type: {self}\", source_location)\n\n @typing.final\n def __lt__(self, other: object) -> bool:\n if not isinstance(other, PyType):\n return NotImplemented\n # self < other -> self is a supertype of other\n return self in other.mro\n\n @typing.final\n def __le__(self, other: object) -> bool:\n if not isinstance(other, PyType):\n return NotImplemented\n return self == other or self < other\n\n @typing.final\n def __gt__(self, other: object) -> bool:\n if not isinstance(other, PyType):\n return NotImplemented\n raise TypeError(\"types are partial ordered\")\n\n @typing.final\n def __ge__(self, other: object) -> bool:\n if not isinstance(other, PyType):\n return NotImplemented\n raise TypeError(\"types are partial ordered\")\n\n def is_type_or_subtype(self, *of_any: PyType) -> bool:\n return any(of <= self for of in of_any)\n\n def is_type_or_supertype(self, *of_any: PyType) -> bool:\n return any(self <= of for of in of_any)\n\n\nclass RuntimeType(PyType, abc.ABC):\n @typing.override\n @property\n @abc.abstractmethod\n def wtype(self) -> wtypes.WType: ...\n\n\n_builtins_registry: typing.Final = dict[str, PyType]()\n\n\n_TPyType = typing_extensions.TypeVar(\"_TPyType\", bound=PyType, default=PyType)\n\n\ndef _register_builtin(typ: _TPyType, *, alias: str | None = None) -> _TPyType:\n name = alias or typ.name\n existing_entry = _builtins_registry.get(name)\n if existing_entry is None:\n _builtins_registry[name] = typ\n elif existing_entry is typ:\n logger.debug(f\"Duplicate registration of {typ}\")\n else:\n raise InternalError(f\"Duplicate mapping of {name}\")\n return typ\n\n\ndef builtins_registry() -> dict[str, PyType]:\n \"\"\"Get a copy of the builtins registry\"\"\"\n return _builtins_registry.copy()\n\n\n# https:\/\/typing.readthedocs.io\/en\/latest\/spec\/literal.html#legal-and-illegal-parameterizations\n# We don't support enums as typing.Literal parameters. mypy encodes these as str values with\n# an additional \"fallback\" data member, but we don't need that complication.\n# mypy.types.LiteralValue also includes float, noting its invalid as a parameterization, but\n# we exclude this here.\n# None types are also encoded as their own type, but we have them as values here.\nTypingLiteralValue: typing.TypeAlias = int | bytes | str | bool | None\n_TypeArgs: typing.TypeAlias = tuple[PyType, ...]\n_Parameterise = typing_extensions.TypeAliasType(\n \"_Parameterise\",\n Callable[[\"_GenericType[_TPyType]\", _TypeArgs, SourceLocation | None], _TPyType],\n type_params=(_TPyType,),\n)\n\n\n@typing.final\n@attrs.frozen(order=False)\nclass _GenericType(PyType, abc.ABC, typing.Generic[_TPyType]):\n \"\"\"Represents a typing.Generic type with unknown parameters\"\"\"\n\n _parameterise: _Parameterise[_TPyType]\n _instance_cache: dict[_TypeArgs, _TPyType] = attrs.field(factory=dict, eq=False)\n\n def __attrs_post_init__(self) -> None:\n _register_builtin(self)\n\n @typing.override\n @property\n def wtype(self) -> ErrorMessage:\n return ErrorMessage(\"generic type usage requires parameters\")\n\n @typing.override\n def parameterise(\n self, args: Sequence[PyType], source_location: SourceLocation | None\n ) -> _TPyType:\n return lazy_setdefault(\n self._instance_cache,\n key=tuple(args),\n default=lambda args_: self._parameterise(self, args_, source_location),\n )\n\n\ndef _parameterise_type_type(\n self: _GenericType, # noqa: ARG001\n args: _TypeArgs,\n source_location: SourceLocation | None,\n) -> TypeType:\n try:\n (arg,) = args\n except ValueError:\n raise CodeError(\n f\"expected a single type parameter, got {len(args)} parameters\", source_location\n ) from None\n return TypeType(typ=arg)\n\n\nGenericTypeType: typing.Final[PyType] = _GenericType(\n name=\"builtins.type\",\n parameterise=_parameterise_type_type,\n)\n\n\n@typing.final\n@attrs.frozen(order=False)\nclass TypeType(PyType):\n typ: PyType\n generic: PyType = attrs.field(default=GenericTypeType, init=False)\n name: str = attrs.field(init=False)\n\n @name.default\n def _name_default(self) -> str:\n return f\"{self.generic.name}[{self.typ.name}]\"\n\n @typing.override\n @property\n def wtype(self) -> ErrorMessage:\n return ErrorMessage(\"type objects are not usable as values\")\n\n\n@typing.final\n@attrs.frozen(order=False)\nclass TypingLiteralType(PyType):\n value: TypingLiteralValue\n source_location: SourceLocation | None\n name: str = attrs.field(init=False)\n generic: None = attrs.field(default=None, init=False)\n bases: tuple[PyType, ...] = attrs.field(default=(), init=False)\n mro: tuple[PyType, ...] = attrs.field(default=(), init=False)\n\n @name.default\n def _name_default(self) -> str:\n return f\"typing.Literal[{self.value!r}]\"\n\n @typing.override\n @property\n def wtype(self) -> ErrorMessage:\n return ErrorMessage(f\"{self} is not usable as a value\")\n\n\ndef _flatten_nested_unions(types: Sequence[PyType]) -> tuple[PyType, ...]:\n result = list[PyType]()\n for t in types:\n if isinstance(t, UnionType):\n result.extend(t.types)\n else:\n result.append(t)\n return tuple(unique(result))\n\n\n@typing.final\n@attrs.frozen(order=False)\nclass UnionType(PyType):\n types: tuple[PyType, ...] = attrs.field(\n converter=_flatten_nested_unions, validator=attrs.validators.min_len(2)\n )\n name: str = attrs.field(init=False)\n generic: None = attrs.field(default=None, init=False)\n bases: tuple[PyType, ...] = attrs.field(default=(), init=False)\n mro: tuple[PyType, ...] = attrs.field(default=(), init=False)\n source_location: SourceLocation\n\n @name.default\n def _name(self) -> str:\n return \" | \".join(t.name for t in self.types)\n\n @typing.override\n @property\n def wtype(self) -> ErrorMessage:\n return ErrorMessage(\"type unions are unsupported at this location\")\n\n\n@attrs.frozen(order=False)\nclass _BaseType(PyType):\n \"\"\"Type that is only usable as a base type\"\"\"\n\n @typing.override\n @property\n def wtype(self) -> ErrorMessage:\n return ErrorMessage(f\"{self} is only usable as a base type\")\n\n def __attrs_post_init__(self) -> None:\n _register_builtin(self)\n\n\n@attrs.frozen(kw_only=True, order=False)\nclass TupleLikeType(PyType, abc.ABC):\n items: tuple[PyType, ...]\n source_location: SourceLocation | None\n\n\ndef _parameterise_tuple(\n self: _GenericType[TupleType], args: _TypeArgs, source_location: SourceLocation | None\n) -> TupleType:\n name = f\"{self.name}[{', '.join(pyt.name for pyt in args)}]\"\n return TupleType(name=name, items=tuple(args), source_location=source_location)\n\n\nGenericTupleType: typing.Final = _GenericType(\n name=\"builtins.tuple\",\n parameterise=_parameterise_tuple,\n)\n\n\n@attrs.frozen(kw_only=True, order=False)\nclass TupleType(TupleLikeType):\n generic: PyType | None = attrs.field(default=GenericTupleType, init=False)\n bases: tuple[PyType, ...] = attrs.field(default=(), init=False)\n mro: tuple[PyType, ...] = attrs.field(default=(), init=False)\n\n @property\n def wtype(self) -> wtypes.WTuple | ErrorMessage:\n item_wtypes = []\n for i in self.items:\n match i.wtype:\n case wtypes.WType() as wtype:\n item_wtypes.append(wtype)\n case ErrorMessage() as err:\n return err\n case other:\n typing.assert_never(other)\n return wtypes.WTuple(\n types=item_wtypes,\n source_location=self.source_location,\n )\n\n\nNamedTupleBaseType: typing.Final[PyType] = _BaseType(name=\"typing.NamedTuple\")\n\n\n@attrs.frozen(kw_only=True, order=False)\nclass NamedTupleType(TupleType, RuntimeType):\n fields: immutabledict[str, PyType] = attrs.field(converter=immutabledict)\n items: tuple[PyType, ...] = attrs.field(init=False)\n generic: None = attrs.field(default=None, init=False)\n bases: tuple[PyType, ...] = attrs.field(default=(NamedTupleBaseType,), init=False)\n mro: tuple[PyType, ...] = attrs.field(default=(NamedTupleBaseType,), init=False)\n desc: str | None = None\n wtype: wtypes.WTuple = attrs.field(init=False)\n\n @items.default\n def _items(self) -> tuple[PyType, ...]:\n return tuple(self.fields.values())\n\n @wtype.default\n def _wtype(self) -> wtypes.WTuple:\n unnamed_type = super().wtype\n if isinstance(unnamed_type, str):\n raise CodeError(unnamed_type, self.source_location)\n return attrs.evolve(\n unnamed_type,\n name=self.name,\n names=tuple(self.fields),\n source_location=self.source_location,\n desc=self.desc,\n )\n\n\n@attrs.frozen(order=False)\nclass SequenceType(PyType, abc.ABC):\n items: PyType\n\n\n@typing.final\n@attrs.frozen(order=False)\nclass ArrayType(SequenceType, RuntimeType):\n size: int | None\n wtype: wtypes.WType\n # convenience accessors\n items_wtype: wtypes.WType\n\n\n@typing.final\n@attrs.frozen(order=False)\nclass StorageProxyType(RuntimeType):\n content: PyType\n wtype: wtypes.WType\n # convenience accessors\n content_wtype: wtypes.WType\n\n\n@typing.final\n@attrs.frozen(order=False)\nclass StorageMapProxyType(RuntimeType):\n generic: PyType\n key: PyType\n content: PyType\n wtype: wtypes.WType\n # convenience accessors\n key_wtype: wtypes.WType\n content_wtype: wtypes.WType\n\n\n@typing.final\n@attrs.frozen\nclass FuncArg:\n type: PyType\n name: str | None\n kind: ArgKind\n\n\n@typing.final\n@attrs.frozen(kw_only=True, order=False)\nclass FuncType(PyType):\n ret_type: PyType\n args: tuple[FuncArg, ...] = attrs.field(converter=tuple[FuncArg, ...])\n # static data\n generic: None = None\n bases: tuple[PyType, ...] = attrs.field(default=(), init=False)\n mro: tuple[PyType, ...] = attrs.field(default=(), init=False)\n\n @typing.override\n @property\n def wtype(self) -> ErrorMessage:\n return ErrorMessage(\"function objects are not usable as values\")\n\n\n@typing.final\n@attrs.frozen(order=False)\nclass StaticType(PyType):\n @typing.override\n @property\n def wtype(self) -> ErrorMessage:\n return ErrorMessage(f\"{self} is only usable as a type and cannot be instantiated\")\n\n\n@typing.final\n@attrs.frozen(kw_only=True, order=False)\nclass ContractType(PyType):\n generic: None = attrs.field(default=None, init=False)\n module_name: str\n class_name: str\n name: ContractReference = attrs.field(init=False)\n source_location: SourceLocation\n\n @name.default\n def _name(self) -> ContractReference:\n return ContractReference(\".\".join((self.module_name, self.class_name)))\n\n @typing.override\n @property\n def wtype(self) -> ErrorMessage:\n return ErrorMessage(f\"{self} is only usable as a type and cannot be instantiated\")\n\n\nObjectType: typing.Final[PyType] = _register_builtin(StaticType(name=\"builtins.object\"))\n\n\n@typing.final\n@attrs.frozen(init=False, order=False)\nclass StructType(RuntimeType):\n fields: immutabledict[str, PyType] = attrs.field(\n converter=immutabledict, validator=[attrs.validators.min_len(1)]\n )\n frozen: bool\n wtype: wtypes.ARC4Struct | wtypes.WStructType\n source_location: SourceLocation | None\n generic: None = None\n desc: str | None = None\n\n @cached_property\n def names(self) -> tuple[str, ...]:\n return tuple(self.fields.keys())\n\n @cached_property\n def types(self) -> tuple[PyType, ...]:\n return tuple(self.fields.values())\n\n def __init__(\n self,\n *,\n base: PyType,\n name: str,\n desc: str | None,\n fields: Mapping[str, PyType],\n frozen: bool,\n source_location: SourceLocation | None,\n ):\n field_wtypes = {\n name: field_typ.checked_wtype(source_location) for name, field_typ in fields.items()\n } # TODO: this is a bit of a kludge\n wtype_cls: type[wtypes.ARC4Struct | wtypes.WStructType]\n if base is ARC4StructBaseType:\n wtype_cls = wtypes.ARC4Struct\n elif base is StructBaseType:\n wtype_cls = wtypes.WStructType\n else:\n raise InternalError(f\"Unknown struct base type: {base}\", source_location)\n wtype = wtype_cls(\n fields=field_wtypes,\n name=name,\n desc=desc,\n frozen=frozen,\n source_location=source_location,\n )\n self.__attrs_init__(\n bases=[base],\n mro=[base],\n name=name,\n desc=desc,\n wtype=wtype,\n fields=fields,\n frozen=frozen,\n source_location=source_location,\n )\n\n\n@typing.final\n@attrs.frozen(order=False)\nclass _SimpleType(RuntimeType):\n wtype: wtypes.WType\n\n def __attrs_post_init__(self) -> None:\n _register_builtin(self)\n\n\n@typing.final\n@attrs.frozen(order=False)\nclass LiteralOnlyType(PyType):\n python_type: type[int | bytes | str]\n name: str = attrs.field(init=False)\n\n @name.default\n def _name(self) -> str:\n return \".\".join((self.python_type.__module__, self.python_type.__qualname__))\n\n @typing.override\n @property\n def wtype(self) -> ErrorMessage:\n return ErrorMessage(f\"Python literals of type {self} cannot be used as runtime values\")\n\n\nNoneType: typing.Final[RuntimeType] = _SimpleType(name=\"types.NoneType\", wtype=wtypes.void_wtype)\nNeverType: typing.Final[PyType] = _SimpleType(name=\"typing.Never\", wtype=wtypes.void_wtype)\nIntLiteralType: typing.Final = _register_builtin(LiteralOnlyType(int))\nStrLiteralType: typing.Final = _register_builtin(LiteralOnlyType(str))\nBytesLiteralType: typing.Final = _register_builtin(LiteralOnlyType(bytes))\nBoolType: typing.Final[RuntimeType] = _SimpleType(\n name=\"builtins.bool\",\n wtype=wtypes.bool_wtype,\n bases=[IntLiteralType],\n mro=[IntLiteralType],\n)\n\nUInt64Type: typing.Final[RuntimeType] = _SimpleType(\n name=\"algopy._primitives.UInt64\",\n wtype=wtypes.uint64_wtype,\n)\nBigUIntType: typing.Final[RuntimeType] = _SimpleType(\n name=\"algopy._primitives.BigUInt\",\n wtype=wtypes.biguint_wtype,\n)\nBytesType: typing.Final[RuntimeType] = _SimpleType(\n name=\"algopy._primitives.Bytes\",\n wtype=wtypes.bytes_wtype,\n)\nStringType: typing.Final[RuntimeType] = _SimpleType(\n name=\"algopy._primitives.String\",\n wtype=wtypes.string_wtype,\n)\nAccountType: typing.Final[RuntimeType] = _SimpleType(\n name=\"algopy._reference.Account\",\n wtype=wtypes.account_wtype,\n)\nAssetType: typing.Final[RuntimeType] = _SimpleType(\n name=\"algopy._reference.Asset\",\n wtype=wtypes.asset_wtype,\n)\nApplicationType: typing.Final[RuntimeType] = _SimpleType(\n name=\"algopy._reference.Application\",\n wtype=wtypes.application_wtype,\n)\n\n\n@attrs.frozen(init=False, order=False)\nclass UInt64EnumType(RuntimeType):\n def __init__(self, name: str):\n self.__attrs_init__(\n name=name,\n bases=[UInt64Type],\n mro=[UInt64Type],\n )\n _register_builtin(self)\n\n @property\n def wtype(self) -> wtypes.WType:\n return wtypes.uint64_wtype\n\n\nOnCompleteActionType: typing.Final = UInt64EnumType(\n name=\"algopy._constants.OnCompleteAction\",\n)\nTransactionTypeType: typing.Final = UInt64EnumType(\n name=\"algopy._constants.TransactionType\",\n)\nOpUpFeeSourceType: typing.Final = UInt64EnumType(\n name=\"algopy._util.OpUpFeeSource\",\n)\n\nARC4StringType: typing.Final[RuntimeType] = _SimpleType(\n name=\"algopy.arc4.String\",\n wtype=wtypes.arc4_string_alias,\n)\nARC4BoolType: typing.Final[RuntimeType] = _SimpleType(\n name=\"algopy.arc4.Bool\",\n wtype=wtypes.arc4_bool_wtype,\n)\n\n\n@attrs.frozen(order=False)\nclass ARC4UIntNType(RuntimeType):\n bits: int\n wtype: wtypes.ARC4UIntN\n native_type: RuntimeType\n\n\ndef _require_int_literal(\n generic: _GenericType[_TPyType],\n type_arg: PyType,\n source_location: SourceLocation | None,\n *,\n position_qualifier: str = \"\",\n) -> int:\n match type_arg:\n case TypingLiteralType(value=int(value)):\n return value\n if position_qualifier:\n position_qualifier = position_qualifier + \" \"\n raise CodeError(\n f\"{generic} expects a typing.Literal[] as a {position_qualifier}parameter\",\n source_location,\n )\n\n\ndef _make_arc4_unsigned_int_parameterise(\n *, native_type: RuntimeType, max_bits: int | None = None\n) -> _Parameterise:\n def parameterise(\n self: _GenericType, args: _TypeArgs, source_location: SourceLocation | None\n ) -> ARC4UIntNType:\n try:\n (bits_t,) = args\n except ValueError:\n raise CodeError(\n f\"expected a single type parameter, got {len(args)} parameters\", source_location\n ) from None\n bits = _require_int_literal(self, bits_t, source_location)\n if (max_bits is not None) and bits > max_bits:\n raise CodeError(f\"max bit size of {self} is {max_bits}, got {bits}\", source_location)\n\n name = f\"{self.name}[{bits_t.name}]\"\n return ARC4UIntNType(\n generic=self,\n name=name,\n bits=bits,\n native_type=native_type,\n wtype=wtypes.ARC4UIntN(n=bits, source_location=source_location),\n )\n\n return parameterise\n\n\nGenericARC4UIntNType: typing.Final = _GenericType(\n name=\"algopy.arc4.UIntN\",\n parameterise=_make_arc4_unsigned_int_parameterise(native_type=UInt64Type, max_bits=64),\n)\nGenericARC4BigUIntNType: typing.Final = _GenericType(\n name=\"algopy.arc4.BigUIntN\",\n parameterise=_make_arc4_unsigned_int_parameterise(native_type=BigUIntType),\n)\n\n\nARC4UIntN_Aliases: typing.Final = immutabledict[int, ARC4UIntNType](\n {\n (_bits := 2**_exp): _register_builtin(\n (GenericARC4UIntNType if _bits <= 64 else GenericARC4BigUIntNType).parameterise(\n [TypingLiteralType(value=_bits, source_location=None)], source_location=None\n ),\n alias=f\"algopy.arc4.UInt{_bits}\",\n )\n for _exp in range(3, 10)\n }\n)\nARC4ByteType: typing.Final = _register_builtin(\n ARC4UIntNType(\n generic=None,\n name=\"algopy.arc4.Byte\",\n wtype=wtypes.arc4_byte_alias,\n bits=8,\n bases=[ARC4UIntN_Aliases[8]],\n mro=[ARC4UIntN_Aliases[8]],\n native_type=UInt64Type,\n )\n)\n\n\n@attrs.frozen(order=False)\nclass ARC4UFixedNxMType(RuntimeType):\n generic: _GenericType\n bits: int\n precision: int\n wtype: wtypes.WType\n\n\ndef _make_arc4_unsigned_fixed_parameterise(*, max_bits: int | None = None) -> _Parameterise:\n def parameterise(\n self: _GenericType, args: _TypeArgs, source_location: SourceLocation | None\n ) -> ARC4UFixedNxMType:\n try:\n bits_t, precision_t = args\n except ValueError:\n raise CodeError(\n f\"expected two type parameters, got {len(args)} parameters\", source_location\n ) from None\n bits = _require_int_literal(self, bits_t, source_location, position_qualifier=\"first\")\n precision = _require_int_literal(\n self, precision_t, source_location, position_qualifier=\"second\"\n )\n if (max_bits is not None) and bits > max_bits:\n raise CodeError(f\"max bit size of {self} is {max_bits}, got {bits}\", source_location)\n\n name = f\"{self.name}[{bits_t.name}, {precision_t.name}]\"\n return ARC4UFixedNxMType(\n generic=self,\n name=name,\n bits=bits,\n precision=precision,\n wtype=wtypes.ARC4UFixedNxM(n=bits, m=precision, source_location=source_location),\n )\n\n return parameterise\n\n\nGenericARC4UFixedNxMType: typing.Final = _GenericType(\n name=\"algopy.arc4.UFixedNxM\",\n parameterise=_make_arc4_unsigned_fixed_parameterise(max_bits=64),\n)\nGenericARC4BigUFixedNxMType: typing.Final = _GenericType(\n name=\"algopy.arc4.BigUFixedNxM\",\n parameterise=_make_arc4_unsigned_fixed_parameterise(),\n)\n\n\ndef _parameterise_arc4_tuple(\n self: _GenericType[ARC4TupleType], # noqa: ARG001\n args: _TypeArgs,\n source_location: SourceLocation | None,\n) -> ARC4TupleType:\n item_wtypes = tuple(arg.checked_wtype(source_location) for arg in args)\n wtype = wtypes.ARC4Tuple(types=item_wtypes, source_location=source_location)\n return ARC4TupleType(items=tuple(args), wtype=wtype, source_location=source_location)\n\n\nGenericARC4TupleType: typing.Final = _GenericType(\n name=\"algopy.arc4.Tuple\",\n parameterise=_parameterise_arc4_tuple,\n)\n\n\n@typing.final\n@attrs.frozen(kw_only=True, order=False)\nclass ARC4TupleType(TupleLikeType, RuntimeType):\n generic: _GenericType = attrs.field(default=GenericARC4TupleType, init=False)\n name: str = attrs.field(init=False)\n bases: tuple[PyType, ...] = attrs.field(default=(), init=False)\n mro: tuple[PyType, ...] = attrs.field(default=(), init=False)\n wtype: wtypes.ARC4Tuple\n\n @name.default\n def _name(self) -> str:\n return f\"{self.generic.name}[{', '.join(pyt.name for pyt in self.items)}]\"\n\n\nCompiledContractType: typing.Final = _register_builtin(\n NamedTupleType(\n name=\"algopy._compiled.CompiledContract\",\n fields={\n \"approval_program\": GenericTupleType.parameterise([BytesType, BytesType], None),\n \"clear_state_program\": GenericTupleType.parameterise([BytesType, BytesType], None),\n \"extra_program_pages\": UInt64Type,\n \"global_uints\": UInt64Type,\n \"global_bytes\": UInt64Type,\n \"local_uints\": UInt64Type,\n \"local_bytes\": UInt64Type,\n },\n source_location=None,\n )\n)\nCompiledLogicSigType: typing.Final = _register_builtin(\n NamedTupleType(\n name=\"algopy._compiled.CompiledLogicSig\",\n fields={\n \"account\": AccountType,\n },\n source_location=None,\n )\n)\n\n\n@typing.final\n@attrs.frozen(order=False)\nclass VariadicTupleType(SequenceType):\n items: PyType\n generic: _GenericType = attrs.field(default=GenericTupleType, init=False)\n bases: tuple[PyType, ...] = attrs.field(default=(), init=False)\n mro: tuple[PyType, ...] = attrs.field(default=(), init=False)\n name: str = attrs.field(init=False)\n\n @name.default\n def _name_factory(self) -> str:\n return f\"{self.generic.name}[{self.items.name}, ...]\"\n\n @typing.override\n @property\n def wtype(self) -> ErrorMessage:\n return ErrorMessage(\"variadic tuples cannot be used as runtime values\")\n\n\ndef _make_array_parameterise(\n typ: type[wtypes.WArray | wtypes.ARC4DynamicArray],\n) -> _Parameterise[ArrayType]:\n def parameterise(\n self: _GenericType[ArrayType], args: _TypeArgs, source_location: SourceLocation | None\n ) -> ArrayType:\n try:\n (arg,) = args\n except ValueError:\n raise CodeError(\n f\"expected a single type parameter, got {len(args)} parameters\", source_location\n ) from None\n name = f\"{self.name}[{arg.name}]\"\n items_wtype = arg.checked_wtype(source_location)\n\n return ArrayType(\n generic=self,\n name=name,\n size=None,\n items=arg,\n wtype=typ(element_type=items_wtype, source_location=source_location),\n items_wtype=items_wtype,\n )\n\n return parameterise\n\n\nGenericArrayType: typing.Final = _GenericType(\n name=\"algopy._array.Array\",\n parameterise=_make_array_parameterise(wtypes.WArray),\n)\n\nGenericARC4DynamicArrayType: typing.Final = _GenericType(\n name=\"algopy.arc4.DynamicArray\",\n parameterise=_make_array_parameterise(wtypes.ARC4DynamicArray),\n)\nARC4DynamicBytesType: typing.Final = _register_builtin(\n ArrayType(\n name=\"algopy.arc4.DynamicBytes\",\n wtype=wtypes.ARC4DynamicArray(\n element_type=ARC4ByteType.wtype,\n native_type=wtypes.bytes_wtype,\n source_location=None,\n ),\n size=None,\n items=ARC4ByteType,\n items_wtype=ARC4ByteType.wtype,\n bases=[GenericARC4DynamicArrayType.parameterise([ARC4ByteType], source_location=None)],\n mro=[GenericARC4DynamicArrayType.parameterise([ARC4ByteType], source_location=None)],\n )\n)\n\n\ndef _parameterise_arc4_static_array(\n self: _GenericType[ArrayType], args: _TypeArgs, source_location: SourceLocation | None\n) -> ArrayType:\n try:\n items, size_t = args\n except ValueError:\n raise CodeError(\n f\"expected a single type parameter, got {len(args)} parameters\", source_location\n ) from None\n size = _require_int_literal(self, size_t, source_location, position_qualifier=\"second\")\n if size < 0:\n raise CodeError(\"array size should be non-negative\", source_location)\n\n name = f\"{self.name}[{items.name}, {size_t.name}]\"\n items_wtype = items.checked_wtype(source_location)\n\n return ArrayType(\n generic=self,\n name=name,\n size=size,\n items=items,\n wtype=wtypes.ARC4StaticArray(\n element_type=items_wtype, array_size=size, source_location=source_location\n ),\n items_wtype=items_wtype,\n )\n\n\nGenericARC4StaticArrayType: typing.Final = _GenericType(\n name=\"algopy.arc4.StaticArray\",\n parameterise=_parameterise_arc4_static_array,\n)\nARC4AddressType: typing.Final = _register_builtin(\n ArrayType(\n name=\"algopy.arc4.Address\",\n wtype=wtypes.arc4_address_alias,\n size=32,\n generic=None,\n items=ARC4ByteType,\n items_wtype=ARC4ByteType.wtype,\n bases=[\n GenericARC4StaticArrayType.parameterise(\n [ARC4ByteType, TypingLiteralType(value=32, source_location=None)],\n source_location=None,\n )\n ],\n mro=[\n GenericARC4StaticArrayType.parameterise(\n [ARC4ByteType, TypingLiteralType(value=32, source_location=None)],\n source_location=None,\n )\n ],\n )\n)\n\n\ndef _make_storage_parameterise(wtype: wtypes.WType) -> _Parameterise[StorageProxyType]:\n def parameterise(\n self: _GenericType[StorageProxyType],\n args: _TypeArgs,\n source_location: SourceLocation | None,\n ) -> StorageProxyType:\n try:\n (arg,) = args\n except ValueError:\n raise CodeError(\n f\"expected a single type parameter, got {len(args)} parameters\", source_location\n ) from None\n name = f\"{self.name}[{arg.name}]\"\n content_wtype = arg.checked_wtype(source_location)\n return StorageProxyType(\n generic=self,\n name=name,\n content=arg,\n wtype=wtype,\n content_wtype=content_wtype,\n )\n\n return parameterise\n\n\ndef _parameterise_storage_map(\n self: _GenericType[StorageMapProxyType],\n args: _TypeArgs,\n source_location: SourceLocation | None,\n) -> StorageMapProxyType:\n try:\n key, content = args\n except ValueError:\n raise CodeError(\n f\"expected two type parameters, got {len(args)} parameters\", source_location\n ) from None\n name = f\"{self.name}[{key.name}, {content.name}]\"\n key_wtype = key.checked_wtype(source_location)\n content_wtype = content.checked_wtype(source_location)\n return StorageMapProxyType(\n generic=self,\n name=name,\n key=key,\n content=content,\n wtype=wtypes.box_key,\n key_wtype=key_wtype,\n content_wtype=content_wtype,\n )\n\n\nGenericGlobalStateType: typing.Final = _GenericType(\n name=\"algopy._state.GlobalState\",\n parameterise=_make_storage_parameterise(wtypes.state_key),\n)\nGenericLocalStateType: typing.Final = _GenericType(\n name=\"algopy._state.LocalState\",\n parameterise=_make_storage_parameterise(wtypes.state_key),\n)\nGenericBoxType: typing.Final = _GenericType(\n name=\"algopy._box.Box\",\n parameterise=_make_storage_parameterise(wtypes.box_key),\n)\nBoxRefType: typing.Final = _register_builtin(\n StorageProxyType(\n name=\"algopy._box.BoxRef\",\n content=BytesType,\n content_wtype=BytesType.wtype,\n wtype=wtypes.box_key,\n generic=None,\n )\n)\n\nGenericBoxMapType: typing.Final = _GenericType(\n name=\"algopy._box.BoxMap\",\n parameterise=_parameterise_storage_map,\n)\n\n\n@attrs.frozen(order=False)\nclass TransactionRelatedType(PyType, abc.ABC):\n transaction_type: TransactionType | None\n \"\"\"None implies \"any\" type, which may be considered as either union or an intersection\"\"\"\n\n def __attrs_post_init__(self) -> None:\n _register_builtin(self)\n\n\n@typing.final\n@attrs.frozen(order=False)\nclass GroupTransactionType(TransactionRelatedType):\n wtype: wtypes.WGroupTransaction\n\n\n@typing.final\n@attrs.frozen(order=False)\nclass InnerTransactionFieldsetType(TransactionRelatedType):\n wtype: wtypes.WInnerTransactionFields\n\n\n@typing.final\n@attrs.frozen(order=False)\nclass InnerTransactionResultType(TransactionRelatedType):\n wtype: wtypes.WInnerTransaction\n\n\nGroupTransactionBaseType: typing.Final = GroupTransactionType(\n name=\"algopy.gtxn.TransactionBase\",\n wtype=wtypes.WGroupTransaction(name=\"group_transaction_base\", transaction_type=None),\n transaction_type=None,\n)\n\n\ndef _make_gtxn_type(kind: TransactionType | None) -> GroupTransactionType:\n if kind is None:\n cls_name = \"Transaction\"\n else:\n cls_name = f\"{_TXN_TYPE_NAMES[kind]}Transaction\"\n stub_name = f\"algopy.gtxn.{cls_name}\"\n return GroupTransactionType(\n name=stub_name,\n transaction_type=kind,\n wtype=wtypes.WGroupTransaction.from_type(kind),\n bases=[GroupTransactionBaseType],\n mro=[GroupTransactionBaseType],\n )\n\n\ndef _make_itxn_fieldset_type(kind: TransactionType | None) -> InnerTransactionFieldsetType:\n if kind is None:\n cls_name = \"InnerTransaction\"\n else:\n cls_name = _TXN_TYPE_NAMES[kind]\n stub_name = f\"algopy.itxn.{cls_name}\"\n return InnerTransactionFieldsetType(\n name=stub_name,\n transaction_type=kind,\n wtype=wtypes.WInnerTransactionFields.from_type(kind),\n )\n\n\ndef _make_itxn_result_type(kind: TransactionType | None) -> InnerTransactionResultType:\n if kind is None:\n cls_name = \"InnerTransactionResult\"\n else:\n cls_name = f\"{_TXN_TYPE_NAMES[kind]}InnerTransaction\"\n stub_name = f\"algopy.itxn.{cls_name}\"\n return InnerTransactionResultType(\n name=stub_name,\n transaction_type=kind,\n wtype=wtypes.WInnerTransaction.from_type(kind),\n )\n\n\n_TXN_TYPE_NAMES: typing.Final[Mapping[TransactionType, str]] = {\n TransactionType.pay: \"Payment\",\n TransactionType.keyreg: \"KeyRegistration\",\n TransactionType.acfg: \"AssetConfig\",\n TransactionType.axfer: \"AssetTransfer\",\n TransactionType.afrz: \"AssetFreeze\",\n TransactionType.appl: \"ApplicationCall\",\n}\n\n_all_txn_kinds: typing.Final[Sequence[TransactionType | None]] = [\n None,\n *TransactionType,\n]\nGroupTransactionTypes: typing.Final[Mapping[TransactionType | None, GroupTransactionType]] = {\n kind: _make_gtxn_type(kind) for kind in _all_txn_kinds\n}\nInnerTransactionFieldsetTypes: typing.Final[\n Mapping[TransactionType | None, InnerTransactionFieldsetType]\n] = {kind: _make_itxn_fieldset_type(kind) for kind in _all_txn_kinds}\nInnerTransactionResultTypes: typing.Final[\n Mapping[TransactionType | None, InnerTransactionResultType]\n] = {kind: _make_itxn_result_type(kind) for kind in _all_txn_kinds}\n\n\n@attrs.frozen(kw_only=True, order=False)\nclass _CompileTimeType(PyType):\n _wtype_error: str\n\n @typing.override\n @property\n def wtype(self) -> ErrorMessage:\n msg = self._wtype_error.format(self=self)\n return ErrorMessage(msg)\n\n def __attrs_post_init__(self) -> None:\n _register_builtin(self)\n\n\nBytesBackedType: typing.Final[PyType] = _CompileTimeType(\n name=\"algopy._primitives.BytesBacked\",\n wtype_error=\"{self} is not usable as a runtime type\",\n)\n\n\n@attrs.frozen(kw_only=True, order=False)\nclass IntrinsicEnumType(PyType):\n generic: None = attrs.field(default=None, init=False)\n bases: tuple[PyType, ...] = attrs.field(\n default=(StrLiteralType,), # strictly true, but not sure if we want this?\n init=False,\n )\n mro: tuple[PyType, ...] = attrs.field(default=(StrLiteralType,), init=False)\n members: immutabledict[str, str] = attrs.field(converter=immutabledict)\n\n @property\n def wtype(self) -> ErrorMessage:\n return ErrorMessage(f\"{self} is only valid as a literal argument to an algopy.op function\")\n\n\ndef _make_intrinsic_enum_types() -> Sequence[IntrinsicEnumType]:\n from puyapy.awst_build.intrinsic_data import ENUM_CLASSES\n\n return [\n _register_builtin(\n IntrinsicEnumType(\n name=\"\".join((constants.ALGOPY_OP_PREFIX, cls_name)),\n members=cls_members,\n )\n )\n for cls_name, cls_members in ENUM_CLASSES.items()\n ]\n\n\n@attrs.frozen(kw_only=True, order=False)\nclass IntrinsicNamespaceType(PyType):\n generic: None = attrs.field(default=None, init=False)\n bases: tuple[PyType, ...] = attrs.field(default=(), init=False)\n mro: tuple[PyType, ...] = attrs.field(default=(), init=False)\n members: immutabledict[str, PropertyOpMapping | OpMappingWithOverloads] = attrs.field(\n converter=immutabledict\n )\n\n @property\n def wtype(self) -> ErrorMessage:\n return ErrorMessage(f\"{self} is a namespace type only and not usable at runtime\")\n\n\ndef _make_intrinsic_namespace_types() -> Sequence[IntrinsicNamespaceType]:\n from puyapy.awst_build.intrinsic_data import NAMESPACE_CLASSES\n\n return [\n _register_builtin(\n IntrinsicNamespaceType(\n name=\"\".join((constants.ALGOPY_OP_PREFIX, cls_name)),\n members=cls_members,\n )\n )\n for cls_name, cls_members in NAMESPACE_CLASSES.items()\n ]\n\n\nOpEnumTypes: typing.Final = _make_intrinsic_enum_types()\nOpNamespaceTypes: typing.Final = _make_intrinsic_namespace_types()\n\nStateTotalsType: typing.Final[PyType] = _CompileTimeType(\n name=\"algopy._contract.StateTotals\",\n wtype_error=\"{self} is only usable in a class options context\",\n)\n\nurangeType: typing.Final[PyType] = _CompileTimeType( # noqa: N816\n name=constants.URANGE,\n wtype_error=\"{self} is not usable at runtime\",\n)\n\n\ndef _parameterise_any_compile_time(\n self: _GenericType,\n args: _TypeArgs,\n source_location: SourceLocation | None, # noqa: ARG001\n) -> PyType:\n arg_names = [arg.name for arg in args]\n name = f\"{self.name}[{', '.join(arg_names)}]\"\n return _CompileTimeType(name=name, generic=self, wtype_error=\"{self} is not usable at runtime\")\n\n\nreversedGenericType: typing.Final[PyType] = _GenericType( # noqa: N816\n name=\"builtins.reversed\",\n parameterise=_parameterise_any_compile_time,\n)\nuenumerateGenericType: typing.Final[PyType] = _GenericType( # noqa: N816\n name=\"algopy._unsigned_builtins.uenumerate\",\n parameterise=_parameterise_any_compile_time,\n)\n\n\nLogicSigType: typing.Final[PyType] = _CompileTimeType(\n name=\"algopy._logic_sig.LogicSig\",\n wtype_error=\"{self} is only usable in a static context\",\n)\n\n\nContractBaseType: typing.Final[PyType] = _BaseType(name=constants.CONTRACT_BASE)\nARC4ContractBaseType: typing.Final[PyType] = _BaseType(\n name=constants.ARC4_CONTRACT_BASE,\n bases=[ContractBaseType],\n mro=[ContractBaseType],\n)\nARC4ClientBaseType: typing.Final[PyType] = _BaseType(name=\"algopy.arc4.ARC4Client\")\nARC4StructBaseType: typing.Final[PyType] = _BaseType(name=\"algopy.arc4.Struct\")\nStructBaseType: typing.Final[PyType] = _BaseType(name=\"algopy._struct.Struct\")\n\n\n@typing.final\n@attrs.frozen(order=False)\nclass PseudoGenericFunctionType(PyType):\n return_type: PyType\n generic: _GenericType[PseudoGenericFunctionType]\n bases: tuple[PyType, ...] = attrs.field(default=(), init=False)\n mro: tuple[PyType, ...] = attrs.field(default=(), init=False)\n\n @property\n def wtype(self) -> ErrorMessage:\n return ErrorMessage(f\"{self} is not a value\")\n\n\ndef _parameterise_pseudo_generic_function_type(\n self: _GenericType[PseudoGenericFunctionType],\n args: _TypeArgs,\n source_location: SourceLocation | None,\n) -> PseudoGenericFunctionType:\n try:\n (arg,) = args\n except ValueError:\n raise CodeError(\n f\"expected a single type parameter, got {len(args)} parameters\", source_location\n ) from None\n name = f\"{self.name}[{arg.name}]\"\n return PseudoGenericFunctionType(generic=self, name=name, return_type=arg)\n\n\nGenericABICallWithReturnType: typing.Final[PyType] = _GenericType(\n name=\"algopy.arc4._ABICallWithReturnProtocol\",\n parameterise=_parameterise_pseudo_generic_function_type,\n)\nGenericTemplateVarType: typing.Final[PyType] = _GenericType(\n name=\"algopy._template_variables._TemplateVarMethod\",\n parameterise=_parameterise_pseudo_generic_function_type,\n)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/pytypes.py","language":"Python","license":"NOASSERTION","size":40461} {"code":"import abc\nimport typing\nfrom collections.abc import Callable, Sequence\n\nimport attrs\nimport mypy.nodes\nimport mypy.patterns\nimport mypy.types\nimport mypy.visitor\n\nfrom puya import log\nfrom puya.awst.nodes import (\n AppStateExpression,\n AppStorageDefinition,\n ARC4MethodConfig,\n AssertExpression,\n AssignmentExpression,\n AssignmentStatement,\n BinaryBooleanOperator,\n Block,\n BooleanBinaryOperation,\n BytesConstant,\n BytesEncoding,\n ConditionalExpression,\n ContractMethod,\n Expression,\n ExpressionStatement,\n ForInLoop,\n Goto,\n IfElse,\n InstanceSuperMethodTarget,\n Label,\n LoopContinue,\n LoopExit,\n Lvalue,\n ReturnStatement,\n Statement,\n Subroutine,\n SubroutineArgument,\n SubroutineID,\n Switch,\n VarExpression,\n WhileLoop,\n)\nfrom puya.errors import CodeError, InternalError\nfrom puya.parse import SourceLocation\nfrom puya.program_refs import ContractReference, LogicSigReference\nfrom puyapy.awst_build import constants, pytypes\nfrom puyapy.awst_build.base_mypy_visitor import BaseMyPyExpressionVisitor, BaseMyPyStatementVisitor\nfrom puyapy.awst_build.context import ASTConversionModuleContext\nfrom puyapy.awst_build.eb import _expect as expect\nfrom puyapy.awst_build.eb._literals import LiteralBuilderImpl\nfrom puyapy.awst_build.eb.arc4 import ARC4ClientTypeBuilder\nfrom puyapy.awst_build.eb.conditional_literal import ConditionalLiteralBuilder\nfrom puyapy.awst_build.eb.contracts import (\n ContractSelfExpressionBuilder,\n ContractTypeExpressionBuilder,\n)\nfrom puyapy.awst_build.eb.dict_ import DictLiteralBuilder\nfrom puyapy.awst_build.eb.factories import (\n builder_for_instance,\n builder_for_type,\n try_get_builder_for_func,\n)\nfrom puyapy.awst_build.eb.interface import (\n BuilderBinaryOp,\n BuilderComparisonOp,\n BuilderUnaryOp,\n CallableBuilder,\n InstanceBuilder,\n LiteralBuilder,\n NodeBuilder,\n StorageProxyConstructorResult,\n)\nfrom puyapy.awst_build.eb.logicsig import LogicSigExpressionBuilder\nfrom puyapy.awst_build.eb.none import NoneTypeBuilder\nfrom puyapy.awst_build.eb.subroutine import SubroutineInvokerExpressionBuilder\nfrom puyapy.awst_build.utils import (\n extract_bytes_literal_from_mypy,\n get_decorators_by_fullname,\n get_unaliased_fullname,\n maybe_resolve_literal,\n require_callable_type,\n)\nfrom puyapy.models import ContractFragmentBase\nfrom puyapy.parse import parse_docstring\n\nlogger = log.get_logger(__name__)\n\n\n@attrs.frozen\nclass ContractMethodInfo:\n fragment: ContractFragmentBase\n contract_type: pytypes.ContractType\n is_abstract: bool\n arc4_method_config: ARC4MethodConfig | None\n\n\nclass ExpressionASTConverter(BaseMyPyExpressionVisitor[NodeBuilder], abc.ABC):\n @abc.abstractmethod\n def resolve_local_type(\n self, var_name: str, expr_loc: SourceLocation\n ) -> pytypes.PyType | None: ...\n\n @abc.abstractmethod\n def builder_for_self(self, expr_loc: SourceLocation) -> NodeBuilder: ...\n\n # Expressions\n def _visit_ref_expr(self, expr: mypy.nodes.MemberExpr | mypy.nodes.NameExpr) -> NodeBuilder:\n expr_loc = self._location(expr)\n # Do a straight forward lookup at the RefExpr level handle the cases of:\n # - type aliases\n # - simple (non-generic) types\n # - generic type that has not been parameterised\n # (e.g. when calling a constructor which can infer the type from its arguments)\n # For parameterised generics, these are resolved at the IndexExpr level, without\n # descending into IndexExpr.base.\n # By doing a simple lookup instead of resolving the PyType of expr,\n # we can side step complex constructs in the stubs that we don't support in user code,\n # such as overloads.\n if py_typ := self.context.lookup_pytype(expr.fullname):\n if isinstance(py_typ, pytypes.ContractType):\n if fragment := self.context.contract_fragments.get(py_typ.name):\n return ContractTypeExpressionBuilder(py_typ, fragment, expr_loc)\n elif pytypes.ARC4ClientBaseType < py_typ: # provides type info only\n if fragment := self.context.contract_fragments.get(ContractReference(py_typ.name)):\n return ARC4ClientTypeBuilder(py_typ, expr_loc, fragment)\n elif py_typ == pytypes.LogicSigType:\n ref = LogicSigReference(get_unaliased_fullname(expr))\n return LogicSigExpressionBuilder(ref, expr_loc)\n else:\n return builder_for_type(py_typ, expr_loc)\n\n if expr.name == \"__all__\":\n # special case here, we allow __all__ at the module level for it's \"public vs private\"\n # control implications w.r.t linting etc, but we do so by ignoring it.\n # so this is here just in case someone tries to reference __all__ inside a function,\n # to give a more useful error message.\n raise CodeError(\"__all__ cannot be referenced inside functions\", expr_loc)\n\n fullname = get_unaliased_fullname(expr)\n if fullname.startswith(\"builtins.\"):\n return self._visit_ref_expr_of_builtins(fullname, expr_loc)\n if func_builder := try_get_builder_for_func(fullname, expr_loc):\n return func_builder\n match expr:\n case mypy.nodes.NameExpr(node=mypy.nodes.Var(is_self=True)):\n return self.builder_for_self(expr_loc)\n case mypy.nodes.RefExpr(\n node=mypy.nodes.Decorator() as dec\n ) if constants.SUBROUTINE_HINT in get_decorators_by_fullname(self.context, dec):\n self._precondition(\n expr.fullname != expr.name,\n \"unqualified name found in call to function\",\n expr_loc,\n )\n mypy_func_type = require_callable_type(dec, expr_loc)\n func_type = self.context.type_to_pytype(mypy_func_type, source_location=expr_loc)\n if not isinstance(func_type, pytypes.FuncType):\n raise CodeError(\"decorated function has non-function type\", expr_loc)\n return SubroutineInvokerExpressionBuilder(\n target=SubroutineID(expr.fullname),\n func_type=func_type,\n location=expr_loc,\n )\n case mypy.nodes.RefExpr(node=mypy.nodes.FuncDef()):\n raise CodeError(\n f\"Cannot invoke {fullname} as it is not \"\n f\"decorated with {constants.SUBROUTINE_HINT_ALIAS}\",\n expr_loc,\n )\n # TODO: is this enough to filter to only global variable references?\n # it seems like it should be...\n case mypy.nodes.RefExpr(kind=mypy.nodes.GDEF, node=mypy.nodes.Var()):\n self._precondition(\n not (\n expr.is_new_def\n or expr.is_inferred_def\n or expr.is_alias_rvalue\n or (isinstance(expr, mypy.nodes.NameExpr) and expr.is_special_form)\n ),\n \"global variable reference with unexpected flags\",\n expr_loc,\n )\n try:\n constant_value = self.context.constants[expr.fullname]\n except KeyError as ex:\n raise CodeError(\n \"Unable to resolve global constant reference\", expr_loc\n ) from ex\n else:\n return LiteralBuilderImpl(source_location=expr_loc, value=constant_value)\n case (\n mypy.nodes.NameExpr(\n kind=mypy.nodes.LDEF, node=mypy.nodes.Var(), name=var_name\n ) as name_expr\n ):\n self._precondition(\n not name_expr.is_special_form,\n \"special form lvalues should only appear\"\n \" as a singular lvalue in an assignment statement\",\n expr_loc,\n )\n local_type = self.resolve_local_type(var_name, expr_loc)\n if local_type is None:\n raise CodeError(\n \"local variable type is unknown - possible use before definition?\",\n expr_loc,\n )\n var_expr = VarExpression(\n name=var_name,\n wtype=local_type.checked_wtype(expr_loc),\n source_location=expr_loc,\n )\n return builder_for_instance(local_type, var_expr)\n scope = {\n mypy.nodes.LDEF: \"local\",\n mypy.nodes.MDEF: \"member\",\n mypy.nodes.GDEF: \"global\",\n None: \"unknown\",\n }.get(expr.kind)\n # this can happen in otherwise well-formed code that is just missing a reference\n raise CodeError(\n f\"Unable to resolve reference to {expr.fullname or expr.name!r}, {scope=}\",\n expr_loc,\n )\n\n @staticmethod\n def _visit_ref_expr_of_builtins(fullname: str, location: SourceLocation) -> NodeBuilder:\n assert fullname.startswith(\"builtins.\")\n rest_of_name = fullname.removeprefix(\"builtins.\")\n match rest_of_name:\n case \"True\":\n return LiteralBuilderImpl(source_location=location, value=True)\n case \"False\":\n return LiteralBuilderImpl(source_location=location, value=False)\n case \"None\":\n raise CodeError(\"None is not supported as a value, only a return type\", location)\n case \"len\":\n raise CodeError(\n \"len() is not supported -\"\n \" types with a length will have a .length property instead\",\n location,\n )\n case \"range\":\n raise CodeError(\"range() is not supported - use algopy.urange() instead\", location)\n case \"enumerate\":\n raise CodeError(\n \"enumerate() is not supported - use algopy.uenumerate() instead\", location\n )\n case _:\n raise CodeError(f\"Unsupported builtin: {rest_of_name}\", location)\n\n @typing.override\n def visit_name_expr(self, expr: mypy.nodes.NameExpr) -> NodeBuilder:\n return self._visit_ref_expr(expr)\n\n @typing.override\n def visit_member_expr(self, expr: mypy.nodes.MemberExpr) -> NodeBuilder:\n expr_loc = self._location(expr)\n if isinstance(expr.expr, mypy.nodes.RefExpr) and isinstance(\n expr.expr.node, mypy.nodes.MypyFile\n ):\n # special case for module attribute access\n return self._visit_ref_expr(expr)\n\n base = expr.expr.accept(self)\n return base.member_access(expr.name, expr_loc)\n\n @typing.override\n def visit_call_expr(self, call: mypy.nodes.CallExpr) -> NodeBuilder:\n if call.analyzed is not None:\n return self._visit_special_call_expr(call, analyzed=call.analyzed)\n\n callee = call.callee.accept(self)\n if not isinstance(callee, CallableBuilder):\n raise CodeError(\"not a callable expression\", self._location(call.callee))\n\n args = [arg.accept(self) for arg in call.args]\n return callee.call(\n args=args,\n arg_kinds=call.arg_kinds,\n arg_names=call.arg_names,\n location=self._location(call),\n )\n\n def _visit_special_call_expr(\n self, call: mypy.nodes.CallExpr, *, analyzed: mypy.nodes.Expression\n ) -> NodeBuilder:\n match analyzed:\n case mypy.nodes.CastExpr(expr=inner_expr):\n self.context.warning(\n \"use of typing.cast, output may be invalid or insecure TEAL\", call\n )\n case mypy.nodes.AssertTypeExpr(expr=inner_expr):\n # just FYI... in case the user thinks this has a runtime effect\n # (it doesn't, not even in Python)\n self.context.warning(\n \"use of typing.assert_type has no effect on compilation\", call\n )\n case mypy.nodes.RevealExpr(expr=mypy.nodes.Expression() as inner_expr):\n pass\n case _:\n raise CodeError(\n f\"Unsupported special function call\"\n f\" of analyzed type {type(analyzed).__name__}\",\n self._location(call),\n )\n\n return inner_expr.accept(self)\n\n @typing.override\n def visit_unary_expr(self, node: mypy.nodes.UnaryExpr) -> NodeBuilder:\n expr_loc = self._location(node)\n builder_or_literal = node.expr.accept(self)\n match node.op:\n case \"not\":\n return builder_or_literal.bool_eval(expr_loc, negate=True)\n case op_str if op_str in BuilderUnaryOp:\n builder_op = BuilderUnaryOp(op_str)\n return require_instance_builder(builder_or_literal).unary_op(builder_op, expr_loc)\n case _:\n # guard against future python unary operators\n raise InternalError(f\"Unable to interpret unary operator '{node.op}'\", expr_loc)\n\n @typing.override\n def visit_op_expr(self, node: mypy.nodes.OpExpr) -> NodeBuilder:\n node_loc = self._location(node)\n lhs = require_instance_builder(node.left.accept(self))\n rhs = require_instance_builder(node.right.accept(self))\n\n # mypy combines ast.BoolOp and ast.BinOp, but they're kinda different...\n if node.op in BinaryBooleanOperator:\n bool_op = BinaryBooleanOperator(node.op)\n return lhs.bool_binary_op(rhs, bool_op, node_loc)\n\n try:\n op = BuilderBinaryOp(node.op)\n except ValueError as ex:\n raise InternalError(f\"Unknown binary operator: {node.op}\") from ex\n\n result: NodeBuilder = NotImplemented\n if isinstance(lhs, NodeBuilder):\n result = lhs.binary_op(other=rhs, op=op, location=node_loc, reverse=False)\n if result is NotImplemented and isinstance(rhs, NodeBuilder):\n result = rhs.binary_op(other=lhs, op=op, location=node_loc, reverse=True)\n if result is NotImplemented:\n raise CodeError(f\"unsupported operation {op.value} between types\", node_loc)\n return result\n\n @typing.override\n def visit_index_expr(self, expr: mypy.nodes.IndexExpr) -> NodeBuilder:\n expr_location = self._location(expr)\n if isinstance(expr.method_type, mypy.types.CallableType):\n result_pytyp = self.context.type_to_pytype(\n expr.method_type.ret_type, source_location=expr_location\n )\n if isinstance(result_pytyp, pytypes.PseudoGenericFunctionType):\n return builder_for_type(result_pytyp, expr_location)\n match expr.analyzed:\n case None:\n pass\n case mypy.nodes.TypeAliasExpr():\n raise CodeError(\"type aliases are not supported inside subroutines\", expr_location)\n case mypy.nodes.TypeApplication(types=type_args):\n # TODO: resolve expr to generic type builder instead\n assert isinstance(\n expr.base, mypy.nodes.RefExpr\n ), \"expect base of type application to be RefExpr\"\n pytyp = self.context.lookup_pytype(expr.base.fullname)\n if pytyp is None:\n raise CodeError(\"unknown base type\", expr_location)\n param_typ = pytyp.parameterise(\n [\n self.context.type_to_pytype(\n t, in_type_args=True, source_location=expr_location\n )\n for t in type_args\n ],\n expr_location,\n )\n return builder_for_type(param_typ, expr_location)\n case _:\n typing.assert_never(expr.analyzed)\n\n base_builder = require_instance_builder(expr.base.accept(self))\n match expr.index:\n # special case handling of SliceExpr, so we don't need to handle slice Literal's\n # or some such everywhere\n # TODO: SliceBuilder?\n case mypy.nodes.SliceExpr(begin_index=begin, end_index=end, stride=stride):\n return base_builder.slice_index(\n begin_index=(require_instance_builder(begin.accept(self)) if begin else None),\n end_index=(require_instance_builder(end.accept(self)) if end else None),\n stride=(require_instance_builder(stride.accept(self)) if stride else None),\n location=expr_location,\n )\n\n index_builder = require_instance_builder(expr.index.accept(self))\n return base_builder.index(index=index_builder, location=expr_location)\n\n @typing.override\n def visit_conditional_expr(self, expr: mypy.nodes.ConditionalExpr) -> NodeBuilder:\n expr_loc = self._location(expr)\n condition = expr.cond.accept(self).bool_eval(self._location(expr.cond))\n true_b = require_instance_builder(expr.if_expr.accept(self))\n false_b = require_instance_builder(expr.else_expr.accept(self))\n if true_b.pytype <= false_b.pytype:\n expr_pytype = true_b.pytype\n elif false_b.pytype < true_b.pytype:\n expr_pytype = false_b.pytype\n else:\n raise CodeError(\n \"incompatible result types for 'true' and 'false' expressions\", expr_loc\n )\n\n if (\n isinstance(expr_pytype, pytypes.LiteralOnlyType)\n and isinstance(true_b, LiteralBuilder)\n and isinstance(false_b, LiteralBuilder)\n ):\n return ConditionalLiteralBuilder(\n true_literal=true_b,\n false_literal=false_b,\n condition=condition,\n location=expr_loc,\n )\n else:\n cond_expr = ConditionalExpression(\n condition=condition.resolve(),\n true_expr=true_b.resolve(),\n false_expr=false_b.resolve(),\n source_location=expr_loc,\n )\n return builder_for_instance(expr_pytype, cond_expr)\n\n @typing.override\n def visit_comparison_expr(self, expr: mypy.nodes.ComparisonExpr) -> NodeBuilder:\n from puyapy.awst_build.eb.bool import BoolExpressionBuilder\n\n expr_loc = self._location(expr)\n self._precondition(\n len(expr.operands) == (len(expr.operators) + 1),\n \"operands don't match with operators\",\n expr_loc,\n )\n # we can decompose this into a series of AND operations, but potentially need to generate\n # assignment expressions for everything except first and last operands, e.g.:\n # a < b < c\n # becomes:\n # (a < (tmp := b)) AND (tmp < c)\n # TODO: what about comparing different types that can never be equal? according to Python\n # type signatures that should be possible, and we can always know it's value at\n # compile time, but it would always result in a constant ...\n\n operands = [require_instance_builder(o.accept(self)) for o in expr.operands]\n operands[1:-1] = [operand.single_eval() for operand in list(operands)[1:-1]]\n\n comparisons = [\n self._build_compare(operator=operator, lhs=lhs, rhs=rhs).resolve()\n for operator, lhs, rhs in zip(expr.operators, operands, operands[1:], strict=False)\n ]\n\n result = prev = comparisons[0]\n for curr in comparisons[1:]:\n result = BooleanBinaryOperation(\n left=result,\n op=BinaryBooleanOperator.and_,\n right=curr,\n source_location=prev.source_location.try_merge(curr.source_location),\n )\n prev = curr\n return BoolExpressionBuilder(result)\n\n @staticmethod\n def _build_compare(\n operator: str, lhs: InstanceBuilder, rhs: InstanceBuilder\n ) -> InstanceBuilder:\n cmp_loc = lhs.source_location.try_merge(rhs.source_location)\n match operator:\n case \"not in\":\n return rhs.contains(lhs, cmp_loc).bool_eval(cmp_loc, negate=True)\n case \"in\":\n return rhs.contains(lhs, cmp_loc)\n\n result: InstanceBuilder = NotImplemented\n op = BuilderComparisonOp(operator)\n if isinstance(lhs, NodeBuilder):\n result = lhs.compare(other=rhs, op=op, location=cmp_loc)\n if result is NotImplemented and isinstance(rhs, NodeBuilder):\n result = rhs.compare(other=lhs, op=op.reversed(), location=cmp_loc)\n if result is NotImplemented:\n raise CodeError(f\"unsupported comparison {operator!r} between types\", cmp_loc)\n return result\n\n @typing.override\n def visit_int_expr(self, expr: mypy.nodes.IntExpr) -> LiteralBuilder:\n return LiteralBuilderImpl(value=expr.value, source_location=self._location(expr))\n\n @typing.override\n def visit_str_expr(self, expr: mypy.nodes.StrExpr) -> LiteralBuilder:\n return LiteralBuilderImpl(value=expr.value, source_location=self._location(expr))\n\n @typing.override\n def visit_bytes_expr(self, expr: mypy.nodes.BytesExpr) -> LiteralBuilder:\n bytes_const = extract_bytes_literal_from_mypy(expr)\n return LiteralBuilderImpl(value=bytes_const, source_location=self._location(expr))\n\n @typing.override\n def visit_tuple_expr(self, mypy_expr: mypy.nodes.TupleExpr) -> NodeBuilder:\n from puyapy.awst_build.eb.tuple import TupleLiteralBuilder\n\n location = self._location(mypy_expr)\n item_builders = [\n require_instance_builder(mypy_item.accept(self)) for mypy_item in mypy_expr.items\n ]\n return TupleLiteralBuilder(item_builders, location)\n\n @typing.override\n def visit_dict_expr(self, expr: mypy.nodes.DictExpr) -> NodeBuilder:\n location = self._location(expr)\n mappings = dict[str, InstanceBuilder]()\n for mypy_name, mypy_value in expr.items:\n if mypy_name is None:\n logger.error(\"None is not usable as a value\", location=location)\n continue\n key_node = mypy_name.accept(self)\n value_node = mypy_value.accept(self)\n key = expect.simple_string_literal(key_node, default=expect.default_none)\n value = require_instance_builder(value_node)\n if key is not None:\n mappings[key] = value\n return DictLiteralBuilder(mappings, location)\n\n # unsupported expressions\n\n def visit_list_comprehension(self, expr: mypy.nodes.ListComprehension) -> NodeBuilder:\n raise CodeError(\"List comprehensions are not supported\", self._location(expr))\n\n def visit_slice_expr(self, expr: mypy.nodes.SliceExpr) -> NodeBuilder:\n raise CodeError(\"Slices are not supported outside of indexing\", self._location(expr))\n\n def visit_lambda_expr(self, expr: mypy.nodes.LambdaExpr) -> NodeBuilder:\n raise CodeError(\"lambda functions are not supported\", self._location(expr))\n\n def visit_ellipsis(self, expr: mypy.nodes.EllipsisExpr) -> NodeBuilder:\n raise CodeError(\"ellipsis expressions are not supported\", self._location(expr))\n\n def visit_list_expr(self, expr: mypy.nodes.ListExpr) -> NodeBuilder:\n raise CodeError(\"Python lists are not supported\", self._location(expr))\n\n\nclass FunctionASTConverter(\n BaseMyPyStatementVisitor[Statement | Sequence[Statement] | None],\n ExpressionASTConverter,\n):\n def __init__(\n self,\n context: ASTConversionModuleContext,\n func_def: mypy.nodes.FuncDef,\n contract_method_info: ContractMethodInfo | None,\n source_location: SourceLocation,\n *,\n inline: bool | None,\n ):\n super().__init__(context=context)\n func_loc = context.node_location(func_def) # TODO: why not source_location ??\n self.contract_method_info = contract_method_info\n self.func_def = func_def\n self._precondition(\n not func_def.is_trivial_body,\n \"trivial functions should be skipped at a higher level\",\n func_loc,\n )\n type_info = func_def.type\n self._precondition(\n isinstance(type_info, mypy.types.CallableType),\n \"should only receive functions\/methods with a type of CallableType\",\n func_loc,\n )\n assert isinstance(type_info, mypy.types.CallableType)\n self._precondition(\n len(type_info.arg_types) == len(func_def.arguments),\n \"FuncDef argument type list length should match arguments list length\",\n func_loc,\n )\n self._break_label_stack = list[Label | None]()\n # convert the return type\n self._return_type = context.type_to_pytype(type_info.ret_type, source_location=func_loc)\n return_wtype = self._return_type.checked_wtype(func_loc)\n # check & convert the arguments\n mypy_args = func_def.arguments\n mypy_arg_types = type_info.arg_types\n if type_info.def_extras.get(\"first_arg\"):\n # function is a method\n if not mypy_args:\n logger.error(\"method declaration is missing 'self' argument\", location=func_loc)\n else:\n self._precondition(\n mypy_args[0].variable.is_self,\n \"if function is a method, first variable should be self-like\",\n func_loc,\n )\n mypy_args = mypy_args[1:]\n mypy_arg_types = mypy_arg_types[1:]\n elif mypy_args:\n self._precondition(\n not mypy_args[0].variable.is_self,\n \"if function is not a method, first variable should be self-like\",\n func_loc,\n )\n self._symtable = dict[str, pytypes.PyType]()\n args = list[SubroutineArgument]()\n for arg, arg_type in zip(mypy_args, mypy_arg_types, strict=True):\n arg_loc = context.node_location(arg)\n if arg.kind.is_star():\n raise CodeError(\"variadic functions are not supported\", arg_loc)\n if arg.initializer is not None:\n context.error(\n \"default function argument values are not supported yet\", arg.initializer\n )\n pytyp = context.type_to_pytype(arg_type, source_location=arg_loc)\n wtype = pytyp.checked_wtype(arg_loc)\n arg_name = arg.variable.name\n args.append(SubroutineArgument(name=arg_name, wtype=wtype, source_location=arg_loc))\n self._symtable[arg_name] = pytyp\n # translate body\n translated_body = self.visit_block(func_def.body)\n # build result\n self.result: Subroutine | ContractMethod\n documentation = parse_docstring(func_def.docstring)\n if contract_method_info is None:\n self.result = Subroutine(\n id=func_def.fullname,\n name=func_def.name,\n source_location=source_location,\n args=args,\n return_type=return_wtype,\n body=translated_body,\n documentation=documentation,\n inline=inline,\n )\n else:\n self.result = ContractMethod(\n cref=contract_method_info.fragment.id,\n member_name=func_def.name,\n source_location=source_location,\n args=args,\n return_type=return_wtype,\n body=translated_body,\n documentation=documentation,\n arc4_method_config=contract_method_info.arc4_method_config,\n inline=inline,\n )\n\n @classmethod\n @typing.overload\n def convert(\n cls,\n context: ASTConversionModuleContext,\n func_def: mypy.nodes.FuncDef,\n source_location: SourceLocation,\n *,\n inline: bool | None,\n ) -> Subroutine: ...\n\n @classmethod\n @typing.overload\n def convert(\n cls,\n context: ASTConversionModuleContext,\n func_def: mypy.nodes.FuncDef,\n source_location: SourceLocation,\n contract_method_info: ContractMethodInfo,\n *,\n inline: bool | None,\n ) -> ContractMethod: ...\n\n @classmethod\n def convert(\n cls,\n context: ASTConversionModuleContext,\n func_def: mypy.nodes.FuncDef,\n source_location: SourceLocation,\n contract_method_info: ContractMethodInfo | None = None,\n *,\n inline: bool | None,\n ) -> Subroutine | ContractMethod:\n return cls(\n context=context,\n func_def=func_def,\n contract_method_info=contract_method_info,\n inline=inline,\n source_location=source_location,\n ).result\n\n @typing.override\n def builder_for_self(self, expr_loc: SourceLocation) -> NodeBuilder:\n if self.contract_method_info is None:\n raise InternalError(\"variable is inferred as self outside of contract scope\", expr_loc)\n return ContractSelfExpressionBuilder(\n fragment=self.contract_method_info.fragment,\n pytype=self.contract_method_info.contract_type,\n location=expr_loc,\n )\n\n @typing.override\n def resolve_local_type(self, var_name: str, expr_loc: SourceLocation) -> pytypes.PyType | None:\n return self._symtable.get(var_name)\n\n # expressions\n\n @typing.override\n def visit_assignment_expr(self, expr: mypy.nodes.AssignmentExpr) -> NodeBuilder:\n expr_loc = self._location(expr)\n self._precondition(\n not isinstance(expr, mypy.nodes.TupleExpr | mypy.nodes.ListExpr),\n \"Python doesn't support tuple unpacking in assignment expressions\",\n expr_loc,\n )\n # TODO: test if self. assignment?\n source = require_instance_builder(expr.value.accept(self))\n if not self._assign_type(expr.target, source.pytype):\n # typing error, just return the source to continue with\n return source\n value = source.resolve()\n target = self.resolve_lvalue(expr.target)\n result = AssignmentExpression(source_location=expr_loc, value=value, target=target)\n result_typ = source.pytype\n return builder_for_instance(result_typ, result)\n\n @typing.override\n def visit_super_expr(self, super_expr: mypy.nodes.SuperExpr) -> NodeBuilder:\n super_loc = self._location(super_expr)\n if self.contract_method_info is None:\n raise CodeError(\"super() expression should not occur outside of class\", super_loc)\n if super_expr.call.args:\n raise CodeError(\n \"only the zero-arguments version of super() is supported\",\n self._location(super_expr.call),\n )\n if (\n super_expr.name.startswith(\"__\")\n and super_expr.name.endswith(\"__\")\n and super_expr.name != \"__init__\"\n ):\n raise CodeError(\"the only dunder method supported for calling is init\", super_loc)\n for base in self.contract_method_info.fragment.mro:\n try:\n base_sym_typ = base.symbols[super_expr.name]\n except KeyError:\n pass\n else:\n if not isinstance(base_sym_typ, pytypes.FuncType):\n raise CodeError(\"super() is only supported for calling functions\", super_loc)\n func_type = base_sym_typ\n base_method = base.resolve_method(super_expr.name, include_inherited=False)\n # the check for class abstractness is because in theory the next method in the MRO\n # when compiling a derived class could still be non-trivial\n if (\n base_method is not None\n and base_method.is_trivial\n and not self.contract_method_info.is_abstract\n ):\n raise CodeError(\"call to trivial method via super()\", super_loc)\n break\n else:\n if super_expr.name == \"__init__\":\n # support fall through to object __init__, it's the only method from\n # non-member bases that is callable, and it's a no-op, but it can be useful\n # in the case of multiple inheritance\n return NoneTypeBuilder(super_loc)\n raise CodeError(\n f\"unable to locate method {super_expr.name}\"\n f\" in bases of {self.contract_method_info.fragment.id}\",\n super_loc,\n )\n\n super_target = InstanceSuperMethodTarget(member_name=super_expr.name)\n return SubroutineInvokerExpressionBuilder(\n target=super_target, func_type=func_type, location=super_loc\n )\n\n # statements\n\n def visit_block(self, block: mypy.nodes.Block) -> Block:\n translated_body = []\n for stmt in block.body:\n translated_stmt = stmt.accept(self)\n if translated_stmt is None:\n pass\n elif isinstance(translated_stmt, Statement):\n translated_body.append(translated_stmt)\n else:\n translated_body.extend(translated_stmt)\n return Block(\n source_location=self._location(block),\n body=translated_body,\n )\n\n def visit_expression_stmt(self, stmt: mypy.nodes.ExpressionStmt) -> ExpressionStatement | None:\n stmt_loc = self._location(stmt)\n if isinstance(stmt.expr, mypy.nodes.StrExpr):\n if stmt.expr.value != self.func_def.docstring:\n logger.warning(\n \"String literal is not assigned and is not part of docstring\",\n location=stmt_loc,\n )\n return None\n if isinstance(stmt.expr, mypy.nodes.TupleExpr) and len(stmt.expr.items) == 1:\n raise CodeError(\n \"Tuple being constructed without assignment,\"\n \" check for a stray comma at the end of the statement\",\n stmt_loc,\n )\n expr_builder = require_instance_builder(stmt.expr.accept(self))\n if expr_builder.pytype != pytypes.NoneType:\n if isinstance(stmt.expr, mypy.nodes.CallExpr) and isinstance(\n stmt.expr.analyzed, mypy.nodes.RevealExpr | mypy.nodes.AssertTypeExpr\n ):\n # special case to ignore ignoring the result of typing.reveal_type\/assert_type\n pass\n elif isinstance(expr_builder.pytype, pytypes.InnerTransactionResultType) or (\n isinstance(expr_builder.pytype, pytypes.TupleLikeType)\n and any(\n isinstance(i, pytypes.InnerTransactionResultType)\n for i in expr_builder.pytype.items\n )\n ):\n # special case to ignore inner transaction result types\n # could maybe expand this check to consider whether an expression has known\n # side-effects\n pass\n else:\n self.context.warning(\"expression result is ignored\", stmt_loc)\n return ExpressionStatement(expr=expr_builder.resolve())\n\n def visit_assignment_stmt(self, stmt: mypy.nodes.AssignmentStmt) -> Sequence[Statement]:\n stmt_loc = self._location(stmt)\n match stmt.lvalues:\n case [mypy.nodes.NameExpr(is_special_form=True)]:\n self._error(\n \"type aliases, type vars, and type constructors\"\n \" are not supported inside functions\",\n stmt_loc,\n )\n return []\n match stmt.rvalue:\n case mypy.nodes.TempNode(no_rhs=True):\n assert (\n len(stmt.lvalues) == 1\n ), \"mypy should guarantee that an annotation assigment has only a single lvalue\"\n (lvalue,) = stmt.lvalues\n assert (\n stmt.type is not None\n ), \"mypy should guarantee that an annotation assignment has a type set\"\n annotated_type = self.context.type_to_pytype(stmt.type, source_location=stmt_loc)\n self._assign_type(lvalue, annotated_type)\n # forward type-declaration only, no-op\n return []\n rvalue = require_instance_builder(stmt.rvalue.accept(self))\n if not all(self._assign_type(lvalue, rvalue.pytype) for lvalue in stmt.lvalues):\n # already a typing error, don't need a second one\n return []\n\n if isinstance(rvalue, StorageProxyConstructorResult):\n try:\n (lvalue,) = stmt.lvalues\n except ValueError:\n # this is true regardless of whether it's a self assignment or not,\n # these are objects so aliasing is an issue in terms of semantic compatibility\n raise CodeError(\n f\"{rvalue.pytype} can only be assigned to a single variable\", stmt_loc\n ) from None\n if is_self_member(lvalue):\n return self._handle_proxy_assignment(lvalue, rvalue, stmt_loc)\n elif rvalue.args.initial_value is not None:\n raise CodeError(\n \"providing an initial value is only allowed\"\n \" when assigning to a member variable\",\n stmt_loc,\n )\n elif isinstance(\n rvalue.pytype, pytypes.StorageProxyType | pytypes.StorageMapProxyType\n ) and any(is_self_member(lvalue) for lvalue in stmt.lvalues):\n raise CodeError(\"unsupported usage of storage type\", stmt_loc)\n elif len(stmt.lvalues) > 1:\n rvalue = rvalue.single_eval()\n\n return [\n AssignmentStatement(\n value=rvalue.resolve(),\n target=self.resolve_lvalue(lvalue),\n source_location=stmt_loc,\n )\n for lvalue in reversed(stmt.lvalues)\n ]\n\n def _assign_type(\n self,\n lvalue: mypy.nodes.Expression,\n typ: pytypes.PyType,\n ) -> bool:\n match lvalue:\n case mypy.nodes.NameExpr(name=var_name):\n if var_name == \"_\":\n raise CodeError(\n \"_ is not currently supported as a variable name\", self._location(lvalue)\n )\n lvalue_loc = self._location(lvalue)\n symbol_type = self._symtable.setdefault(var_name, typ)\n if not (symbol_type <= typ):\n logger.error(\n f\"{var_name!r} already has type {symbol_type}\"\n f\" which is not compatible with {typ}\",\n location=lvalue_loc,\n )\n return False\n return True\n case mypy.nodes.TupleExpr(items=lval_items) | mypy.nodes.ListExpr(items=lval_items):\n if star_expr := next(\n (\n lval_item\n for lval_item in lval_items\n if isinstance(lval_item, mypy.nodes.StarExpr)\n ),\n None,\n ):\n raise CodeError(\n \"star expressions are not supported\", self._location(star_expr)\n )\n match typ:\n case pytypes.SequenceType(items=homogenous_type):\n tuple_item_types = (homogenous_type,) * len(lval_items)\n case pytypes.TupleLikeType(items=tuple_item_types):\n if len(tuple_item_types) != len(lval_items):\n raise CodeError(\n f\"length mismatch source size of {len(tuple_item_types)}\"\n f\" and target size of {len(lval_items)}\",\n self._location(lvalue),\n )\n case _:\n raise CodeError(\n \"source type not supported for unpacking\", self._location(lvalue)\n )\n return all(\n self._assign_type(lval_item, inner_typ)\n for lval_item, inner_typ in zip(lval_items, tuple_item_types, strict=True)\n )\n case _:\n return True\n\n def _handle_proxy_assignment(\n self,\n lvalue: mypy.nodes.MemberExpr,\n rvalue: StorageProxyConstructorResult,\n stmt_loc: SourceLocation,\n ) -> Sequence[Statement]:\n if self.contract_method_info is None:\n raise InternalError(\"Assignment to self outside of a contract class\", stmt_loc)\n pytype = rvalue.pytype\n if self.func_def.name != \"__init__\":\n raise CodeError(\n f\"{pytype.generic or pytype}\"\n \" can only be assigned to a member variable in the __init__ method\",\n stmt_loc,\n )\n member_loc = self._location(lvalue)\n member_name = lvalue.name\n storage = self.contract_method_info.fragment.resolve_storage(member_name)\n if storage is None:\n raise CodeError(\"unable to resolve class storage member\", member_loc)\n if storage.definition is not None:\n logger.info(\n f\"previous definition of {member_name} was here\",\n location=storage.definition.source_location,\n )\n logger.error(\n f\"redefinition of {member_name}\",\n location=stmt_loc,\n )\n\n key = rvalue.args.key\n if key is None:\n key = BytesConstant(\n value=member_name.encode(\"utf8\"),\n wtype=pytype.wtype,\n encoding=BytesEncoding.utf8,\n source_location=member_loc,\n )\n elif not isinstance(key, BytesConstant):\n logger.error(\n f\"assigning {pytype} to a member variable\"\n f\" requires a constant value for {rvalue.args.key_arg_name}\",\n location=stmt_loc,\n )\n key = BytesConstant(\n value=b\"0\",\n wtype=key.wtype,\n encoding=BytesEncoding.unknown,\n source_location=key.source_location,\n )\n storage.definition = AppStorageDefinition(\n source_location=member_loc,\n member_name=member_name,\n kind=storage.kind,\n storage_wtype=pytype.content_wtype,\n key_wtype=(\n pytype.key_wtype if isinstance(pytype, pytypes.StorageMapProxyType) else None\n ),\n key=key,\n description=rvalue.args.description,\n )\n\n if rvalue.args.initial_value is None:\n return []\n match pytype:\n case pytypes.StorageProxyType(\n generic=pytypes.GenericGlobalStateType, content_wtype=content_wtype\n ):\n global_state_target = AppStateExpression(\n key=key,\n exists_assertion_message=None, # this is a write, not a read\n wtype=content_wtype,\n source_location=member_loc,\n )\n return [\n AssignmentStatement(\n target=global_state_target,\n value=rvalue.args.initial_value.resolve(),\n source_location=stmt_loc,\n )\n ]\n case unhandled:\n raise InternalError(\n f\"Don't know how to do initialise-on-declaration for {unhandled}\", stmt_loc\n )\n\n def resolve_lvalue(self, lvalue: mypy.nodes.Expression) -> Lvalue:\n builder_or_literal = lvalue.accept(self)\n builder = require_instance_builder(builder_or_literal)\n return builder.resolve_lvalue()\n\n @typing.override\n def empty_statement(self, stmt: mypy.nodes.Statement) -> None:\n return None\n\n def visit_operator_assignment_stmt(self, stmt: mypy.nodes.OperatorAssignmentStmt) -> Statement:\n stmt_loc = self._location(stmt)\n builder = require_instance_builder(stmt.lvalue.accept(self))\n rhs = require_instance_builder(stmt.rvalue.accept(self))\n try:\n op = BuilderBinaryOp(stmt.op)\n except ValueError as ex:\n raise InternalError(f\"Unknown binary operator: {stmt.op}\") from ex\n return builder.augmented_assignment(op=op, rhs=rhs, location=stmt_loc)\n\n def visit_if_stmt(self, stmt: mypy.nodes.IfStmt) -> IfElse:\n self._precondition(\n len(stmt.body) == len(stmt.expr),\n \"mismatch between if statement condition list length and body list length\",\n stmt,\n )\n self._precondition(\n len(stmt.expr) == 1,\n \"python ast module should produce normalised if statements\",\n stmt,\n )\n (expr,) = stmt.expr\n (if_body,) = stmt.body\n condition = expr.accept(self).bool_eval(self._location(expr))\n if_branch = self.visit_block(if_body)\n else_branch = self.visit_block(stmt.else_body) if stmt.else_body else None\n return IfElse(\n source_location=self._location(stmt),\n condition=condition.resolve(),\n if_branch=if_branch,\n else_branch=else_branch,\n )\n\n @typing.overload\n def _build_loop(\n self,\n stmt: mypy.nodes.WhileStmt,\n ctor: Callable[[Block, SourceLocation], WhileLoop],\n ) -> WhileLoop | Block: ...\n\n @typing.overload\n def _build_loop(\n self,\n stmt: mypy.nodes.ForStmt,\n ctor: Callable[[Block, SourceLocation], ForInLoop],\n ) -> ForInLoop | Block: ...\n\n def _build_loop(\n self,\n stmt: mypy.nodes.WhileStmt | mypy.nodes.ForStmt,\n ctor: Callable[[Block, SourceLocation], WhileLoop | ForInLoop],\n ) -> WhileLoop | ForInLoop | Block:\n loop_loc = self._location(stmt)\n if stmt.else_body is None:\n break_label = None\n else:\n break_label = Label(f\"after_loop_L{loop_loc.line}\")\n\n self._break_label_stack.append(break_label)\n try:\n block = self.visit_block(stmt.body)\n finally:\n self._break_label_stack.pop()\n loop = ctor(block, loop_loc)\n if stmt.else_body is None:\n return loop\n else_body = self.visit_block(stmt.else_body)\n # empty block, exists so we have a goto target that skips the else body\n after_block = Block(label=break_label, body=[], source_location=loop_loc)\n return Block(\n body=[loop, else_body, after_block],\n comment=f\"loop_with_else_L{loop_loc.line}\",\n source_location=loop_loc,\n )\n\n def visit_while_stmt(self, stmt: mypy.nodes.WhileStmt) -> WhileLoop | Block:\n condition = stmt.expr.accept(self).bool_eval(self._location(stmt.expr))\n return self._build_loop(\n stmt,\n lambda loop_body, loop_loc: WhileLoop(\n condition=condition.resolve(),\n loop_body=loop_body,\n source_location=loop_loc,\n ),\n )\n\n def visit_for_stmt(self, stmt: mypy.nodes.ForStmt) -> ForInLoop | Block:\n sequence_builder = require_instance_builder(stmt.expr.accept(self))\n sequence = sequence_builder.iterate()\n iter_item_type = sequence_builder.iterable_item_type()\n self._assign_type(stmt.index, iter_item_type)\n items = self.resolve_lvalue(stmt.index)\n return self._build_loop(\n stmt,\n lambda loop_body, loop_loc: ForInLoop(\n items=items,\n sequence=sequence,\n loop_body=loop_body,\n source_location=loop_loc,\n ),\n )\n\n def visit_break_stmt(self, stmt: mypy.nodes.BreakStmt) -> LoopExit | Goto:\n stmt_loc = self._location(stmt)\n break_label = self._break_label_stack[-1]\n if break_label is None:\n return LoopExit(stmt_loc)\n else:\n return Goto(target=break_label, source_location=stmt_loc)\n\n def visit_continue_stmt(self, stmt: mypy.nodes.ContinueStmt) -> LoopContinue:\n return LoopContinue(self._location(stmt))\n\n def visit_assert_stmt(self, stmt: mypy.nodes.AssertStmt) -> ExpressionStatement:\n error_message: str | None = None\n if stmt.msg is not None:\n msg = stmt.msg.accept(self)\n match msg:\n case LiteralBuilder(value=str(error_message)):\n pass\n case _:\n self._error(\"only literal strings are supported as assertion messages\", stmt)\n condition = stmt.expr.accept(self).bool_eval(self._location(stmt.expr))\n return ExpressionStatement(\n AssertExpression(\n condition=condition.resolve(),\n error_message=error_message,\n source_location=self._location(stmt),\n )\n )\n\n def visit_del_stmt(self, stmt: mypy.nodes.DelStmt) -> Statement:\n stmt_expr = stmt.expr.accept(self)\n del_item = require_instance_builder(stmt_expr)\n return del_item.delete(self._location(stmt))\n\n def visit_return_stmt(self, stmt: mypy.nodes.ReturnStmt) -> ReturnStatement | None:\n loc = self._location(stmt)\n return_expr = stmt.expr\n if return_expr is None:\n if self._return_type is not pytypes.NoneType:\n self._error(\n \"function is typed as returning a value, so a value must be returned\", loc\n )\n return ReturnStatement(source_location=loc, value=None)\n\n returning_builder = require_instance_builder(return_expr.accept(self))\n if not (self._return_type <= returning_builder.pytype):\n self._error(\n f\"invalid return type of {returning_builder.pytype}, expected {self._return_type}\",\n loc,\n )\n return ReturnStatement(source_location=loc, value=returning_builder.resolve())\n\n def visit_match_stmt(self, stmt: mypy.nodes.MatchStmt) -> Switch | None:\n loc = self._location(stmt)\n subject = require_instance_builder(stmt.subject.accept(self))\n case_block_map = dict[Expression, Block]()\n default_block: Block | None = None\n for pattern, guard, block in zip(stmt.patterns, stmt.guards, stmt.bodies, strict=True):\n if guard is not None:\n self._error(\"guard clauses are not supported\", guard)\n if default_block is not None:\n self._error(\"default case already encountered\", pattern)\n continue\n case_block = self.visit_block(block)\n pattern_loc = self._location(pattern)\n case_value_builder: InstanceBuilder | None = None\n match pattern:\n case mypy.patterns.AsPattern(name=None, pattern=None):\n default_block = case_block\n case mypy.patterns.ValuePattern(expr=case_expr):\n case_value_builder = require_instance_builder(case_expr.accept(self))\n case_value_builder = maybe_resolve_literal(case_value_builder, subject.pytype)\n case mypy.patterns.SingletonPattern(value=bool(bool_literal)):\n case_value_builder = LiteralBuilderImpl(\n value=bool_literal, source_location=pattern_loc\n )\n case_value_builder = maybe_resolve_literal(case_value_builder, subject.pytype)\n case mypy.patterns.ClassPattern() as cls_pattern:\n class_builder = cls_pattern.class_ref.accept(self)\n if not isinstance(class_builder, CallableBuilder):\n logger.error(\"expected a type\", location=class_builder.source_location)\n elif cls_pattern.keyword_values:\n self._error(\n \"attribute matching is not supported\", cls_pattern.keyword_values[0]\n )\n else:\n cls_args = []\n has_error = False\n for pos_case in cls_pattern.positionals:\n if isinstance(pos_case, mypy.patterns.ValuePattern):\n cls_args.append(pos_case.expr.accept(self))\n else:\n has_error = True\n self._error(\"expected a value pattern\", pos_case)\n if not has_error:\n case_value_builder = class_builder.call(\n args=cls_args,\n arg_kinds=[mypy.nodes.ARG_POS] * len(cls_args),\n arg_names=[None] * len(cls_args),\n location=pattern_loc,\n )\n\n case _:\n logger.error(\"unsupported case pattern\", location=pattern_loc)\n if case_value_builder is not None:\n if case_value_builder.pytype != subject.pytype:\n # TODO: what about other comparable types, or subtypes?\n logger.error(\n \"type mismatch,\"\n \" case values must be the exact same type as the subject type\",\n location=pattern_loc,\n )\n else:\n case_block_map[case_value_builder.resolve()] = case_block\n\n return Switch(\n source_location=loc,\n value=subject.resolve(),\n cases=case_block_map,\n default_case=default_block,\n )\n\n # Unsupported statements\n @typing.override\n def visit_function(self, fdef: mypy.nodes.FuncDef, _: mypy.nodes.Decorator | None) -> None:\n self._error(\"nested functions are not supported\", fdef)\n\n @typing.override\n def visit_class_def(self, cdef: mypy.nodes.ClassDef) -> None:\n self._error(\"classes nested inside functions are not supported\", cdef)\n\n @typing.override\n def visit_type_alias_stmt(self, o: mypy.nodes.TypeAliasStmt) -> None:\n self._error(\"type alias statements are not supported\", o)\n\n\ndef is_self_member(\n expr: mypy.nodes.Expression,\n) -> typing.TypeGuard[mypy.nodes.MemberExpr]:\n match expr:\n case mypy.nodes.MemberExpr(expr=mypy.nodes.NameExpr(node=mypy.nodes.Var(is_self=True))):\n return True\n return False\n\n\ndef require_instance_builder(builder_or_literal: NodeBuilder) -> InstanceBuilder:\n return expect.instance_builder(builder_or_literal, default=expect.default_raise)\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/subroutine.py","language":"Python","license":"NOASSERTION","size":55330} {"code":"import contextlib\nimport operator\nimport re\nimport typing\nimport warnings\nfrom collections.abc import Callable, Iterator, Mapping, Sequence\nfrom itertools import zip_longest\n\nimport mypy.build\nimport mypy.nodes\nimport mypy.types\nfrom mypy.types import get_proper_type, is_named_instance\n\nfrom puya import log\nfrom puya.errors import CodeError, InternalError\nfrom puya.parse import SourceLocation\nfrom puya.utils import unique\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.context import ASTConversionModuleContext\nfrom puyapy.awst_build.eb.factories import builder_for_type\nfrom puyapy.awst_build.eb.interface import InstanceBuilder, NodeBuilder, TypeBuilder\nfrom puyapy.models import ConstantValue\n\nlogger = log.get_logger(__name__)\n\n\ndef refers_to_fullname(ref_expr: mypy.nodes.RefExpr, *fullnames: str) -> bool:\n \"\"\"Is node a name or member expression with the given full name?\"\"\"\n if isinstance(ref_expr.node, mypy.nodes.TypeAlias):\n return is_named_instance(ref_expr.node.target, fullnames)\n else:\n return ref_expr.fullname in fullnames\n\n\ndef get_unaliased_fullname(ref_expr: mypy.nodes.RefExpr) -> str:\n alias = get_aliased_instance(ref_expr)\n if alias:\n return alias.type.fullname\n return ref_expr.fullname\n\n\ndef get_aliased_instance(ref_expr: mypy.nodes.RefExpr) -> mypy.types.Instance | None:\n if isinstance(ref_expr.node, mypy.nodes.TypeAlias):\n t = get_proper_type(ref_expr.node.target)\n if isinstance(t, mypy.types.Instance):\n return t\n if (\n isinstance(t, mypy.types.TupleType)\n and t.partial_fallback.type.fullname != \"builtins.tuple\"\n ):\n return t.partial_fallback\n return None\n\n\ndef get_decorators_by_fullname(\n ctx: ASTConversionModuleContext,\n decorator: mypy.nodes.Decorator,\n *,\n original: bool = False,\n) -> dict[str, mypy.nodes.Expression]:\n result = dict[str, mypy.nodes.Expression]()\n for d in decorator.original_decorators if original else decorator.decorators:\n if isinstance(d, mypy.nodes.RefExpr):\n full_name = get_unaliased_fullname(d)\n result[get_unaliased_fullname(d)] = d\n elif isinstance(d, mypy.nodes.CallExpr) and isinstance(d.callee, mypy.nodes.RefExpr):\n full_name = get_unaliased_fullname(d.callee)\n else:\n raise CodeError(\"Unsupported decorator usage\", ctx.node_location(d))\n result[full_name] = d\n return result\n\n\nUNARY_OPS: typing.Final[Mapping[str, Callable[[typing.Any], typing.Any]]] = {\n \"~\": operator.inv,\n \"not\": operator.not_,\n \"+\": operator.pos,\n \"-\": operator.neg,\n}\n\n\n@contextlib.contextmanager\ndef _log_warnings(location: SourceLocation) -> Iterator[None]:\n folding_warnings = []\n try:\n with warnings.catch_warnings(record=True, action=\"always\") as folding_warnings:\n yield\n finally:\n for warning in folding_warnings:\n logger.warning(warning.message, location=location)\n\n\ndef fold_unary_expr(location: SourceLocation, op: str, expr: ConstantValue) -> ConstantValue:\n if not (func := UNARY_OPS.get(op)):\n raise InternalError(f\"Unhandled unary operator: {op}\", location)\n if op == \"~\" and isinstance(expr, int):\n logger.warning(\n \"due to Python ints being signed, bitwise inversion yield a negative number\",\n location=location,\n )\n try:\n with _log_warnings(location):\n result = func(expr)\n except Exception as ex:\n raise CodeError(str(ex), location) from ex\n if not isinstance(result, ConstantValue):\n raise CodeError(f\"unsupported result type of {type(result).__name__}\", location)\n return result\n\n\nBINARY_OPS: typing.Final[Mapping[str, Callable[[typing.Any, typing.Any], typing.Any]]] = {\n \"+\": operator.add,\n \"-\": operator.sub,\n \"*\": operator.mul,\n \"@\": operator.matmul,\n \"\/\": operator.truediv,\n \"%\": operator.mod,\n \"**\": operator.pow,\n \"<<\": operator.lshift,\n \">>\": operator.rshift,\n \"|\": operator.or_,\n \"^\": operator.xor,\n \"&\": operator.and_,\n \"\/\/\": operator.floordiv,\n \">\": operator.gt,\n \"<\": operator.lt,\n \"==\": operator.eq,\n \">=\": operator.ge,\n \"<=\": operator.le,\n \"!=\": operator.ne,\n \"is\": operator.is_,\n \"is not\": operator.is_not,\n \"in\": lambda a, b: a in b,\n \"not in\": lambda a, b: a not in b,\n \"and\": lambda a, b: a and b,\n \"or\": lambda a, b: a or b,\n}\n\n\ndef fold_binary_expr(\n location: SourceLocation,\n op: str,\n lhs: ConstantValue,\n rhs: ConstantValue,\n) -> ConstantValue:\n if not (func := BINARY_OPS.get(op)):\n raise InternalError(f\"Unhandled binary operator: {op}\", location)\n try:\n with _log_warnings(location):\n result = func(lhs, rhs)\n except Exception as ex:\n raise CodeError(str(ex), location) from ex\n if not isinstance(result, ConstantValue):\n raise CodeError(f\"unsupported result type of {type(result).__name__}\", location)\n return result\n\n\ndef extract_bytes_literal_from_mypy(expr: mypy.nodes.BytesExpr) -> bytes:\n import ast\n\n bytes_str = expr.value\n # mypy doesn't preserve the value of the quotes, need to reverse it\n if '\"' in bytes_str:\n bytes_literal = \"b'\" + bytes_str + \"'\"\n else:\n bytes_literal = 'b\"' + bytes_str + '\"'\n bytes_const: bytes = ast.literal_eval(bytes_literal)\n return bytes_const\n\n\nTBuilder = typing.TypeVar(\"TBuilder\", bound=NodeBuilder)\n\n\ndef get_arg_mapping(\n *,\n required_positional_names: Sequence[str] | None = None,\n optional_positional_names: Sequence[str] | None = None,\n required_kw_only: Sequence[str] | None = None,\n optional_kw_only: Sequence[str] | None = None,\n args: Sequence[TBuilder],\n arg_names: Sequence[str | None],\n call_location: SourceLocation,\n raise_on_missing: bool,\n) -> tuple[dict[str, TBuilder], bool]:\n required_positional_names = required_positional_names or []\n optional_positional_names = optional_positional_names or []\n required_kw_only = required_kw_only or []\n optional_kw_only = optional_kw_only or []\n all_names = [\n *required_positional_names,\n *optional_positional_names,\n *required_kw_only,\n *optional_kw_only,\n ]\n if len(all_names) != len(set(all_names)):\n raise InternalError(\"duplicate names\", call_location)\n\n arg_mapping = dict[str, TBuilder]()\n num_positionals = arg_names.count(None)\n positional_names = [*required_positional_names, *optional_positional_names]\n for positional_name, positional_arg in zip_longest(positional_names, args[:num_positionals]):\n if positional_name is None:\n logger.error(\"unexpected positional argument\", location=positional_arg.source_location)\n elif positional_arg is None:\n break # positional arguments could be named\n else:\n arg_mapping[positional_name] = positional_arg\n for arg_name, kw_arg in zip(arg_names[num_positionals:], args[num_positionals:], strict=True):\n if arg_name is None:\n # shouldn't be possible, might happen with type ignore?\n logger.error(\n \"non-keyword argument appears after keywords\", location=kw_arg.source_location\n )\n elif arg_name in arg_mapping:\n # again, shouldn't be possible, but might happen with type ignore?\n logger.error(\"duplicate argument name\", location=kw_arg.source_location)\n elif arg_name not in all_names:\n logger.error(\"unrecognised keyword argument\", location=kw_arg.source_location)\n else:\n arg_mapping[arg_name] = kw_arg\n any_missing = False\n if missing_args := set(required_positional_names).difference(arg_mapping.keys()):\n msg = f\"missing required positional argument(s): {', '.join(sorted(missing_args))}\"\n if raise_on_missing:\n raise CodeError(msg, call_location)\n any_missing = True\n logger.error(msg, location=call_location)\n elif missing_kwargs := set(required_kw_only).difference(arg_mapping.keys()):\n msg = f\"missing required keyword argument(s): {', '.join(sorted(missing_kwargs))}\"\n if raise_on_missing:\n raise CodeError(msg, call_location)\n any_missing = True\n logger.error(msg, location=call_location)\n return arg_mapping, any_missing\n\n\ndef snake_case(s: str) -> str:\n s = s.replace(\"-\", \" \")\n s = re.sub(r\"([A-Z]+)([A-Z][a-z])\", r\"\\1_\\2\", s)\n s = re.sub(r\"([a-z\\d])([A-Z])\", r\"\\1_\\2\", s)\n return re.sub(r\"[-\\s]\", \"_\", s).lower()\n\n\ndef require_callable_type(\n node: mypy.nodes.FuncBase | mypy.nodes.Decorator, location: SourceLocation\n) -> mypy.types.CallableType:\n if isinstance(node, mypy.nodes.Decorator):\n typ = node.var.type\n else:\n typ = node.type\n if typ is None:\n raise InternalError(f\"unable to resolve type of {node.fullname}\", location)\n if not isinstance(typ, mypy.types.CallableType):\n raise CodeError(\"expected a callable type\", location)\n return typ\n\n\ndef maybe_resolve_literal(\n operand: TBuilder, target_type: pytypes.PyType\n) -> TBuilder | InstanceBuilder:\n if not isinstance(operand, InstanceBuilder):\n return operand\n if not (target_type <= operand.pytype):\n target_type_builder = builder_for_type(target_type, operand.source_location)\n if isinstance(target_type_builder, TypeBuilder):\n return operand.resolve_literal(target_type_builder)\n return operand\n\n\ndef resolve_literal(operand: InstanceBuilder, target_type: pytypes.PyType) -> InstanceBuilder:\n target_type_builder = builder_for_type(target_type, operand.source_location)\n assert isinstance(target_type_builder, TypeBuilder)\n return operand.resolve_literal(target_type_builder)\n\n\ndef determine_base_type(\n first: pytypes.PyType, *rest: pytypes.PyType, location: SourceLocation\n) -> pytypes.PyType:\n operands = unique((first, *rest))\n if len(operands) == 1:\n return first\n for candidate in operands:\n if all(candidate <= operand for operand in operands):\n return candidate\n return pytypes.UnionType(operands, location)\n\n\ndef extract_decorator_args(\n decorator: mypy.nodes.Expression, location: SourceLocation\n) -> list[tuple[str | None, mypy.nodes.Expression]]:\n match decorator:\n case mypy.nodes.RefExpr():\n return []\n case mypy.nodes.CallExpr(args=args, arg_names=arg_names):\n return list(zip(arg_names, args, strict=True))\n case unexpected_node:\n raise InternalError(f\"unexpected decorator node: {unexpected_node}\", location)\n\n\ndef get_subroutine_decorator_inline_arg(\n context: ASTConversionModuleContext, decorator: mypy.nodes.Expression\n) -> bool | None:\n args = extract_decorator_args(decorator, context.node_location(decorator))\n for name, expr in args:\n match name, expr:\n case \"inline\", mypy.nodes.NameExpr(fullname=\"builtins.True\"):\n return True\n case \"inline\", mypy.nodes.NameExpr(fullname=\"builtins.False\"):\n return False\n case \"inline\", mypy.nodes.NameExpr(fullname=\"builtins.None\"):\n return None\n case _:\n logger.error(\"unexpected argument\", location=context.node_location(expr))\n return None\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/awst_build\/utils.py","language":"Python","license":"NOASSERTION","size":11376} {"code":"import argparse\nimport json\nimport typing\nfrom collections.abc import Iterable, Sequence\nfrom pathlib import Path\n\nimport attrs\nfrom cattrs.preconf.json import make_converter\n\nfrom puya import (\n arc56_models as arc56,\n log,\n)\nfrom puya.arc32 import OCA_ARC32_MAPPING\nfrom puya.arc56 import allowed_call_oca, allowed_create_oca\nfrom puya.artifact_metadata import ARC4MethodArg, ARC4Returns\nfrom puya.errors import PuyaError\nfrom puyapy.awst_build.arc4_client_gen import write_arc4_client\n\nlogger = log.get_logger(__name__)\nARC32_OCA_MAPPING = {v: k for k, v in OCA_ARC32_MAPPING.items()}\n\n\n@attrs.define(kw_only=True)\nclass PuyaGenOptions:\n paths: Sequence[Path] = attrs.field(default=(), repr=lambda p: str(list(map(str, p))))\n log_level: log.LogLevel = log.LogLevel.info\n out_dir: Path | None = None\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n prog=\"puyapy-clientgen\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n description=\"Output algopy contract client for typed ARC4 ABI calls from an \"\n \"ARC-32 or ARC-56 application spec\",\n )\n parser.add_argument(\n \"--out-dir\",\n type=Path,\n help=\"Path for outputting client, defaults to app spec folder\",\n default=False,\n )\n parser.add_argument(\"paths\", type=Path, nargs=\"+\", metavar=\"PATH\")\n options = PuyaGenOptions()\n parser.parse_args(namespace=options)\n log.configure_logging(min_log_level=options.log_level)\n output_stubs(options.paths, options.out_dir)\n\n\ndef output_stubs(paths: Sequence[Path], out_dir: Path | None) -> None:\n try:\n app_spec_paths = resolve_app_specs(paths)\n for app_spec_path in app_spec_paths:\n app_spec_json = app_spec_path.read_text(\"utf8\")\n if app_spec_path.name.endswith(\".arc56.json\"):\n app_spec = parse_arc56(app_spec_json)\n else:\n # TODO: use algokit_utils to do this conversion when it is available?\n app_spec = _convert_arc32_to_arc56(app_spec_json)\n write_arc4_client(app_spec, out_dir or app_spec_path.parent)\n except PuyaError as ex:\n logger.error(str(ex)) # noqa: TRY400\n\n\ndef _convert_arc32_to_arc56(app_spec_json: str) -> arc56.Contract:\n name, structs, methods = _parse_arc32_app_spec_methods(app_spec_json)\n return arc56.Contract(\n name=name,\n structs=structs,\n methods=methods,\n )\n\n\ndef resolve_app_specs(paths: Sequence[Path]) -> Sequence[Path]:\n app_specs = list[Path]()\n for path in paths:\n if not path.is_dir():\n app_specs.append(path)\n else:\n patterns = [\"application.json\", \"*.arc32.json\"]\n\n app_specs = []\n for pattern in patterns:\n app_specs.extend(path.rglob(pattern))\n\n app_specs = sorted(set(app_specs))\n if not app_specs:\n raise PuyaError(\"No app specs found\")\n return app_specs\n\n\ndef parse_arc56(app_spec_json: str) -> arc56.Contract:\n converter = make_converter(omit_if_default=True)\n return converter.loads(app_spec_json, arc56.Contract)\n\n\ndef _parse_arc32_app_spec_methods(\n app_spec_json: str,\n) -> tuple[str, dict[str, Sequence[arc56.StructField]], Sequence[arc56.Method]]:\n # only need to parse a limited subset of ARC32 for client generation\n # i.e. ABI methods, their OCA parameters, and any struct info\n # default args are ignored as they aren't supported for on chain calls currently\n\n app_spec = json.loads(app_spec_json)\n contract = app_spec[\"contract\"]\n hints = app_spec[\"hints\"]\n contract_name = contract[\"name\"]\n methods = list[arc56.Method]()\n arc4_methods = {m.signature: m for m in _parse_methods(contract[\"methods\"])}\n known_structs = dict[str, Sequence[arc56.StructField]]()\n for arc4_method in arc4_methods.values():\n method_hints = hints[str(arc4_method.signature)]\n arg_to_struct = dict[str, str]()\n for param, struct_name, struct in _parse_structs(method_hints.get(\"structs\", {})):\n for known_struct_name, known_struct in known_structs.items():\n if known_struct == struct:\n arg_to_struct[param] = known_struct_name\n break\n else:\n known_structs[struct_name] = struct\n arg_to_struct[param] = struct_name\n methods.append(\n arc56.Method(\n name=arc4_method.signature.name,\n desc=arc4_method.desc,\n args=[\n arc56.MethodArg(\n name=a.name,\n type=a.type_,\n struct=arg_to_struct.get(a.name),\n )\n for a in arc4_method.signature.args\n ],\n returns=arc56.MethodReturns(\n type=arc4_method.signature.returns.type_,\n desc=arc4_method.desc,\n struct=arg_to_struct.get(\"output\"),\n ),\n readonly=bool(method_hints.get(\"read_only\") or arc4_method.readonly),\n actions=_parse_call_config(method_hints[\"call_config\"]),\n )\n )\n return contract_name, known_structs, methods\n\n\n@attrs.frozen(kw_only=True)\nclass _MethodSignature:\n name: str\n args: tuple[ARC4MethodArg, ...]\n returns: ARC4Returns\n\n def __str__(self) -> str:\n return f\"{self.name}({','.join(a.type_ for a in self.args)}){self.returns.type_}\"\n\n\n@attrs.frozen(kw_only=True)\nclass _Method:\n signature: _MethodSignature\n desc: str | None\n readonly: bool | None\n\n\ndef _parse_methods(methods: list[dict[str, typing.Any]]) -> Iterable[_Method]:\n for method in methods:\n signature = _parse_signature(method)\n yield _Method(\n signature=signature,\n desc=method.get(\"desc\"),\n readonly=method.get(\"readonly\"),\n )\n\n\ndef _parse_signature(method: dict[str, typing.Any]) -> _MethodSignature:\n returns = method[\"returns\"]\n return _MethodSignature(\n name=method[\"name\"],\n args=tuple(\n ARC4MethodArg(\n name=arg[\"name\"],\n type_=arg[\"type\"],\n desc=arg.get(\"desc\"),\n struct=arg.get(\"struct\"),\n client_default=None, # not supported on chain\n )\n for arg in method[\"args\"]\n ),\n returns=ARC4Returns(\n type_=returns[\"type\"],\n desc=returns.get(\"desc\"),\n struct=returns.get(\"struct\"),\n ),\n )\n\n\ndef _parse_call_config(method_call_config: dict[str, str]) -> arc56.MethodActions:\n create = []\n call = []\n for oca, call_config in method_call_config.items():\n action = ARC32_OCA_MAPPING[oca].name\n match call_config:\n case \"CREATE\" if allowed_create_oca(action):\n create.append(action)\n case \"CALL\" if allowed_call_oca(action):\n call.append(action)\n # allowed creates is narrower than calls so only need to check that\n case \"ALL\" if allowed_create_oca(action):\n create.append(action)\n call.append(action)\n case invalid:\n raise PuyaError(f\"invalid call config option: {invalid}\")\n\n return arc56.MethodActions(\n create=create,\n call=call,\n )\n\n\ndef _parse_structs(\n structs: dict[str, dict[str, typing.Any]],\n) -> Iterable[tuple[str, str, Sequence[arc56.StructField]]]:\n for param, struct_config in structs.items():\n yield (\n param,\n struct_config[\"name\"],\n [arc56.StructField(name=f[0], type=f[1]) for f in struct_config[\"elements\"]],\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/client_gen.py","language":"Python","license":"NOASSERTION","size":7774} {"code":"import os\nimport shutil\nimport subprocess\nimport sysconfig\nfrom collections.abc import Callable, Mapping, Sequence\nfrom importlib import metadata\nfrom pathlib import Path\n\nimport mypy.build\nimport mypy.errors\nimport mypy.find_sources\nimport mypy.fscache\nimport mypy.modulefinder\nimport mypy.nodes\nimport mypy.options\nimport mypy.util\nfrom packaging import version\n\nfrom puya import log\nfrom puya.arc56 import create_arc56_json\nfrom puya.awst.nodes import AWST\nfrom puya.awst.serialize import awst_to_json\nfrom puya.awst.to_code_visitor import ToCodeVisitor\nfrom puya.compilation_artifacts import CompilationArtifact, CompiledContract\nfrom puya.compile import awst_to_teal\nfrom puya.errors import log_exceptions\nfrom puya.program_refs import ContractReference, LogicSigReference\nfrom puya.utils import make_path_relative_to_cwd\nfrom puyapy.awst_build.arc4_client_gen import write_arc4_client\nfrom puyapy.awst_build.main import transform_ast\nfrom puyapy.client_gen import parse_arc56\nfrom puyapy.options import PuyaPyOptions\nfrom puyapy.parse import TYPESHED_PATH, ParseResult, parse_and_typecheck\nfrom puyapy.utils import determine_out_dir\n\n# this should contain the lowest version number that this compiler does NOT support\n# i.e. the next minor version after what is defined in stubs\/pyproject.toml:tool.poetry.version\nMAX_SUPPORTED_ALGOPY_VERSION_EX = version.parse(\"2.7.0\")\nMIN_SUPPORTED_ALGOPY_VERSION = version.parse(f\"{MAX_SUPPORTED_ALGOPY_VERSION_EX.major}.0.0\")\n\nlogger = log.get_logger(__name__)\n\n\ndef compile_to_teal(puyapy_options: PuyaPyOptions) -> None:\n \"\"\"Drive the actual core compilation step.\"\"\"\n with log.logging_context() as log_ctx, log_exceptions():\n logger.debug(puyapy_options)\n try:\n parse_result = parse_with_mypy(puyapy_options.paths)\n log_ctx.sources_by_path = parse_result.sources_by_path\n log_ctx.exit_if_errors()\n awst, compilation_targets = transform_ast(parse_result)\n except mypy.errors.CompileError:\n # the placement of this catch is probably overly conservative,\n # but in parse_with_mypy there is a piece copied from mypyc, around setting\n # the location during mypy callbacks in case errors are produced.\n # also this error should have already been logged\n assert log_ctx.num_errors > 0, \"expected mypy errors to be logged\"\n log_ctx.exit_if_errors()\n if puyapy_options.output_awst or puyapy_options.output_awst_json:\n awst_out_dir = (\n puyapy_options.out_dir or Path.cwd() # TODO: maybe make this defaulted on init?\n )\n nodes = [\n n for n in awst if n.source_location.file in parse_result.explicit_source_paths\n ]\n if puyapy_options.output_awst:\n output_awst(nodes, awst_out_dir)\n if puyapy_options.output_awst_json:\n output_awst_json(nodes, awst_out_dir)\n awst_lookup = {n.id: n for n in awst}\n compilation_set = {\n target_id: determine_out_dir(loc.file.parent, puyapy_options)\n for target_id, loc in (\n (t, awst_lookup[t].source_location) for t in compilation_targets\n )\n if loc.file\n }\n teal = awst_to_teal(\n log_ctx, puyapy_options, compilation_set, parse_result.sources_by_path, awst\n )\n log_ctx.exit_if_errors()\n if puyapy_options.output_client:\n write_arc4_clients(puyapy_options.template_vars_prefix, compilation_set, teal)\n # needs to be outside the with block\n log_ctx.exit_if_errors()\n\n\ndef write_arc4_clients(\n template_prefix: str,\n compilation_set: Mapping[ContractReference | LogicSigReference, Path],\n artifacts: Sequence[CompilationArtifact],\n) -> None:\n for artifact in artifacts:\n if isinstance(artifact, CompiledContract) and artifact.metadata.is_arc4:\n contract_out_dir = compilation_set.get(artifact.id)\n if contract_out_dir:\n app_spec_json = create_arc56_json(\n approval_program=artifact.approval_program,\n clear_program=artifact.clear_program,\n metadata=artifact.metadata,\n template_prefix=template_prefix,\n )\n # use round trip of ARC-56 -> reparse to ensure consistency\n # of client output regardless if generating from ARC-56 or\n # Puya ARC4Contract\n contract = parse_arc56(app_spec_json)\n write_arc4_client(contract, contract_out_dir)\n\n\ndef parse_with_mypy(paths: Sequence[Path]) -> ParseResult:\n mypy_options = get_mypy_options()\n\n _, ordered_modules = parse_and_typecheck(paths, mypy_options)\n return ParseResult(\n mypy_options=mypy_options,\n ordered_modules=ordered_modules,\n )\n\n\ndef get_mypy_options() -> mypy.options.Options:\n mypy_opts = mypy.options.Options()\n\n # improve mypy parsing performance by using a cut-down typeshed\n mypy_opts.custom_typeshed_dir = str(TYPESHED_PATH)\n mypy_opts.abs_custom_typeshed_dir = str(TYPESHED_PATH.resolve())\n\n # set python_executable so third-party packages can be found\n mypy_opts.python_executable = _get_python_executable()\n\n mypy_opts.preserve_asts = True\n mypy_opts.include_docstrings = True\n # next two options disable caching entirely.\n # slows things down but prevents intermittent failures.\n mypy_opts.incremental = False\n mypy_opts.cache_dir = os.devnull\n\n # strict mode flags, need to review these and all others too\n mypy_opts.disallow_any_generics = True\n mypy_opts.disallow_subclassing_any = True\n mypy_opts.disallow_untyped_calls = True\n mypy_opts.disallow_untyped_defs = True\n mypy_opts.disallow_incomplete_defs = True\n mypy_opts.check_untyped_defs = True\n mypy_opts.disallow_untyped_decorators = True\n mypy_opts.warn_redundant_casts = True\n mypy_opts.warn_unused_ignores = True\n mypy_opts.warn_return_any = True\n mypy_opts.strict_equality = True\n mypy_opts.strict_concatenate = True\n\n # disallow use of any\n mypy_opts.disallow_any_unimported = True\n mypy_opts.disallow_any_expr = True\n mypy_opts.disallow_any_decorated = True\n mypy_opts.disallow_any_explicit = True\n\n mypy_opts.pretty = True # show source in output\n\n return mypy_opts\n\n\ndef _get_python_executable() -> str | None:\n prefix = _get_prefix()\n if not prefix:\n logger.warning(\"Could not determine python prefix or algopy version\")\n return None\n logger.info(f\"Found python prefix: {prefix}\")\n venv_paths = sysconfig.get_paths(vars={\"base\": prefix})\n\n python_exe = None\n for python in (\"python3\", \"python\"):\n python_exe = shutil.which(python, path=venv_paths[\"scripts\"])\n if python_exe:\n logger.debug(f\"Using python executable: {python_exe}\")\n break\n else:\n logger.warning(\"Found a python prefix, but could not find the expected python interpreter\")\n # use glob here, as we don't want to assume the python version\n discovered_site_packages = list(\n Path(prefix).glob(str(Path(\"[Ll]ib\") \/ \"**\" \/ \"site-packages\"))\n )\n try:\n (site_packages,) = discovered_site_packages\n except ValueError:\n logger.warning(\n \"Found a prefix, but could not find the expected\"\n f\" site-packages: {prefix=}, {discovered_site_packages=}\"\n )\n else:\n logger.debug(f\"Using python site-packages: {site_packages}\")\n _check_algopy_version(site_packages)\n\n return python_exe\n\n\ndef _get_prefix() -> str | None:\n # look for VIRTUAL_ENV as we want the venv puyapy is being run against (i.e. the project),\n # if no venv is active, then fallback to the ambient python prefix\n venv = os.getenv(\"VIRTUAL_ENV\")\n if venv:\n return venv\n for python in (\"python3\", \"python\"):\n prefix_result = subprocess.run( # noqa: S602\n f\"{python} -c 'import sys; print(sys.prefix or sys.base_prefix)'\",\n shell=True,\n text=True,\n capture_output=True,\n check=False,\n )\n if prefix_result.returncode == 0 and (maybe_prefix := prefix_result.stdout.strip()):\n return maybe_prefix\n return None\n\n\n_STUBS_PACKAGE_NAME = \"algorand-python\"\n\n\ndef _check_algopy_version(site_packages: Path) -> None:\n pkgs = metadata.Distribution.discover(name=_STUBS_PACKAGE_NAME, path=[str(site_packages)])\n try:\n (algopy,) = pkgs\n except ValueError:\n logger.warning(\"Could not determine algopy version\")\n return\n algopy_version = version.parse(algopy.version)\n logger.debug(f\"Found algopy: {algopy_version}\")\n\n if not (MIN_SUPPORTED_ALGOPY_VERSION <= algopy_version < MAX_SUPPORTED_ALGOPY_VERSION_EX):\n logger.warning(\n f\"{_STUBS_PACKAGE_NAME} version {algopy_version} is outside the supported range:\"\n f\" >={MIN_SUPPORTED_ALGOPY_VERSION}, <{MAX_SUPPORTED_ALGOPY_VERSION_EX}\",\n important=True,\n related_lines=[\n \"This will cause typing errors if there are incompatibilities in the API used.\",\n \"Please update your algorand-python package to be in the supported range.\",\n ],\n )\n\n\ndef output_awst(awst: AWST, awst_out_dir: Path) -> None:\n _output_awst_any(awst, ToCodeVisitor().visit_module, awst_out_dir, \".awst\")\n\n\ndef output_awst_json(awst: AWST, awst_out_dir: Path) -> None:\n _output_awst_any(awst, awst_to_json, awst_out_dir, \".awst.json\")\n\n\ndef _output_awst_any(\n awst: AWST, formatter: Callable[[AWST], str], awst_out_dir: Path, suffix: str\n) -> None:\n out_text = formatter(awst)\n awst_out_dir.mkdir(exist_ok=True)\n output_path = awst_out_dir \/ f\"module{suffix}\"\n logger.info(f\"writing {make_path_relative_to_cwd(output_path)}\")\n output_path.write_text(out_text, \"utf-8\")\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/compile.py","language":"Python","license":"NOASSERTION","size":9964} {"code":"import abc\nimport contextlib\nimport typing\nfrom collections.abc import Iterator, Mapping, Sequence, Set\nfrom functools import cached_property\n\nimport attrs\n\nfrom puya import log\nfrom puya.avm import OnCompletionAction\nfrom puya.awst.nodes import (\n AppStorageDefinition,\n AppStorageKind,\n ARC4ABIMethodConfig,\n ARC4BareMethodConfig,\n ARC4CreateOption,\n ContractMethod,\n StateTotals,\n)\nfrom puya.errors import CodeError\nfrom puya.parse import SourceLocation\nfrom puya.program_refs import ContractReference\nfrom puyapy.awst_build import pytypes\n\nlogger = log.get_logger(__name__)\n\n\n@attrs.frozen\nclass ContractClassOptions:\n name_override: str | None\n scratch_slot_reservations: Set[int] | None\n state_totals: StateTotals | None\n avm_version: int | None\n\n\n@attrs.frozen\nclass ARC4BareMethodData:\n pytype: pytypes.FuncType\n source_location: SourceLocation\n member_name: str\n config: ARC4BareMethodConfig\n is_bare: bool = attrs.field(default=True, init=False)\n\n\n@attrs.frozen\nclass ARC4ABIMethodData:\n pytype: pytypes.FuncType\n source_location: SourceLocation\n member_name: str\n config: ARC4ABIMethodConfig\n is_bare: bool = attrs.field(default=False, init=False)\n _signature: dict[str, pytypes.PyType]\n _arc4_signature: Mapping[str, pytypes.PyType] = attrs.field(init=False)\n\n @_arc4_signature.default\n def _arc4_signature_default(self) -> Mapping[str, pytypes.PyType]:\n from puyapy.awst_build.arc4_utils import pytype_to_arc4_pytype # TODO: resolve circularity\n\n def on_error(bad_type: pytypes.PyType) -> typing.Never:\n raise CodeError(\n f\"invalid type for an ARC4 method: {bad_type}\", self.config.source_location\n )\n\n return {k: pytype_to_arc4_pytype(v, on_error=on_error) for k, v in self._signature.items()}\n\n @property\n def signature(self) -> Mapping[str, pytypes.PyType]:\n return self._signature\n\n @cached_property\n def return_type(self) -> pytypes.PyType:\n return self._signature[\"output\"]\n\n @cached_property\n def arc4_return_type(self) -> pytypes.PyType:\n return self._arc4_signature[\"output\"]\n\n @cached_property\n def argument_types(self) -> Sequence[pytypes.PyType]:\n names, types = zip(*self._signature.items(), strict=True)\n assert names[-1] == \"output\"\n return tuple(types[:-1])\n\n @cached_property\n def arc4_argument_types(self) -> Sequence[pytypes.PyType]:\n names, types = zip(*self._arc4_signature.items(), strict=True)\n assert names[-1] == \"output\"\n return tuple(types[:-1])\n\n\nARC4MethodData: typing.TypeAlias = ARC4BareMethodData | ARC4ABIMethodData\n\n\n@attrs.define\nclass ContractFragmentStorage:\n member_name: str = attrs.field(on_setattr=attrs.setters.frozen)\n source_location: SourceLocation = attrs.field(on_setattr=attrs.setters.frozen)\n kind: AppStorageKind = attrs.field(on_setattr=attrs.setters.frozen)\n definition: AppStorageDefinition | None\n\n\n@attrs.define(kw_only=True)\nclass ContractFragmentMethod:\n member_name: str = attrs.field(on_setattr=attrs.setters.frozen)\n source_location: SourceLocation = attrs.field(on_setattr=attrs.setters.frozen)\n metadata: ARC4MethodData | None = attrs.field(on_setattr=attrs.setters.frozen)\n is_trivial: bool = attrs.field(on_setattr=attrs.setters.frozen)\n synthetic: bool = attrs.field(default=False, on_setattr=attrs.setters.frozen)\n inheritable: bool = attrs.field(default=True, on_setattr=attrs.setters.frozen)\n implementation: ContractMethod | None = attrs.field(default=None)\n\n @implementation.validator\n def _implementation_validate(self, _attr: object, value: ContractMethod | None) -> None:\n if value is None:\n return\n assert not self.is_trivial, \"trivial methods should not have an implementation\"\n assert value.member_name == self.member_name\n\n\nclass ContractFragmentBase(abc.ABC):\n @property\n @abc.abstractmethod\n def id(self) -> ContractReference: ...\n\n @property\n @abc.abstractmethod\n def mro(self) -> Sequence[\"ContractFragmentBase\"]: ...\n\n @property\n @abc.abstractmethod\n def symbols(self) -> Mapping[str, pytypes.PyType | None]: ...\n\n @typing.final\n def resolve_symbol(self, name: str) -> pytypes.PyType | None:\n for frag in (self, *self.mro):\n with contextlib.suppress(KeyError):\n return frag.symbols[name]\n return None\n\n @abc.abstractmethod\n def resolve_method(\n self, name: str, *, include_inherited: bool = True\n ) -> ContractFragmentMethod | None: ...\n\n @abc.abstractmethod\n def methods(\n self, *, include_inherited: bool = True, include_overridden: bool = False\n ) -> Iterator[ContractFragmentMethod]: ...\n\n @abc.abstractmethod\n def resolve_storage(\n self, name: str, *, include_inherited: bool = True\n ) -> ContractFragmentStorage | None: ...\n\n @abc.abstractmethod\n def state(self, *, include_inherited: bool = True) -> Iterator[ContractFragmentStorage]: ...\n\n @typing.final\n def find_arc4_method_metadata(\n self,\n *,\n bare: bool | None = None,\n oca: OnCompletionAction | None = None,\n can_create: bool | None = None,\n ) -> Iterator[ARC4MethodData]:\n for method in self.methods():\n md = method.metadata\n if md is not None:\n bare_matches = bare is None or bare == md.is_bare\n oca_matches = oca is None or oca in md.config.allowed_completion_types\n can_create_matches = can_create is None or (\n can_create != (md.config.create == ARC4CreateOption.disallow)\n )\n if bare_matches and oca_matches and can_create_matches:\n yield md\n\n\nConstantValue: typing.TypeAlias = int | str | bytes | bool\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/models.py","language":"Python","license":"NOASSERTION","size":5879} {"code":"from collections.abc import Sequence\nfrom pathlib import Path\n\nimport attrs\n\nfrom puya.log import LogLevel\nfrom puya.options import PuyaOptions\n\n\n@attrs.frozen(kw_only=True)\nclass PuyaPyOptions(PuyaOptions):\n paths: Sequence[Path] = attrs.field(default=(), repr=lambda p: str(list(map(str, p))))\n output_awst: bool = False\n output_awst_json: bool = False\n output_client: bool = False\n out_dir: Path | None = attrs.field(default=None, repr=False)\n log_level: LogLevel = LogLevel.info\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/options.py","language":"Python","license":"NOASSERTION","size":501} {"code":"from __future__ import annotations\n\nimport codecs\nimport enum\nimport os\nimport re\nimport typing\nfrom functools import cached_property\nfrom pathlib import Path\n\nimport attrs\nimport docstring_parser\nimport mypy.build\nimport mypy.errors\nimport mypy.find_sources\nimport mypy.fscache\nimport mypy.modulefinder\nimport mypy.nodes\nimport mypy.options\nimport mypy.util\n\nfrom puya import log\nfrom puya.awst.nodes import MethodDocumentation\nfrom puya.parse import SourceLocation\nfrom puya.utils import make_path_relative_to_cwd\n\nif typing.TYPE_CHECKING:\n from collections.abc import Mapping, Sequence, Set\n\nlogger = log.get_logger(__name__)\n_PUYAPY_SRC_ROOT = Path(__file__).parent\n_PUYA_SRC_ROOT = _PUYAPY_SRC_ROOT.parent \/ \"puya\"\nTYPESHED_PATH = _PUYAPY_SRC_ROOT \/ \"_typeshed\"\n_MYPY_FSCACHE = mypy.fscache.FileSystemCache()\n_MYPY_SEVERITY_TO_LOG_LEVEL = {\n \"error\": log.LogLevel.error,\n \"warning\": log.LogLevel.warning,\n \"note\": log.LogLevel.info,\n}\n\n\n@attrs.frozen\nclass EmbeddedSource:\n path: Path\n mypy_module_name: str\n puya_module_name: str\n\n @classmethod\n def from_path(cls, filename: str, *, module_override: str | None = None) -> typing.Self:\n path = _PUYA_SRC_ROOT \/ \"lib_embedded\" \/ filename\n return cls(\n path=path,\n mypy_module_name=path.stem,\n puya_module_name=module_override or path.stem,\n )\n\n\nclass SourceDiscoveryMechanism(enum.Enum):\n explicit_file = enum.auto()\n explicit_directory_walk = enum.auto()\n dependency = enum.auto()\n\n\n@attrs.frozen\nclass SourceModule:\n name: str\n node: mypy.nodes.MypyFile\n path: Path\n lines: Sequence[str] | None\n discovery_mechanism: SourceDiscoveryMechanism\n\n\n@attrs.frozen\nclass ParseResult:\n mypy_options: mypy.options.Options\n ordered_modules: Mapping[str, SourceModule]\n \"\"\"All discovered modules, topologically sorted by dependencies.\n The sort order is from leaves (nodes without dependencies) to\n roots (nodes on which no other nodes depend).\"\"\"\n\n @cached_property\n def sources_by_path(self) -> Mapping[Path, Sequence[str] | None]:\n return {s.path: s.lines for s in self.ordered_modules.values()}\n\n @cached_property\n def explicit_source_paths(self) -> Set[Path]:\n return {\n sm.path\n for sm in self.ordered_modules.values()\n if sm.discovery_mechanism != SourceDiscoveryMechanism.dependency\n }\n\n\ndef parse_and_typecheck(\n paths: Sequence[Path], mypy_options: mypy.options.Options\n) -> tuple[mypy.build.BuildManager, dict[str, SourceModule]]:\n \"\"\"Generate the ASTs from the build sources, and all imported modules (recursively)\"\"\"\n\n # ensure we have the absolute, canonical paths to the files\n resolved_input_paths = {p.resolve() for p in paths}\n # creates a list of BuildSource objects from the contract Paths\n mypy_build_sources = mypy.find_sources.create_source_list(\n paths=[str(p) for p in resolved_input_paths],\n options=mypy_options,\n fscache=_MYPY_FSCACHE,\n )\n build_source_paths = {\n Path(m.path).resolve() for m in mypy_build_sources if m.path and not m.followed\n }\n result = _mypy_build(mypy_build_sources, mypy_options, _MYPY_FSCACHE)\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(\"\", module=None, scope=None, options=mypy_options)\n missing_module_names = {s.module for s in mypy_build_sources} - result.manager.modules.keys()\n # Note: this shouldn't happen, provided we've successfully disabled the mypy cache\n assert (\n not missing_module_names\n ), f\"mypy parse failed, missing modules: {', '.join(missing_module_names)}\"\n\n # order modules by dependency, and also sanity check the contents\n ordered_modules = {}\n for scc_module_names in mypy.build.sorted_components(result.graph):\n for module_name in scc_module_names:\n module = result.manager.modules[module_name]\n assert (\n module_name == module.fullname\n ), f\"mypy module mismatch, expected {module_name}, got {module.fullname}\"\n assert module.path, f\"no path for mypy module: {module_name}\"\n module_path = Path(module.path).resolve()\n if module_path.is_dir():\n # this module is a module directory with no __init__.py, ie it contains\n # nothing and is only in the graph as a reference\n pass\n else:\n _check_encoding(_MYPY_FSCACHE, module_path)\n lines = mypy.util.read_py_file(str(module_path), _MYPY_FSCACHE.read)\n if module_path in resolved_input_paths:\n discovery_mechanism = SourceDiscoveryMechanism.explicit_file\n elif module_path in build_source_paths:\n discovery_mechanism = SourceDiscoveryMechanism.explicit_directory_walk\n else:\n discovery_mechanism = SourceDiscoveryMechanism.dependency\n ordered_modules[module_name] = SourceModule(\n name=module_name,\n node=module,\n path=module_path,\n lines=lines,\n discovery_mechanism=discovery_mechanism,\n )\n\n return result.manager, ordered_modules\n\n\ndef _check_encoding(mypy_fscache: mypy.fscache.FileSystemCache, module_path: Path) -> None:\n module_rel_path = make_path_relative_to_cwd(module_path)\n module_loc = SourceLocation(file=module_path, line=1)\n try:\n source = mypy_fscache.read(str(module_path))\n except OSError:\n logger.warning(\n f\"Couldn't read source for {module_rel_path}\",\n location=module_loc,\n )\n return\n # below is based on mypy\/util.py:decode_python_encoding\n # check for BOM UTF-8 encoding\n if source.startswith(b\"\\xef\\xbb\\xbf\"):\n return\n # otherwise look at first two lines and check if PEP-263 coding is present\n encoding, _ = mypy.util.find_python_encoding(source)\n # find the codec for this encoding and check it is utf-8\n codec = codecs.lookup(encoding)\n if codec.name != \"utf-8\":\n logger.warning(\n \"UH OH SPAGHETTI-O's,\"\n \" darn tootin' non-utf8(?!) encoded file encountered:\"\n f\" {module_rel_path} encoded as {encoding}\",\n location=module_loc,\n )\n\n\ndef _mypy_build(\n sources: list[mypy.modulefinder.BuildSource],\n options: mypy.options.Options,\n fscache: mypy.fscache.FileSystemCache | None,\n) -> mypy.build.BuildResult:\n \"\"\"Simple wrapper around mypy.build.build\n\n Makes it so that check errors and parse errors are handled the same (ie with an exception)\n \"\"\"\n\n all_messages = list[str]()\n\n def flush_errors(\n _filename: str | None,\n new_messages: list[str],\n _is_serious: bool, # noqa: FBT001\n ) -> None:\n all_messages.extend(msg for msg in new_messages if os.devnull not in msg)\n\n try:\n result = mypy.build.build(\n sources=sources,\n options=options,\n flush_errors=flush_errors,\n fscache=fscache,\n )\n finally:\n _log_mypy_messages(all_messages)\n return result\n\n\ndef _log_mypy_message(message: log.Log | None, related_lines: list[str]) -> None:\n if not message:\n return\n logger.log(\n message.level, message.message, location=message.location, related_lines=related_lines\n )\n\n\ndef _log_mypy_messages(messages: list[str]) -> None:\n first_message: log.Log | None = None\n related_messages = list[str]()\n for message_str in messages:\n message = _parse_log_message(message_str)\n if not first_message:\n first_message = message\n elif not message.location:\n # collate related error messages and log together\n related_messages.append(message.message)\n else:\n _log_mypy_message(first_message, related_messages)\n related_messages = []\n first_message = message\n _log_mypy_message(first_message, related_messages)\n\n\n_MYPY_LOG_MESSAGE = re.compile(\n r\"\"\"^\n (?P([A-Z]:\\\\)?[^:]*)(:(?P\\d+))?\n :\\s(?Perror|warning|note)\n :\\s(?P.*)$\"\"\",\n re.VERBOSE,\n)\n\n\ndef _parse_log_message(log_message: str) -> log.Log:\n match = _MYPY_LOG_MESSAGE.match(log_message)\n if match:\n matches = match.groupdict()\n return _try_parse_log_parts(\n matches.get(\"filename\"),\n matches.get(\"line\") or \"\",\n matches.get(\"severity\") or \"error\",\n matches[\"msg\"],\n )\n return log.Log(\n level=log.LogLevel.error,\n message=log_message,\n location=None,\n )\n\n\ndef _try_parse_log_parts(\n path_str: str | None, line_str: str, severity_str: str, msg: str\n) -> log.Log:\n if not path_str:\n location = None\n else:\n try:\n line = int(line_str)\n except ValueError:\n line = 1\n location = SourceLocation(file=Path(path_str).resolve(), line=line)\n level = _MYPY_SEVERITY_TO_LOG_LEVEL[severity_str]\n return log.Log(message=msg, level=level, location=location)\n\n\ndef _join_single_new_line(doc: str) -> str:\n return doc.strip().replace(\"\\n\", \" \")\n\n\ndef parse_docstring(docstring_raw: str | None) -> MethodDocumentation:\n if docstring_raw is None:\n return MethodDocumentation()\n docstring = docstring_parser.parse(docstring_raw)\n method_desc = \"\\n\".join(\n _join_single_new_line(line)\n for lines in filter(None, (docstring.short_description, docstring.long_description))\n for line in lines.split(\"\\n\\n\")\n )\n return MethodDocumentation(\n description=method_desc if method_desc else None,\n args={\n p.arg_name: _join_single_new_line(p.description)\n for p in docstring.params\n if p.description\n },\n returns=(\n _join_single_new_line(docstring.returns.description)\n if docstring.returns and docstring.returns.description\n else None\n ),\n )\n\n\ndef source_location_from_mypy(file: Path, node: mypy.nodes.Context) -> SourceLocation:\n assert node.line is not None\n assert node.line >= 1\n\n match node:\n case (\n mypy.nodes.FuncDef(body=body)\n | mypy.nodes.Decorator(func=mypy.nodes.FuncDef(body=body))\n ):\n # end_line of a function node includes the entire body\n # try to get just the signature\n end_line = node.line\n # no body means the end_line is ok to use\n if body is None:\n end_line = max(end_line, node.end_line or node.line)\n # if there is a body, attempt to use the first line before the body as the end\n else:\n end_line = max(end_line, body.line - 1)\n return SourceLocation(\n file=file,\n line=node.line,\n end_line=end_line,\n )\n case mypy.nodes.ClassDef(decorators=class_decorators, defs=class_body):\n line = node.line\n for dec in class_decorators:\n line = min(dec.line, line)\n end_line = max(line, class_body.line - 1)\n return SourceLocation(\n file=file,\n line=line,\n end_line=end_line,\n )\n case mypy.nodes.WhileStmt(body=compound_body) | mypy.nodes.ForStmt(body=compound_body):\n return SourceLocation(\n file=file,\n line=node.line,\n end_line=compound_body.line - 1,\n )\n case mypy.nodes.IfStmt(body=[*bodies], else_body=else_body):\n body_start: int | None = None\n if else_body is not None:\n bodies.append(else_body)\n for body in bodies:\n if body_start is None:\n body_start = body.line\n else:\n body_start = min(body_start, body.line)\n if body_start is None:\n # this shouldn't happen, there should be at least one body in one branch,\n # but this serves okay as a fallback\n end_line = node.end_line or node.line\n else:\n end_line = body_start - 1\n return SourceLocation(\n file=file,\n line=node.line,\n end_line=end_line,\n )\n return SourceLocation(\n file=file,\n line=node.line,\n end_line=(\n node.end_line if (node.end_line is not None and node.end_line >= 1) else node.line\n ),\n column=node.column if (node.column is not None and node.column >= 0) else 0,\n end_column=(\n node.end_column if (node.end_column is not None and node.end_column >= 0) else None\n ),\n )\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/parse.py","language":"Python","license":"NOASSERTION","size":12981} {"code":"import ast\nimport typing\n\nfrom puya.utils import valid_bytes, valid_int64\n\n\ndef parse_template_key_value(key_value_str: str) -> tuple[str, int | bytes]:\n try:\n name, value_str = key_value_str.split(\"=\", maxsplit=1)\n except ValueError:\n raise ValueError(f\"invalid template var definition: {key_value_str!r}\") from None\n\n if value_str.startswith(\"0x\"):\n value: int | bytes = bytes.fromhex(value_str[2:])\n else:\n try:\n literal = ast.literal_eval(value_str)\n except ValueError:\n literal = None\n match literal:\n case str(str_value):\n value = str_value.encode(\"utf8\")\n case bool(bool_value):\n value = int(bool_value)\n case int(value):\n pass\n case _:\n raise ValueError(f\"invalid template var definition: {key_value_str!r}\")\n match value:\n case int(int_result):\n too_big = not valid_int64(int_result)\n case bytes(bytes_result):\n too_big = not valid_bytes(bytes_result)\n case unexpected:\n typing.assert_never(unexpected)\n if too_big:\n raise ValueError(f\"template value {name!r} too big: {value_str}\")\n return name, value\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/template.py","language":"Python","license":"NOASSERTION","size":1262} {"code":"from pathlib import Path\n\nfrom puyapy.options import PuyaPyOptions\n\n\ndef determine_out_dir(contract_path: Path, options: PuyaPyOptions) -> Path:\n if not options.out_dir:\n out_dir = contract_path\n else:\n # find input path the contract is relative to\n for src_path in options.paths:\n src_path = src_path.resolve()\n src_path = src_path if src_path.is_dir() else src_path.parent\n try:\n relative_path = contract_path.relative_to(src_path)\n except ValueError:\n continue\n # construct a path that maintains a hierarchy to src_path\n out_dir = options.out_dir \/ relative_path\n if not options.out_dir.is_absolute():\n out_dir = src_path \/ out_dir\n break\n else:\n # if not relative to any input path\n if options.out_dir.is_absolute():\n out_dir = options.out_dir \/ contract_path\n else:\n out_dir = contract_path \/ options.out_dir\n\n out_dir.mkdir(parents=True, exist_ok=True)\n return out_dir\n","repo_name":"algorandfoundation\/puya","path":"src\/puyapy\/utils.py","language":"Python","license":"NOASSERTION","size":1111} {"code":"import typing\n\nif not typing.TYPE_CHECKING:\n raise RuntimeError(\n \"`import algopy` cannot be executed by the python interpreter. \"\n \"It is intended to be used by the puyapy compiler to compile \"\n \"Algorand smart contracts written in Algorand Python.\"\n \"For more details see \"\n \"https:\/\/algorandfoundation.github.io\/puya\/index.html#compiler-usage\"\n )\n","repo_name":"algorandfoundation\/puya","path":"stubs\/algopy.py","language":"Python","license":"NOASSERTION","size":391} {"code":"","repo_name":"algorandfoundation\/puya","path":"test_cases\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"import typing\n\nfrom algopy import (\n Account,\n Application,\n ARC4Contract,\n Asset,\n Bytes,\n OnCompleteAction,\n String,\n TransactionType,\n UInt64,\n arc4,\n gtxn,\n log,\n op,\n)\n\nBytes3: typing.TypeAlias = arc4.StaticArray[arc4.Byte, typing.Literal[3]]\n\n\nclass Reference(ARC4Contract):\n def __init__(self) -> None:\n self.asa = Asset(123)\n self.an_int = UInt64(2)\n self.some_bytes = Bytes3(arc4.Byte(7), arc4.Byte(8), arc4.Byte(9))\n self.creator = op.Txn.sender\n self.app = Application(123)\n\n assert arc4.arc4_signature(\"get(uint64,byte[])byte[]\"), \"has method selector\"\n\n @arc4.abimethod\n def noop_with_uint64(self, a: arc4.UInt64) -> arc4.UInt8:\n result = 1 + a.native\n return arc4.UInt8(result)\n\n @arc4.abimethod(\n allow_actions=[\n \"NoOp\",\n OnCompleteAction.OptIn,\n \"CloseOut\",\n OnCompleteAction.UpdateApplication,\n OnCompleteAction.DeleteApplication,\n ],\n name=\"all_the_things\",\n create=\"allow\",\n readonly=True,\n )\n def full_abi_config(self, a: arc4.UInt64) -> arc4.UInt8:\n result = UInt64(1) + a.native\n return arc4.UInt8(result)\n\n @arc4.abimethod(\n allow_actions=[\n \"NoOp\",\n \"CloseOut\",\n \"DeleteApplication\",\n ],\n create=\"disallow\",\n readonly=True,\n )\n def mixed_oca(self, a: arc4.UInt64) -> arc4.UInt8:\n result = UInt64(1) + a.native\n return arc4.UInt8(result)\n\n @arc4.baremethod(\n allow_actions=[\n \"NoOp\",\n \"OptIn\",\n \"CloseOut\",\n \"UpdateApplication\",\n \"DeleteApplication\",\n ],\n create=\"require\",\n )\n def bare_abi_config(self) -> None:\n log(\"Hello World\")\n\n @arc4.abimethod\n def opt_into_asset(self, asset: Asset) -> None:\n # Only allow app creator to opt the app account into a ASA\n assert op.Txn.sender == op.Global.creator_address, \"Only creator can opt in to ASA\"\n # Verify a ASA hasn't already been opted into\n assert not self.asa, \"ASA already opted in\"\n # Save ASA ID in global state\n self.asa = asset\n\n # Submit opt-in transaction: 0 asset transfer to self\n op.ITxnCreate.begin()\n op.ITxnCreate.set_type_enum(TransactionType.AssetTransfer)\n op.ITxnCreate.set_fee(UInt64(0)) # cover fee with outer txn\n op.ITxnCreate.set_asset_receiver(op.Global.current_application_address)\n op.ITxnCreate.set_xfer_asset(asset)\n op.ITxnCreate.submit()\n\n @arc4.abimethod\n def with_transactions(\n self,\n asset: Asset,\n an_int: arc4.UInt64,\n pay: gtxn.PaymentTransaction,\n another_int: arc4.UInt64,\n ) -> None:\n assert self.asa == asset, \"is correct asset\"\n assert an_int.native == 1, \"is correct int\"\n assert pay.receiver == op.Global.current_application_address, \"is payment to app\"\n assert another_int.native == 2, \"is correct int\"\n\n @arc4.abimethod\n def compare_assets(self, asset_a: Asset, asset_b: Asset) -> None:\n assert asset_a == asset_b, \"asset a == b\"\n\n @arc4.abimethod(readonly=True)\n def get_address(self) -> arc4.Address:\n return arc4.Address()\n\n @arc4.abimethod(readonly=True)\n def get_asset(self) -> arc4.UInt64:\n return arc4.UInt64(456)\n\n @arc4.abimethod(readonly=True, name=\"get_application\")\n def get_app(self) -> arc4.UInt64:\n return arc4.UInt64(456)\n\n @arc4.abimethod(readonly=True, name=\"get_an_int\")\n def get_a_int(self) -> arc4.UInt64:\n return arc4.UInt64(3)\n\n @arc4.abimethod(\n default_args={\n \"asset_from_storage\": \"asa\",\n \"asset_from_function\": get_asset,\n \"account_from_storage\": \"creator\",\n \"account_from_function\": \"get_address\",\n \"application_from_storage\": \"app\",\n \"application_from_function\": get_app,\n \"bytes_from_storage\": \"some_bytes\",\n \"int_from_storage\": \"an_int\",\n \"int_from_function\": \"get_a_int\",\n \"int_from_const\": arc4.UInt32(123),\n \"str_from_const\": arc4.String(\"abc\"),\n }\n )\n def method_with_default_args(\n self,\n asset_from_storage: Asset,\n asset_from_function: Asset,\n account_from_storage: Account,\n account_from_function: Account,\n application_from_storage: Application,\n application_from_function: Application,\n bytes_from_storage: Bytes3,\n int_from_storage: arc4.UInt64,\n int_from_function: arc4.UInt64,\n int_from_const: arc4.UInt32,\n str_from_const: arc4.String,\n ) -> None:\n assert asset_from_storage == Asset(123), \"wrong asset from storage\"\n assert asset_from_function == Asset(456), \"wrong asset from function\"\n assert account_from_storage == op.Global.creator_address, \"wrong account from storage\"\n assert account_from_function == op.Global.zero_address, \"wrong account from function\"\n assert application_from_storage == Application(123), \"wrong application from storage\"\n assert application_from_function == Application(456), \"wrong application from function\"\n assert bytes_from_storage[0] == arc4.Byte(7), \"wrong 0th byte from storage\"\n assert bytes_from_storage[1] == arc4.Byte(8), \"wrong 1st byte from storage\"\n assert bytes_from_storage[2] == arc4.Byte(9), \"wrong 2nd byte from storage\"\n assert int_from_storage.native == 2, \"wrong int from storage\"\n assert int_from_function.native == 3, \"wrong int from function\"\n assert int_from_const == 123\n assert str_from_const == \"abc\"\n\n @arc4.abimethod\n def method_with_15_args(\n self,\n one: UInt64,\n two: UInt64,\n three: UInt64,\n four: UInt64,\n five: UInt64,\n six: UInt64,\n seven: UInt64,\n eight: UInt64,\n nine: UInt64,\n ten: UInt64,\n eleven: UInt64,\n twelve: UInt64,\n thirteen: UInt64,\n fourteen: UInt64,\n fifteen: Bytes,\n ) -> Bytes:\n \"\"\"Fifteen args should not encode the last argument as a tuple\"\"\"\n assert (\n one\n + two\n + three\n + four\n + five\n + six\n + seven\n + eight\n + nine\n + ten\n + eleven\n + twelve\n + thirteen\n + fourteen\n )\n return fifteen\n\n @arc4.abimethod\n def method_with_more_than_15_args(\n self,\n a: arc4.UInt64,\n b: arc4.UInt64,\n c: arc4.UInt64,\n d: UInt64,\n asset: Asset,\n e: arc4.UInt64,\n f: arc4.UInt64,\n pay: gtxn.PaymentTransaction,\n g: arc4.UInt64,\n h: arc4.UInt64,\n i: arc4.UInt64,\n j: arc4.UInt64,\n k: arc4.UInt64,\n # ruff: noqa: E741\n l: arc4.UInt64,\n m: arc4.UInt64,\n n: arc4.UInt64,\n o: arc4.UInt64,\n p: UInt64,\n q: arc4.UInt64,\n r: arc4.UInt64,\n s: Bytes,\n t: Bytes,\n asset2: Asset,\n pay2: gtxn.PaymentTransaction,\n u: arc4.UInt64,\n v: arc4.UInt64,\n ) -> arc4.UInt64:\n \"\"\"\n Application calls only support 16 args, and arc4 calls utilise the first arg for the method\n selector. Args beyond this number are packed into a tuple and placed in the 16th slot.\n \"\"\"\n assert op.Txn.num_app_args == 16\n assert pay.amount == 100000\n assert pay2.amount == 200000\n assert asset.id\n assert asset2.id\n\n log(s + t)\n\n return arc4.UInt64(\n a.native\n + b.native\n + c.native\n + d\n + e.native\n + f.native\n + g.native\n + h.native\n + i.native\n + j.native\n + k.native\n + l.native\n + m.native\n + n.native\n + o.native\n + p\n + q.native\n + r.native\n + u.native\n + v.native\n )\n\n @arc4.abimethod\n def hello_with_algopy_string(self, name: String) -> String:\n return \"Hello \" + name + \"!\"\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/abi_routing\/contract.py","language":"Python","license":"NOASSERTION","size":8358} {"code":"import typing\n\nfrom algopy import ARC4Contract, Txn, UInt64, arc4, log, op\n\n\nclass CustomApproval(ARC4Contract):\n def __init__(self) -> None:\n super().__init__()\n assert Txn.application_id == 0, \"nonsense assert just to generate an init method\"\n\n @typing.override\n def approval_program(self) -> bool:\n if Txn.num_app_args == 2 and Txn.application_args(1) == op.itob(42):\n log(\"\ud83c\udf89\ud83c\udf89\ud83c\udf89\")\n result = super().approval_program()\n if not result:\n log(\n \"this will never be seen unless you're running in simulation mode anyway\"\n \" so I can say whatever I want here\"\n )\n return result\n\n @arc4.abimethod\n def add_one(self, x: UInt64) -> UInt64:\n return x + 1\n\n\nclass CustomApproval2(CustomApproval):\n @typing.override\n def approval_program(self) -> bool:\n return False\n\n\nclass CustomApproval3(ARC4Contract):\n @arc4.abimethod\n def unused(self) -> None:\n return\n\n @typing.override\n def approval_program(self) -> bool:\n return False\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/abi_routing\/custom_approval.py","language":"Python","license":"NOASSERTION","size":1092} {"code":"from algopy import ARC4Contract, UInt64\n\n\nclass MinimumARC4(ARC4Contract):\n def __init__(self) -> None:\n self.gvalue = UInt64(4)\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/abi_routing\/minimal.py","language":"Python","license":"NOASSERTION","size":139} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass CustomApproval(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def add_one(\n self,\n x: algopy.arc4.UIntN[typing.Literal[64]],\n ) -> algopy.arc4.UIntN[typing.Literal[64]]: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/abi_routing\/out\/client_CustomApproval.py","language":"Python","license":"NOASSERTION","size":325} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass CustomApproval2(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def add_one(\n self,\n x: algopy.arc4.UIntN[typing.Literal[64]],\n ) -> algopy.arc4.UIntN[typing.Literal[64]]: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/abi_routing\/out\/client_CustomApproval2.py","language":"Python","license":"NOASSERTION","size":326} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass CustomApproval3(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def unused(\n self,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/abi_routing\/out\/client_CustomApproval3.py","language":"Python","license":"NOASSERTION","size":242} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass MinimumARC4(algopy.arc4.ARC4Client, typing.Protocol):\n pass\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/abi_routing\/out\/client_MinimumARC4.py","language":"Python","license":"NOASSERTION","size":171} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass Reference(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def noop_with_uint64(\n self,\n a: algopy.arc4.UIntN[typing.Literal[64]],\n ) -> algopy.arc4.UIntN[typing.Literal[8]]: ...\n\n @algopy.arc4.abimethod(readonly=True, allow_actions=['NoOp', 'OptIn', 'CloseOut', 'UpdateApplication', 'DeleteApplication'], create='allow')\n def all_the_things(\n self,\n a: algopy.arc4.UIntN[typing.Literal[64]],\n ) -> algopy.arc4.UIntN[typing.Literal[8]]: ...\n\n @algopy.arc4.abimethod(readonly=True, allow_actions=['NoOp', 'CloseOut', 'DeleteApplication'])\n def mixed_oca(\n self,\n a: algopy.arc4.UIntN[typing.Literal[64]],\n ) -> algopy.arc4.UIntN[typing.Literal[8]]: ...\n\n @algopy.arc4.abimethod\n def opt_into_asset(\n self,\n asset: algopy.Asset,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def with_transactions(\n self,\n asset: algopy.Asset,\n an_int: algopy.arc4.UIntN[typing.Literal[64]],\n pay: algopy.gtxn.PaymentTransaction,\n another_int: algopy.arc4.UIntN[typing.Literal[64]],\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def compare_assets(\n self,\n asset_a: algopy.Asset,\n asset_b: algopy.Asset,\n ) -> None: ...\n\n @algopy.arc4.abimethod(readonly=True)\n def get_address(\n self,\n ) -> algopy.arc4.Address: ...\n\n @algopy.arc4.abimethod(readonly=True)\n def get_asset(\n self,\n ) -> algopy.arc4.UIntN[typing.Literal[64]]: ...\n\n @algopy.arc4.abimethod(readonly=True)\n def get_application(\n self,\n ) -> algopy.arc4.UIntN[typing.Literal[64]]: ...\n\n @algopy.arc4.abimethod(readonly=True)\n def get_an_int(\n self,\n ) -> algopy.arc4.UIntN[typing.Literal[64]]: ...\n\n @algopy.arc4.abimethod\n def method_with_default_args(\n self,\n asset_from_storage: algopy.Asset,\n asset_from_function: algopy.Asset,\n account_from_storage: algopy.Account,\n account_from_function: algopy.Account,\n application_from_storage: algopy.Application,\n application_from_function: algopy.Application,\n bytes_from_storage: algopy.arc4.StaticArray[algopy.arc4.Byte, typing.Literal[3]],\n int_from_storage: algopy.arc4.UIntN[typing.Literal[64]],\n int_from_function: algopy.arc4.UIntN[typing.Literal[64]],\n int_from_const: algopy.arc4.UIntN[typing.Literal[32]],\n str_from_const: algopy.arc4.String,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def method_with_15_args(\n self,\n one: algopy.arc4.UIntN[typing.Literal[64]],\n two: algopy.arc4.UIntN[typing.Literal[64]],\n three: algopy.arc4.UIntN[typing.Literal[64]],\n four: algopy.arc4.UIntN[typing.Literal[64]],\n five: algopy.arc4.UIntN[typing.Literal[64]],\n six: algopy.arc4.UIntN[typing.Literal[64]],\n seven: algopy.arc4.UIntN[typing.Literal[64]],\n eight: algopy.arc4.UIntN[typing.Literal[64]],\n nine: algopy.arc4.UIntN[typing.Literal[64]],\n ten: algopy.arc4.UIntN[typing.Literal[64]],\n eleven: algopy.arc4.UIntN[typing.Literal[64]],\n twelve: algopy.arc4.UIntN[typing.Literal[64]],\n thirteen: algopy.arc4.UIntN[typing.Literal[64]],\n fourteen: algopy.arc4.UIntN[typing.Literal[64]],\n fifteen: algopy.arc4.DynamicBytes,\n ) -> algopy.arc4.DynamicBytes:\n \"\"\"\n Fifteen args should not encode the last argument as a tuple\n \"\"\"\n\n @algopy.arc4.abimethod\n def method_with_more_than_15_args(\n self,\n a: algopy.arc4.UIntN[typing.Literal[64]],\n b: algopy.arc4.UIntN[typing.Literal[64]],\n c: algopy.arc4.UIntN[typing.Literal[64]],\n d: algopy.arc4.UIntN[typing.Literal[64]],\n asset: algopy.Asset,\n e: algopy.arc4.UIntN[typing.Literal[64]],\n f: algopy.arc4.UIntN[typing.Literal[64]],\n pay: algopy.gtxn.PaymentTransaction,\n g: algopy.arc4.UIntN[typing.Literal[64]],\n h: algopy.arc4.UIntN[typing.Literal[64]],\n i: algopy.arc4.UIntN[typing.Literal[64]],\n j: algopy.arc4.UIntN[typing.Literal[64]],\n k: algopy.arc4.UIntN[typing.Literal[64]],\n l: algopy.arc4.UIntN[typing.Literal[64]],\n m: algopy.arc4.UIntN[typing.Literal[64]],\n n: algopy.arc4.UIntN[typing.Literal[64]],\n o: algopy.arc4.UIntN[typing.Literal[64]],\n p: algopy.arc4.UIntN[typing.Literal[64]],\n q: algopy.arc4.UIntN[typing.Literal[64]],\n r: algopy.arc4.UIntN[typing.Literal[64]],\n s: algopy.arc4.DynamicBytes,\n t: algopy.arc4.DynamicBytes,\n asset2: algopy.Asset,\n pay2: algopy.gtxn.PaymentTransaction,\n u: algopy.arc4.UIntN[typing.Literal[64]],\n v: algopy.arc4.UIntN[typing.Literal[64]],\n ) -> algopy.arc4.UIntN[typing.Literal[64]]:\n \"\"\"\n Application calls only support 16 args, and arc4 calls utilise the first arg for the method\n selector. Args beyond this number are packed into a tuple and placed in the 16th slot.\n \"\"\"\n\n @algopy.arc4.abimethod\n def hello_with_algopy_string(\n self,\n name: algopy.arc4.String,\n ) -> algopy.arc4.String: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/abi_routing\/out\/client_Reference.py","language":"Python","license":"NOASSERTION","size":5307} {"code":"from algopy import (\n Application,\n Bytes,\n Contract,\n LocalState,\n Txn,\n UInt64,\n op,\n subroutine,\n)\n\n\nclass Reference(Contract):\n def __init__(self) -> None:\n self.int_1 = UInt64(0)\n self.bytes_1 = Bytes(b\"\")\n self.bytes_2 = Bytes(b\"\")\n self.int_l1 = LocalState(UInt64)\n self.int_l2 = LocalState(UInt64)\n self.int_l3 = LocalState(UInt64)\n self.bytes_l1 = LocalState(Bytes)\n self.bytes_l2 = LocalState(Bytes)\n self.bytes_l3 = LocalState(Bytes)\n self.bytes_l4 = LocalState(Bytes)\n\n def approval_program(self) -> bool:\n if op.Txn.num_app_args == 1:\n if op.Txn.application_args(0) == b\"validate\":\n self.validate_asset(op.Global.current_application_id)\n else:\n assert False, \"Expected validate\"\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n @subroutine\n def validate_asset(self, app: Application) -> None:\n assert not Txn.sender.is_opted_in(app), \"app opted in\"\n assert app.creator == op.Global.creator_address, \"expected creator\"\n assert app.global_num_uint == 1, \"expected global_num_uint\"\n assert app.global_num_bytes == 2, \"expected global_num_bytes\"\n assert app.local_num_uint == 3, \"expected local_num_uint\"\n assert app.local_num_bytes == 4, \"expected local_num_bytes\"\n assert app.approval_program, \"expected approval_program\"\n assert app.clear_state_program, \"expected clear_state_program\"\n assert app == op.Global.current_application_id, \"expected current_application_id\"\n assert (\n app.address == op.Global.current_application_address\n ), \"expected current_application_address\"\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/application\/contract.py","language":"Python","license":"NOASSERTION","size":1777} {"code":"import typing\n\nfrom algopy import ARC4Contract, arc4, log, subroutine\n\n\nclass StaticStruct(arc4.Struct):\n a: arc4.UInt64\n b: arc4.StaticArray[arc4.Byte, typing.Literal[2]]\n\n\nclass DynamicStruct(arc4.Struct):\n a: arc4.String\n b: arc4.String\n\n\nclass MixedSingleStruct(arc4.Struct):\n a: arc4.UInt64\n b: arc4.String\n c: arc4.UInt64\n\n\nclass MixedMultipleStruct(arc4.Struct):\n a: arc4.UInt64\n b: arc4.String\n c: arc4.UInt64\n d: arc4.DynamicArray[arc4.UInt16]\n e: arc4.UInt64\n\n\nclass NestedDynamicStruct(arc4.Struct):\n one: StaticStruct\n two: DynamicStruct\n three: StaticStruct\n four: MixedMultipleStruct\n five: DynamicStruct\n\n\nclass DynamicArrayContract(ARC4Contract):\n @arc4.abimethod()\n def test_static_elements(self) -> None:\n byte_array1 = arc4.StaticArray(get_byte1(), get_byte2())\n byte_array2 = arc4.StaticArray(get_byte3(), get_byte4())\n\n struct1 = StaticStruct(get_uint1(), byte_array1.copy())\n struct2 = StaticStruct(get_uint2(), byte_array2.copy())\n array = arc4.DynamicArray(struct1.copy(), struct1.copy())\n array[1] = struct2.copy()\n log(array)\n log(array[0])\n log(array[1])\n\n assert array.pop() == struct2\n assert array.pop() == struct1\n\n @arc4.abimethod()\n def test_dynamic_elements(self) -> None:\n struct1 = DynamicStruct(get_string1(), get_string2())\n struct2 = DynamicStruct(get_string3(), get_string1())\n array = arc4.DynamicArray(struct1.copy(), struct1.copy())\n array.append(struct1.copy())\n array[1] = struct2.copy() # replace\n log(array)\n log(array[0])\n log(array[1])\n log(array[2])\n\n assert array.pop() == struct1\n log(array)\n assert array.pop() == struct2\n log(array)\n assert array.pop() == struct1\n log(array)\n\n @arc4.abimethod()\n def test_mixed_single_dynamic_elements(self) -> None:\n struct1 = MixedSingleStruct(get_uint1(), get_string1(), get_uint2())\n struct2 = MixedSingleStruct(get_uint2(), get_string2(), get_uint1())\n array = arc4.DynamicArray[MixedSingleStruct]()\n array.append(struct2.copy())\n array.append(struct2.copy())\n array[0] = struct1.copy() # replace\n log(array)\n log(array[0])\n log(array[1])\n\n assert array.pop() == struct2\n assert array.pop() == struct1\n\n @arc4.abimethod()\n def test_mixed_multiple_dynamic_elements(self) -> None:\n struct1 = MixedMultipleStruct(\n get_uint1(), get_string1(), get_uint2(), get_u16_arr1(), get_uint1()\n )\n struct2 = MixedMultipleStruct(\n get_uint2(), get_string2(), get_uint1(), get_u16_arr2(), get_uint2()\n )\n array = arc4.DynamicArray(struct1.copy(), struct1.copy())\n array[1] = struct2.copy()\n log(array)\n log(array[0])\n log(array[1])\n\n assert array.pop() == struct2\n assert array.pop() == struct1\n\n @arc4.abimethod()\n def test_nested_struct_replacement(self) -> None:\n one = StaticStruct(get_uint1(), arc4.StaticArray(get_byte1(), get_byte2()))\n two = DynamicStruct(get_string1(), get_string2())\n three = StaticStruct(get_uint2(), arc4.StaticArray(get_byte2(), get_byte1()))\n four = MixedMultipleStruct(\n get_uint1(), get_string1(), get_uint2(), get_u16_arr1(), get_uint1()\n )\n five = DynamicStruct(get_string1(), get_string2())\n struct1 = NestedDynamicStruct(\n one=one.copy(),\n two=two.copy(),\n three=three.copy(),\n four=four.copy(),\n five=five.copy(),\n )\n struct2 = NestedDynamicStruct(\n one=one.copy(),\n two=DynamicStruct(get_string2(), get_string1()), # this is the difference with struct1\n three=three.copy(),\n four=four.copy(),\n five=five.copy(),\n )\n\n struct2.two = two.copy() # now struct2 should match struct1\n assert struct1.bytes == struct2.bytes, \"struct1 does not match struct2\"\n\n @arc4.abimethod()\n def test_nested_tuple_modification(self) -> None:\n one = StaticStruct(get_uint1(), arc4.StaticArray(get_byte1(), get_byte2()))\n two = DynamicStruct(get_string1(), get_string2())\n three = StaticStruct(get_uint2(), arc4.StaticArray(get_byte2(), get_byte1()))\n four1 = MixedMultipleStruct(\n get_uint1(), get_string1(), get_uint2(), get_u16_arr1(), get_uint1()\n )\n four2 = MixedMultipleStruct(\n get_uint1(),\n get_string1(),\n get_uint2(),\n get_u16_arr1() + (arc4.UInt16(123),), # noqa: RUF005\n get_uint1(),\n )\n five = DynamicStruct(get_string1(), get_string2())\n tup1 = arc4.Tuple(\n (\n one.copy(),\n two.copy(),\n three.copy(),\n four1.copy(),\n five.copy(),\n )\n )\n tup2 = arc4.Tuple(\n (\n one.copy(),\n two.copy(),\n three.copy(),\n four2.copy(),\n five.copy(),\n )\n )\n\n tup2[3].d.pop()\n assert tup1.bytes == tup2.bytes, \"tup1 does not match tup2\"\n\n\n@subroutine\ndef get_string1() -> arc4.String:\n return arc4.String(\"a\")\n\n\n@subroutine\ndef get_string2() -> arc4.String:\n return arc4.String(\"bee\")\n\n\n@subroutine\ndef get_string3() -> arc4.String:\n return arc4.String(\"Hello World\")\n\n\n@subroutine\ndef get_uint1() -> arc4.UInt64:\n return arc4.UInt64(3)\n\n\n@subroutine\ndef get_uint2() -> arc4.UInt64:\n return arc4.UInt64(2**42)\n\n\n@subroutine\ndef get_byte1() -> arc4.Byte:\n return arc4.Byte(4)\n\n\n@subroutine\ndef get_byte2() -> arc4.Byte:\n return arc4.Byte(5)\n\n\n@subroutine\ndef get_byte3() -> arc4.Byte:\n return arc4.Byte(42)\n\n\n@subroutine\ndef get_byte4() -> arc4.Byte:\n return arc4.Byte(255)\n\n\n@subroutine\ndef get_u16_arr1() -> arc4.DynamicArray[arc4.UInt16]:\n return arc4.DynamicArray(arc4.UInt16(2**16 - 1), arc4.UInt16(0), arc4.UInt16(42))\n\n\n@subroutine\ndef get_u16_arr2() -> arc4.DynamicArray[arc4.UInt16]:\n return arc4.DynamicArray(arc4.UInt16(1), arc4.UInt16(2), arc4.UInt16(3), arc4.UInt16(4))\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc4_dynamic_arrays\/contract.py","language":"Python","license":"NOASSERTION","size":6313} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass DynamicArrayContract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def test_static_elements(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_dynamic_elements(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_mixed_single_dynamic_elements(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_mixed_multiple_dynamic_elements(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_nested_struct_replacement(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_nested_tuple_modification(\n self,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc4_dynamic_arrays\/out\/client_DynamicArrayContract.py","language":"Python","license":"NOASSERTION","size":767} {"code":"# ruff: noqa: SIM201, SIM202, SIM300, PLR0124\nimport typing as t\n\nfrom algopy import BigUInt, Contract, UInt64, arc4, subroutine\n\n\nclass UIntNOrdering(Contract):\n def approval_program(self) -> bool:\n check_both_uint_n(arc4.Byte(1), arc4.UInt64(2))\n check_mixed(arc4.Byte(1), arc4.BigUIntN[t.Literal[264]](2))\n check_both_big_uint_n(arc4.UInt256(1), arc4.BigUIntN[t.Literal[264]](2))\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n\n@subroutine\ndef check_both_uint_n(one: arc4.Byte, two: arc4.UInt64) -> None:\n one_uint64 = UInt64(1)\n one_biguint = BigUInt(1)\n\n two_uint64 = UInt64(2)\n two_biguint = BigUInt(2)\n\n assert one == 1\n assert 1 == one\n assert one == one\n assert one == one_uint64\n assert one == one_biguint\n assert not (one == 2)\n assert not (one == two)\n assert not (one == two_uint64)\n assert not (one == two_biguint)\n\n assert not (one != 1)\n assert not (1 != one)\n assert not (one != one)\n assert not (one != one_uint64)\n assert not (one != one_biguint)\n assert one != 2\n assert one != two\n assert one != two_uint64\n assert one != two_biguint\n\n assert one <= 1\n assert 1 <= one\n assert one <= one\n assert one <= one_uint64\n assert one <= one_biguint\n assert one <= 2\n assert one <= two\n assert one <= two_uint64\n assert one <= two_biguint\n\n assert not (one < 1)\n assert not (1 < one)\n assert not (one < one)\n assert not (one < one_uint64)\n assert not (one < one_biguint)\n assert one < 2\n assert one < two\n assert one < two_uint64\n assert one < two_biguint\n\n assert one >= 1\n assert 1 >= one\n assert one >= one\n assert one >= one_uint64\n assert one >= one_biguint\n assert not (one >= 2)\n assert not (one >= two)\n assert not (one >= two_uint64)\n assert not (one >= two_biguint)\n\n assert not (one > 1)\n assert not (1 > one)\n assert not (one > one)\n assert not (one > one_uint64)\n assert not (one > one_biguint)\n assert not (one > 2)\n assert not (one > two)\n assert not (one > two_uint64)\n assert not (one > two_biguint)\n\n\n@subroutine\ndef check_mixed(one: arc4.Byte, two: arc4.BigUIntN[t.Literal[264]]) -> None:\n one_uint64 = UInt64(1)\n one_biguint = BigUInt(1)\n\n two_uint64 = UInt64(2)\n two_biguint = BigUInt(2)\n\n assert one == 1\n assert 1 == one\n assert one == one\n assert one == one_uint64\n assert one == one_biguint\n assert not (one == 2)\n assert not (one == two)\n assert not (one == two_uint64)\n assert not (one == two_biguint)\n\n assert not (one != 1)\n assert not (1 != one)\n assert not (one != one)\n assert not (one != one_uint64)\n assert not (one != one_biguint)\n assert one != 2\n assert one != two\n assert one != two_uint64\n assert one != two_biguint\n\n assert one <= 1\n assert 1 <= one\n assert one <= one\n assert one <= one_uint64\n assert one <= one_biguint\n assert one <= 2\n assert one <= two\n assert one <= two_uint64\n assert one <= two_biguint\n\n assert not (one < 1)\n assert not (1 < one)\n assert not (one < one)\n assert not (one < one_uint64)\n assert not (one < one_biguint)\n assert one < 2\n assert one < two\n assert one < two_uint64\n assert one < two_biguint\n\n assert one >= 1\n assert 1 >= one\n assert one >= one\n assert one >= one_uint64\n assert one >= one_biguint\n assert not (one >= 2)\n assert not (one >= two)\n assert not (one >= two_uint64)\n assert not (one >= two_biguint)\n\n assert not (one > 1)\n assert not (1 > one)\n assert not (one > one)\n assert not (one > one_uint64)\n assert not (one > one_biguint)\n assert not (one > 2)\n assert not (one > two)\n assert not (one > two_uint64)\n assert not (one > two_biguint)\n\n\n@subroutine\ndef check_both_big_uint_n(one: arc4.UInt256, two: arc4.BigUIntN[t.Literal[264]]) -> None:\n one_uint64 = UInt64(1)\n one_biguint = BigUInt(1)\n\n two_uint64 = UInt64(2)\n two_biguint = BigUInt(2)\n\n assert one == 1\n assert 1 == one\n assert one == one\n assert one == one_uint64\n assert one == one_biguint\n assert not (one == 2)\n assert not (one == two)\n assert not (one == two_uint64)\n assert not (one == two_biguint)\n\n assert not (one != 1)\n assert not (1 != one)\n assert not (one != one)\n assert not (one != one_uint64)\n assert not (one != one_biguint)\n assert one != 2\n assert one != two\n assert one != two_uint64\n assert one != two_biguint\n\n assert one <= 1\n assert 1 <= one\n assert one <= one\n assert one <= one_uint64\n assert one <= one_biguint\n assert one <= 2\n assert one <= two\n assert one <= two_uint64\n assert one <= two_biguint\n\n assert not (one < 1)\n assert not (1 < one)\n assert not (one < one)\n assert not (one < one_uint64)\n assert not (one < one_biguint)\n assert one < 2\n assert one < two\n assert one < two_uint64\n assert one < two_biguint\n\n assert one >= 1\n assert 1 >= one\n assert one >= one\n assert one >= one_uint64\n assert one >= one_biguint\n assert not (one >= 2)\n assert not (one >= two)\n assert not (one >= two_uint64)\n assert not (one >= two_biguint)\n\n assert not (one > 1)\n assert not (1 > one)\n assert not (one > one)\n assert not (one > one_uint64)\n assert not (one > one_biguint)\n assert not (one > 2)\n assert not (one > two)\n assert not (one > two_uint64)\n assert not (one > two_biguint)\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc4_numeric_comparisons\/uint_n.py","language":"Python","license":"NOASSERTION","size":5550} {"code":"from algopy import Contract, Global, Txn, arc4\n\nSOME_ADDRESS = \"VCMJKWOY5P5P7SKMZFFOCEROPJCZOTIJMNIYNUCKH7LRO45JMJP6UYBIJA\"\n\n\nclass Arc4AddressContract(Contract):\n def approval_program(self) -> bool:\n address = arc4.Address(Txn.sender)\n assert address == Txn.sender\n assert address.length == 32\n assert address.native == Txn.sender\n\n zero_address = arc4.Address(Global.zero_address.bytes)\n assert zero_address.bytes == Global.zero_address.bytes\n\n some_address = arc4.Address(SOME_ADDRESS)\n assert some_address == SOME_ADDRESS\n\n address_copy = some_address\n\n assert some_address == address_copy\n return True\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc4_types\/address.py","language":"Python","license":"NOASSERTION","size":751} {"code":"import typing as t\n\nfrom algopy import Bytes, Contract, String, UInt64, op, subroutine, uenumerate\nfrom algopy.arc4 import (\n Byte,\n DynamicArray,\n StaticArray,\n String as ARC4String,\n UFixedNxM,\n UInt8,\n UInt16,\n UInt32,\n)\n\nAliasedDynamicArray: t.TypeAlias = DynamicArray[UInt16]\nAliasedStaticArray: t.TypeAlias = StaticArray[UInt8, t.Literal[1]]\n\nDecimal: t.TypeAlias = UFixedNxM[t.Literal[64], t.Literal[10]]\n\nHashResult: t.TypeAlias = StaticArray[Byte, t.Literal[32]]\n\n\nclass Arc4ArraysContract(Contract):\n def approval_program(self) -> bool:\n dynamic_uint8_array = DynamicArray[UInt8](UInt8(1), UInt8(2))\n total = UInt64(0)\n for uint8_item in dynamic_uint8_array:\n total += uint8_item.native\n\n assert total == 3, \"Total should be sum of dynamic_uint8_array items\"\n aliased_dynamic = AliasedDynamicArray(UInt16(1))\n for uint16_item in aliased_dynamic:\n total += uint16_item.native\n assert total == 4, \"Total should now include sum of aliased_dynamic items\"\n dynamic_string_array = DynamicArray[ARC4String](ARC4String(\"Hello\"), ARC4String(\"World\"))\n assert dynamic_string_array.length == 2\n assert dynamic_string_array[0] == ARC4String(\"Hello\")\n result = String(\"\")\n for index, string_item in uenumerate(dynamic_string_array):\n if index == 0:\n result = string_item.native\n else:\n result += \" \" + string_item.native\n\n assert result == \"Hello World\"\n\n static_uint32_array = StaticArray(UInt32(1), UInt32(10), UInt32(255), UInt32(128))\n\n for uint32_item in static_uint32_array:\n total += uint32_item.native\n\n assert total == 4 + 1 + 10 + 255 + 128\n\n aliased_static = AliasedStaticArray(UInt8(101))\n\n index = UInt64(0)\n\n assert (aliased_static[0].native + aliased_static[index].native) == 202\n\n static_string_array = StaticArray(ARC4String(\"Ping\"), ARC4String(\"Pong\"))\n\n result = String(\"\")\n for index, string_item in uenumerate(static_string_array):\n if index == 0:\n result = string_item.native\n else:\n result += \" \" + string_item.native\n\n assert result == \"Ping Pong\"\n\n self.hash_as_array(Bytes(b\"Testing 123\"))\n\n return True\n\n @subroutine\n def hash_as_array(self, commitment_args_concat: Bytes) -> HashResult:\n return HashResult.from_bytes(op.sha3_256(commitment_args_concat))\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc4_types\/array.py","language":"Python","license":"NOASSERTION","size":2595} {"code":"import typing as t\n\nfrom algopy import Bytes, Contract, Txn, subroutine\nfrom algopy.arc4 import (\n Bool as ARC4Bool,\n DynamicArray,\n StaticArray,\n)\n\n\nclass Arc4BoolTypeContract(Contract):\n def approval_program(self) -> bool:\n self.test_stuff(ARC4Bool(True), ARC4Bool(False))\n assert ARC4Bool(\n False if Txn.num_app_args else True # noqa: SIM211\n ).native, \"conditional expr\"\n\n static_boolean_array = StaticArray[ARC4Bool, t.Literal[12]](\n ARC4Bool(True),\n ARC4Bool(True),\n ARC4Bool(True),\n ARC4Bool(True),\n ARC4Bool(True),\n ARC4Bool(True),\n ARC4Bool(True),\n ARC4Bool(True),\n ARC4Bool(True),\n ARC4Bool(True),\n ARC4Bool(True),\n ARC4Bool(True),\n )\n\n assert static_boolean_array.bytes == Bytes.from_hex(\"FFF0\")\n\n assert static_boolean_array[0] == ARC4Bool(True), \"Single boolean can be unpacked\"\n assert static_boolean_array[-1] == ARC4Bool(True), \"Single boolean can be unpacked\"\n\n dynamic_boolean_array = DynamicArray[ARC4Bool](\n ARC4Bool(True), ARC4Bool(False), ARC4Bool(True)\n )\n\n assert dynamic_boolean_array.bytes == Bytes.from_hex(\"0003A0\")\n\n assert ARC4Bool(True) == True # noqa: E712\n assert ARC4Bool(False) != True # noqa: E712\n assert False == ARC4Bool(False) # noqa: E712, SIM300\n assert False != ARC4Bool(True) # noqa: E712, SIM300\n\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n @subroutine\n def test_stuff(self, true: ARC4Bool, false: ARC4Bool) -> bool:\n assert true.native\n\n assert not false.native\n\n assert true == ARC4Bool(true.native)\n assert false == ARC4Bool(false.native)\n\n return true.native\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc4_types\/bool.py","language":"Python","license":"NOASSERTION","size":1867} {"code":"import typing as t\n\nfrom algopy import Contract, arc4\nfrom algopy.op import Txn\n\n\nclass Arc4BoolEvalContract(Contract):\n def approval_program(self) -> bool:\n assert not arc4.Bool(False)\n assert arc4.Bool(True)\n\n assert not arc4.String(\"\")\n assert arc4.String(\".\")\n\n assert not arc4.Address()\n assert arc4.Address(Txn.sender)\n\n assert not arc4.UInt8(0)\n assert arc4.UInt8(1)\n\n assert not arc4.UInt16(0)\n assert arc4.UInt16(1)\n\n assert not arc4.UInt32(0)\n assert arc4.UInt32(1)\n\n assert not arc4.UInt64(0)\n assert arc4.UInt64(1)\n\n assert not arc4.UInt128(0)\n assert arc4.UInt128(1)\n\n assert not arc4.UInt256(0)\n assert arc4.UInt256(1)\n\n assert not arc4.UInt512(0)\n assert arc4.UInt512(1)\n\n assert not arc4.UIntN[t.Literal[24]](0)\n assert arc4.UIntN[t.Literal[24]](1)\n\n assert not arc4.BigUIntN[t.Literal[504]](0)\n assert arc4.BigUIntN[t.Literal[504]](1)\n\n assert not arc4.UFixedNxM[t.Literal[48], t.Literal[10]](\"0.0\")\n assert arc4.UFixedNxM[t.Literal[48], t.Literal[10]](\"1.0\")\n\n assert not arc4.BigUFixedNxM[t.Literal[496], t.Literal[10]](\"0.0\")\n assert arc4.BigUFixedNxM[t.Literal[496], t.Literal[10]](\"0.01\")\n\n dynamic_arr = arc4.DynamicArray[arc4.UInt64]()\n assert not dynamic_arr\n dynamic_arr.append(arc4.UInt64(0))\n assert dynamic_arr\n\n assert arc4.Bool() == arc4.Bool(False)\n\n return True\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc4_types\/bool_eval.py","language":"Python","license":"NOASSERTION","size":1600} {"code":"from algopy import Bytes, Contract, Txn, UInt64\nfrom algopy.arc4 import (\n Byte,\n DynamicBytes,\n UInt8,\n)\n\n\nclass Arc4DynamicBytesContract(Contract):\n def approval_program(self) -> bool:\n total = UInt64(0)\n dynamic_bytes = DynamicBytes(Byte(2), UInt8(3), 1)\n assert dynamic_bytes.native == b\"\\x02\\x03\\x01\"\n assert dynamic_bytes.bytes == b\"\\x00\\x03\\x02\\x03\\x01\"\n\n for uint8_item in dynamic_bytes:\n total += uint8_item.native\n\n assert total == 6, \"Total should be of dynamic_bytes items\"\n\n dynamic_bytes2 = DynamicBytes(b\"\\x03\\x04\")\n assert dynamic_bytes2.native == b\"\\x03\\x04\"\n assert dynamic_bytes2.bytes == b\"\\x00\\x02\\x03\\x04\"\n\n for uint8_item in dynamic_bytes2:\n total += uint8_item.native\n\n dynamic_bytes3 = DynamicBytes(dynamic_bytes2.native)\n assert dynamic_bytes3.native == b\"\\x03\\x04\"\n assert dynamic_bytes3.bytes == b\"\\x00\\x02\\x03\\x04\"\n\n for uint8_item in dynamic_bytes3:\n total += uint8_item.native\n\n assert total == 20, \"Total should now include sum of dynamic_bytes3 items\"\n\n dynamic_bytes3.extend(DynamicBytes(b\"abc\"))\n assert dynamic_bytes3.bytes == b\"\\x00\\x05\\x03\\x04abc\"\n assert dynamic_bytes3.native == b\"\\x03\\x04abc\"\n\n dynamic_bytes = DynamicBytes(2 if Txn.num_app_args else 3, UInt8(3), 1)\n assert dynamic_bytes.native == Bytes.from_hex(\"030301\")\n\n dynamic_bytes = DynamicBytes(b\"2\" if Txn.num_app_args else b\"3\")\n assert dynamic_bytes.native == b\"3\"\n return True\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc4_types\/dynamic_bytes.py","language":"Python","license":"NOASSERTION","size":1652} {"code":"from algopy import ARC4Contract, arc4\n\n\nclass Arc4DynamicStringArrayContract(ARC4Contract):\n @arc4.abimethod\n def xyz(self) -> arc4.DynamicArray[arc4.String]:\n return arc4.DynamicArray(\n arc4.String(\"X\"),\n arc4.String(\"Y\"),\n arc4.String(\"Z\"),\n )\n\n @arc4.abimethod\n def xyz_raw(self) -> arc4.DynamicArray[arc4.String]:\n raw = arc4.DynamicArray(\n arc4.DynamicArray(arc4.Byte(88)),\n arc4.DynamicArray(arc4.Byte(89)),\n arc4.DynamicArray(arc4.Byte(90)),\n )\n return arc4.DynamicArray[arc4.String].from_bytes(raw.bytes)\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc4_types\/dynamic_string_array.py","language":"Python","license":"NOASSERTION","size":626} {"code":"import typing\n\nfrom algopy import Contract, UInt64, subroutine\nfrom algopy.arc4 import (\n Bool,\n StaticArray,\n String,\n Struct,\n UInt8,\n)\n\n\nclass TestStruct(Struct):\n b_val: Bool\n u_val: UInt8\n s_val_1: String\n s_val_2: String\n\n\nTestArray: typing.TypeAlias = StaticArray[UInt8, typing.Literal[4]]\n\n\nclass StructWithArray(Struct):\n test_array: TestArray\n\n\nclass Arc4MutableParamsContract(Contract):\n def approval_program(self) -> bool:\n self.mutating_copies()\n\n return True\n\n @subroutine\n def mutating_copies(self) -> None:\n my_array = StaticArray(UInt8(1), UInt8(2), UInt8(3), UInt8(4))\n my_struct = TestStruct(\n b_val=Bool(True),\n u_val=UInt8(50),\n s_val_1=String(\"Happy\"),\n s_val_2=String(\"Days\"),\n )\n\n my_array_copy = my_array.copy()\n my_struct_copy = my_struct.copy()\n\n my_array[2] = UInt8(5)\n\n assert my_array_copy[2] == UInt8(3), \"my_array_copy should be unchanged\"\n assert my_array[2] == UInt8(5), \"my_array should be mutated\"\n\n # Pass to subroutine without a copy\n t, f = self.other_routine(my_array, my_struct)\n assert t\n assert not f\n\n assert my_array[1] == UInt8(5), \"my_array has been mutated by the subroutine\"\n\n assert my_struct.s_val_1 == String(\n \"AARRGH!\"\n ), \"my_struct has been mutated by the subroutine\"\n\n # Pass to subroutine with copy\n self.other_routine(my_array_copy.copy(), my_struct_copy.copy())\n\n assert my_array_copy[1] == UInt8(\n 2\n ), \"my_array_copy should not be mutated by the subroutine\"\n\n assert my_struct_copy.s_val_1 == String(\n \"Happy\"\n ), \"my_struct_copy should not be mutated by the subroutine\"\n\n my_array_copy_2 = my_array_copy.copy()\n\n my_array_copy_2 = self.other_routine_2(my_array_copy_2)\n\n assert my_array_copy_2[0] == UInt8(1), \"my_array_copy_2 should have original value\"\n\n self.other_routine_2(my_array_copy_2)\n assert my_array_copy_2[0] == UInt8(10), \"my_array_copy_2 should have mutated value\"\n\n my_array_copy_3 = my_array_copy.copy()\n\n originals = (my_array.copy(), my_array_copy_2.copy(), my_array_copy_3.copy())\n self.mutate_tuple_items_and_reassign(\n (my_array.copy(), my_array_copy_2.copy(), my_array_copy_3.copy()),\n start=UInt64(0),\n reassign=True,\n )\n assert originals == (my_array, my_array_copy_2, my_array_copy_3)\n\n self.mutate_tuple_items_and_reassign(\n (my_array, my_array_copy_2, my_array_copy_3), start=UInt64(100), reassign=True\n )\n\n assert my_array[0] == 100\n assert my_array_copy_2[0] == 101\n assert my_array_copy_3[0] == 102\n assert my_array[1] == 103\n assert my_array_copy_2[1] == 104\n assert my_array_copy_3[1] == 105\n\n self.mutate_tuple_items_and_reassign(\n (my_array, my_array_copy_2, my_array_copy_3), start=UInt64(200), reassign=False\n )\n\n assert my_array[0] == 200\n assert my_array_copy_2[0] == 201\n assert my_array_copy_3[0] == 202\n assert my_array[1] == 206\n assert my_array_copy_2[1] == 207\n assert my_array_copy_3[1] == 208\n\n # Nested array items should still require a copy\n nested = StructWithArray(test_array=my_array.copy())\n self.other_routine_2(nested.test_array.copy())\n\n @subroutine\n def other_routine(self, array: TestArray, struct: TestStruct) -> tuple[bool, bool]:\n array[1] = UInt8(5)\n struct.s_val_1 = String(\"AARRGH!\")\n return True, False\n\n @subroutine\n def other_routine_2(self, array: TestArray) -> TestArray:\n copy = array.copy()\n array[0] = UInt8(10)\n return copy\n\n @subroutine\n def mutate_tuple_items_and_reassign(\n self, arrays: tuple[TestArray, TestArray, TestArray], *, start: UInt64, reassign: bool\n ) -> None:\n arrays[0][0] = UInt8(start)\n arrays[1][0] = UInt8(start + 1)\n arrays[2][0] = UInt8(start + 2)\n\n assert arrays[0][0] == start\n assert arrays[1][0] == start + 1\n assert arrays[2][0] == start + 2\n\n arrays[0][1] = UInt8(start + 3)\n arrays[1][1] = UInt8(start + 4)\n arrays[2][1] = UInt8(start + 5)\n\n # overwrite params\n if reassign:\n arrays = (arrays[0].copy(), arrays[1].copy(), arrays[2].copy())\n\n arrays[0][1] = UInt8(start + 6)\n arrays[1][1] = UInt8(start + 7)\n arrays[2][1] = UInt8(start + 8)\n\n assert arrays[0][1] == start + 6\n assert arrays[1][1] == start + 7\n assert arrays[2][1] == start + 8\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc4_types\/mutable_params.py","language":"Python","license":"NOASSERTION","size":4810} {"code":"from algopy import arc4, subroutine\n\n\nclass MutableParams2(arc4.ARC4Contract):\n @arc4.abimethod()\n def test_array_rebinding(self) -> None:\n a = arc4.DynamicBytes(0)\n self.maybe_modify_array(a, assign_local=True)\n assert a == arc4.DynamicBytes(0, 1)\n\n a = arc4.DynamicBytes(1)\n self.maybe_modify_array(a, assign_local=False)\n assert a == arc4.DynamicBytes(1, 42, 4)\n\n @subroutine\n def maybe_modify_array(self, a: arc4.DynamicBytes, *, assign_local: bool) -> None: # v0\n if assign_local:\n a.append(arc4.Byte(1)) # v1: modify out\n a = arc4.DynamicBytes(1, 2, 3) # v2: BOUNDARY\n a.append(arc4.Byte(4)) # v3: local only\n a = arc4.DynamicBytes(1, 2, 4) # v4: local only\n else:\n a.append(arc4.Byte(42)) # v5: modify out\n\n a.append(arc4.Byte(4)) # v6: modify out IF not b ELSE local only\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc4_types\/mutable_params2.py","language":"Python","license":"NOASSERTION","size":917} {"code":"import typing\nimport typing as t\n\nfrom algopy import Bytes, Contract, subroutine\nfrom algopy.arc4 import (\n Bool,\n DynamicArray,\n StaticArray,\n String,\n Struct,\n UFixedNxM,\n UInt8,\n UInt16,\n)\n\nAliasedDynamicArray: t.TypeAlias = DynamicArray[UInt16]\nAliasedStaticArray: t.TypeAlias = StaticArray[UInt8, t.Literal[1]]\n\nDecimal: t.TypeAlias = UFixedNxM[t.Literal[64], t.Literal[10]]\n\n\nclass TestStruct(Struct):\n b_val: Bool\n u_val: UInt8\n s_val_1: String\n s_val_2: String\n\n\nclass StructWithArray(Struct):\n d_array: DynamicArray[String]\n\n\nclass Arc4MutationContract(Contract):\n def approval_program(self) -> bool:\n self.dynamic_array_fixed_size()\n self.dynamic_array_bool()\n self.dynamic_array_string()\n self.array_of_array_dynamic()\n self.array_of_array_static()\n self.index_assign()\n self.struct_assign()\n self.array_concat()\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n @subroutine\n def check_copy_required(self) -> None:\n d_array = DynamicArray(String(\"Test\"))\n\n nested_in_array = DynamicArray(d_array.copy())\n\n nested_in_struct = StructWithArray(d_array=nested_in_array[0].copy())\n\n assert d_array == nested_in_struct.d_array\n\n @subroutine\n def array_concat(self) -> None:\n uint8_array = DynamicArray(UInt8(1), UInt8(2))\n array_concat_tuple = uint8_array + (UInt8(3), UInt8(4)) # noqa: RUF005\n assert array_concat_tuple == DynamicArray(UInt8(1), UInt8(2), UInt8(3), UInt8(4))\n array_concat_tuple += (UInt8(5),)\n assert array_concat_tuple == DynamicArray(UInt8(1), UInt8(2), UInt8(3), UInt8(4), UInt8(5))\n\n hello_world = DynamicArray(String(\"Hello\"), String(\"World\"))\n hello_world_concat = DynamicArray(String(\"Hello\")) + DynamicArray(String(\"World\"))\n assert hello_world == hello_world_concat\n\n @subroutine\n def array_of_array_dynamic(self) -> None:\n array_of_array = DynamicArray[DynamicArray[UInt8]]()\n assert array_of_array.bytes == Bytes.from_hex(\"0000\")\n array_of_array.append(DynamicArray[UInt8](UInt8(10)))\n assert array_of_array.bytes == Bytes.from_hex(\"0001000200010A\")\n array_of_array.append(DynamicArray[UInt8](UInt8(16)))\n assert array_of_array.bytes == Bytes.from_hex(\"00020004000700010A000110\")\n array_of_array[0].append(UInt8(255))\n\n assert array_of_array.bytes == Bytes.from_hex(\"00020004000800020AFF000110\")\n\n array_of_array[0][1] = UInt8(0)\n assert array_of_array.bytes == Bytes.from_hex(\"00020004000800020A00000110\")\n\n @subroutine\n def array_of_array_static(self) -> None:\n array_of_array = StaticArray[StaticArray[UInt8, typing.Literal[2]], typing.Literal[2]](\n StaticArray[UInt8, typing.Literal[2]](UInt8(10), UInt8(9)),\n StaticArray[UInt8, typing.Literal[2]](UInt8(64), UInt8(128)),\n )\n\n assert array_of_array.bytes == Bytes.from_hex(\"0A094080\")\n\n array_of_array[0] = StaticArray[UInt8, typing.Literal[2]](UInt8(255), UInt8(254))\n assert array_of_array.bytes == Bytes.from_hex(\"FFFE4080\")\n\n array_of_array[1][0] = UInt8(1)\n assert array_of_array.bytes == Bytes.from_hex(\"FFFE0180\")\n\n @subroutine\n def index_assign(self) -> None:\n dynamic_uint8_array = DynamicArray[UInt8](UInt8(1), UInt8(2))\n dynamic_uint8_array[0] = UInt8(255)\n assert dynamic_uint8_array.bytes == Bytes.from_hex(\"0002ff02\")\n static_uint8_array = StaticArray(UInt8(1), UInt8(2))\n static_uint8_array[1] = UInt8(255)\n assert static_uint8_array.bytes == Bytes.from_hex(\"01ff\")\n\n dynamic_bool_array = DynamicArray(Bool(True), Bool(False))\n dynamic_bool_array[0] = Bool(False)\n assert dynamic_bool_array.bytes == Bytes.from_hex(\"000200\")\n static_bool_array = StaticArray[Bool, typing.Literal[2]](Bool(True), Bool(True))\n static_bool_array[1] = Bool(False)\n assert static_bool_array.bytes == Bytes.from_hex(\"80\")\n\n @subroutine\n def struct_assign(self) -> None:\n test_struct = TestStruct(\n b_val=Bool(True),\n u_val=UInt8(50),\n s_val_1=String(\"Happy\"),\n s_val_2=String(\"Days\"),\n )\n\n test_struct.b_val = Bool(False)\n test_struct.u_val = UInt8(12)\n assert test_struct == TestStruct(\n b_val=Bool(False),\n u_val=UInt8(12),\n s_val_1=String(\"Happy\"),\n s_val_2=String(\"Days\"),\n )\n test_struct.s_val_1 = String(\"Hmmmm\")\n test_struct.s_val_2 = String(\"Oh well\")\n\n assert test_struct == TestStruct(\n b_val=Bool(False),\n u_val=UInt8(12),\n s_val_1=String(\"Hmmmm\"),\n s_val_2=String(\"Oh well\"),\n )\n\n @subroutine\n def dynamic_array_fixed_size(self) -> None:\n dynamic_uint8_array = DynamicArray[UInt8](UInt8(1), UInt8(2))\n dynamic_uint8_array.append(UInt8(50))\n assert dynamic_uint8_array == DynamicArray[UInt8](UInt8(1), UInt8(2), UInt8(50))\n dynamic_uint8_array.extend(dynamic_uint8_array)\n\n assert dynamic_uint8_array == DynamicArray[UInt8](\n UInt8(1), UInt8(2), UInt8(50), UInt8(1), UInt8(2), UInt8(50)\n )\n dynamic_uint8_array.extend((UInt8(4), UInt8(90)))\n\n assert dynamic_uint8_array == DynamicArray(\n UInt8(1), UInt8(2), UInt8(50), UInt8(1), UInt8(2), UInt8(50), UInt8(4), UInt8(90)\n )\n\n popped = dynamic_uint8_array.pop()\n assert popped == UInt8(90)\n\n assert dynamic_uint8_array == DynamicArray(\n UInt8(1), UInt8(2), UInt8(50), UInt8(1), UInt8(2), UInt8(50), UInt8(4)\n )\n\n @subroutine\n def dynamic_array_bool(self) -> None:\n dynamic_bool_array = DynamicArray[Bool](Bool(True), Bool(False))\n assert dynamic_bool_array.bytes == Bytes.from_hex(\"000280\")\n dynamic_bool_array.extend((Bool(True), Bool(False)))\n assert dynamic_bool_array.bytes == Bytes.from_hex(\"0004A0\")\n assert dynamic_bool_array == DynamicArray[Bool](\n Bool(True), Bool(False), Bool(True), Bool(False)\n )\n dynamic_bool_array.extend(dynamic_bool_array)\n\n assert dynamic_bool_array == DynamicArray[Bool](\n Bool(True),\n Bool(False),\n Bool(True),\n Bool(False),\n Bool(True),\n Bool(False),\n Bool(True),\n Bool(False),\n )\n dynamic_bool_array.append(Bool(True))\n\n assert dynamic_bool_array == DynamicArray[Bool](\n Bool(True),\n Bool(False),\n Bool(True),\n Bool(False),\n Bool(True),\n Bool(False),\n Bool(True),\n Bool(False),\n Bool(True),\n )\n\n assert dynamic_bool_array.pop() == Bool(True)\n assert dynamic_bool_array.pop() == Bool(False)\n assert dynamic_bool_array == DynamicArray[Bool](\n Bool(True),\n Bool(False),\n Bool(True),\n Bool(False),\n Bool(True),\n Bool(False),\n Bool(True),\n )\n\n @subroutine\n def dynamic_array_string(self) -> None:\n hello = String(\"Hello\")\n world = String(\"World\")\n foo = String(\"Foo\")\n bar = String(\"Bar\")\n dynamic_string_array = DynamicArray(hello, world)\n assert dynamic_string_array.bytes == Bytes(\n b\"\\x00\\x02\\x00\\x04\\x00\\x0b\\x00\\x05Hello\\x00\\x05World\"\n )\n dynamic_string_array.extend((foo, bar))\n\n assert dynamic_string_array.bytes == Bytes(\n b\"\\x00\\x04\\x00\\x08\\x00\\x0f\\x00\\x16\\x00\\x1b\\x00\\x05Hello\\x00\\x05World\\x00\\x03Foo\\x00\\x03Bar\"\n )\n\n dynamic_string_array.extend(dynamic_string_array)\n\n assert dynamic_string_array == DynamicArray(hello, world, foo, bar, hello, world, foo, bar)\n dynamic_string_array = DynamicArray(hello, world, foo, bar, hello, world, foo, bar)\n dynamic_string_array[3] = hello\n dynamic_string_array[5] = hello\n\n assert dynamic_string_array == DynamicArray(\n hello, world, foo, hello, hello, hello, foo, bar\n )\n\n assert dynamic_string_array.pop() == bar\n assert dynamic_string_array.pop() == foo\n assert dynamic_string_array == DynamicArray(hello, world, foo, hello, hello, hello)\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc4_types\/mutation.py","language":"Python","license":"NOASSERTION","size":8450} {"code":"import typing\nimport typing as t\n\nfrom algopy import BigUInt, Bytes, Contract, OnCompleteAction, Txn, UInt64, op\nfrom algopy.arc4 import (\n BigUFixedNxM,\n BigUIntN,\n Byte,\n Tuple,\n UFixedNxM,\n UInt8,\n UInt16,\n UInt32,\n UInt64 as ARC4UInt64,\n UInt512,\n UIntN,\n)\n\nDecimal: t.TypeAlias = UFixedNxM[t.Literal[64], t.Literal[10]]\n\nARC4BigUInt: t.TypeAlias = BigUIntN[t.Literal[128]]\n\nARC4BiggieSmalls: t.TypeAlias = BigUIntN[t.Literal[32]]\n\n\nsixty_four_byte_num = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF # noqa: E501\n\n\nclass Arc4NumericTypesContract(Contract):\n def approval_program(self) -> bool:\n uint8 = UInt64(255)\n\n int8_encoded = UInt8(uint8)\n\n int8_decoded = int8_encoded.native\n\n assert uint8 == int8_decoded\n\n test_bytes = Bytes.from_hex(\"7FFFFFFFFFFFFFFF00\")\n assert UInt8.from_bytes(test_bytes[:1]).native == 2**8 - 1 - 2**7\n assert UIntN[typing.Literal[24]].from_bytes(test_bytes[:3]).native == 2**24 - 1 - 2**23\n assert UInt16.from_bytes(test_bytes[:2]).native == 2**16 - 1 - 2**15\n assert UInt32.from_bytes(test_bytes[:4]).native == 2**32 - 1 - 2**31\n assert ARC4UInt64.from_bytes(test_bytes[:8]).native == 2**64 - 1 - 2**63\n assert UInt8(1 if Txn.num_app_args else 2) == 2\n assert UInt512(1 if Txn.num_app_args else 2) == 2\n\n decimals = Decimal(\"145.6853943940\")\n\n assert decimals.bytes == op.itob(145_6853943940)\n\n decimals_from_truncated_str = Decimal(\"145.0\")\n\n assert decimals_from_truncated_str.bytes == op.itob(145_0000000000)\n\n thousand = Decimal(\"1e3\")\n\n assert thousand.bytes.length == 8\n assert thousand.bytes == op.itob(1000_0000000000)\n\n one_decimal = Decimal(\"1.0\")\n\n assert one_decimal.bytes == op.itob(1_0000000000)\n\n zero_decimal = Decimal(\"0.0\")\n\n assert zero_decimal.bytes == op.itob(0)\n\n small_decimal = Decimal(\"0.00000001\")\n\n assert small_decimal.bytes == op.itob(100)\n\n smaller_decimal = Decimal(\"1E-9\")\n\n assert smaller_decimal.bytes == op.itob(10)\n\n smallest_decimal = Decimal(\"0.0000000001\")\n\n assert smallest_decimal.bytes == op.itob(1)\n\n sixty_four_decimal = Decimal(\"1844674407.3709551615\")\n\n assert sixty_four_decimal.bytes == op.itob(1844674407_3709551615)\n\n really_big_int = BigUIntN[t.Literal[512]](sixty_four_byte_num)\n\n assert really_big_int == BigUIntN[t.Literal[512]].from_bytes(really_big_int.bytes)\n\n really_big_decimal = BigUFixedNxM[t.Literal[512], t.Literal[2]].from_bytes(\n BigUInt(sixty_four_byte_num).bytes\n )\n\n assert Decimal(\"1844674407.3709551615\" if Txn.num_app_args else \"0.0\") == Decimal()\n\n biguint = BigUInt(1)\n arc4_biguint_const = ARC4BigUInt(1)\n arc4_biguint_dynamic = ARC4BigUInt(biguint + 1)\n\n assert biguint == arc4_biguint_const.native\n\n assert arc4_biguint_dynamic.bytes.length == (128 \/\/ 8)\n\n assert really_big_decimal.bytes.length == 64\n\n # check UInt64 sub-types are converted properly\n tup = Tuple((ARC4UInt64(OnCompleteAction.ClearState),))\n assert tup[0].native == OnCompleteAction.ClearState\n\n assert ARC4BiggieSmalls(1).native == BigUInt(1)\n\n return True\n\n def clear_state_program(self) -> bool:\n assert BigUInt.from_bytes(Decimal().bytes) == 0\n assert BigUInt.from_bytes(BigUFixedNxM[t.Literal[512], t.Literal[5]]().bytes) == 0\n assert Byte() == 0\n assert ARC4UInt64() == 0\n assert UInt512() == 0\n\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc4_types\/numeric.py","language":"Python","license":"NOASSERTION","size":3703} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass Arc4DynamicStringArrayContract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def xyz(\n self,\n ) -> algopy.arc4.DynamicArray[algopy.arc4.String]: ...\n\n @algopy.arc4.abimethod\n def xyz_raw(\n self,\n ) -> algopy.arc4.DynamicArray[algopy.arc4.String]: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc4_types\/out\/client_Arc4DynamicStringArrayContract.py","language":"Python","license":"NOASSERTION","size":412} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass MutableParams2(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def test_array_rebinding(\n self,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc4_types\/out\/client_MutableParams2.py","language":"Python","license":"NOASSERTION","size":255} {"code":"from algopy import Contract, arc4, op\n\n\nclass Arc4RefTypesContract(Contract):\n def approval_program(self) -> bool:\n # When creating an address from an account no need to check the length as we assume the\n # Account is valid\n sender_address = arc4.Address(op.Txn.sender)\n assert sender_address == op.Txn.sender\n # When creating an address from bytes, we check the length is 32 as we don't know the\n # source of the bytes\n checked_address = arc4.Address(op.Txn.sender.bytes)\n # When using from_bytes, no validation is performed as per all implementations of\n # from_bytes\n unchecked_address = arc4.Address.from_bytes(op.Txn.sender.bytes)\n assert sender_address == checked_address and checked_address == unchecked_address\n\n assert arc4.Address() == \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ\"\n return True\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc4_types\/reference_types.py","language":"Python","license":"NOASSERTION","size":978} {"code":"from algopy import Contract, String, Txn, arc4\n\nHELLO_WORLD = b\"Hello World!\"\n\n\nclass Arc4StringTypesContract(Contract):\n def approval_program(self) -> bool:\n some_bytes_as_string = arc4.String(String.from_bytes(HELLO_WORLD))\n\n some_bytes_as_bytes_again = some_bytes_as_string.native.bytes\n\n assert (\n some_bytes_as_string.bytes != HELLO_WORLD\n ), \"Original bytes should not match encoded bytes\"\n\n assert (\n some_bytes_as_string.bytes[2:] == HELLO_WORLD\n ), \"Original bytes should match encoded if we strip the length header\"\n\n assert some_bytes_as_bytes_again == HELLO_WORLD\n\n hello = arc4.String(\"Hello\")\n space = arc4.String(\" \")\n world = arc4.String(\"World!\")\n\n assert arc4.String(\"Hello World!\") == (hello + space + world)\n\n thing = arc4.String(\"hi\")\n thing += thing\n assert thing == arc4.String(\"hihi\")\n\n value = arc4.String(\"a\") + arc4.String(\"b\") + \"cd\"\n value += \"e\"\n value += arc4.String(\"f\")\n value += arc4.String(\"g\")\n assert arc4.String(\"abcdefg\") == value\n\n assert arc4.String().native == \"\"\n assert arc4.String(\"hello\") == String(\"hello\")\n\n assert arc4.String(\"aye\" if Txn.num_app_args else \"bee\") == \"bee\"\n return True\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc4_types\/string.py","language":"Python","license":"NOASSERTION","size":1385} {"code":"import typing\n\nfrom algopy import Contract, arc4, log, op, subroutine\n\nDecimal: typing.TypeAlias = arc4.UFixedNxM[typing.Literal[64], typing.Literal[9]]\n\n\nclass Vector(arc4.Struct, kw_only=True):\n x: Decimal\n y: Decimal\n\n\nclass Flags(arc4.Struct):\n a: arc4.Bool\n b: arc4.Bool\n c: arc4.Bool\n d: arc4.Bool\n\n\nclass VectorFlags(arc4.Struct):\n vector: Vector\n flags: Flags\n\n\nclass FrozenButMutable(arc4.Struct, frozen=True):\n mutable: arc4.DynamicBytes\n\n\nclass FrozenAndImmutable(arc4.Struct, frozen=True):\n one: arc4.UInt64\n two: arc4.UInt64\n\n\nclass Arc4StructsTypeContract(Contract):\n def approval_program(self) -> bool:\n coord_1 = Vector(x=Decimal(\"35.382882839\"), y=Decimal(\"150.382884930\"))\n coord_2 = Vector(y=Decimal(\"150.382884930\"), x=Decimal(\"35.382882839\"))\n coord_3 = add(coord_1.copy(), coord_2.copy())\n for val in (coord_3.x, coord_3.y):\n log(val.bytes)\n\n flags = Flags(a=arc4.Bool(True), b=arc4.Bool(False), c=arc4.Bool(True), d=arc4.Bool(False))\n check(flags.copy())\n log(flags.bytes)\n assert Vector.from_bytes(coord_1.bytes).bytes == coord_1.bytes\n\n nested_decode(VectorFlags(coord_1.copy(), flags.copy()))\n\n mutable = FrozenButMutable(arc4.DynamicBytes())\n copy = mutable.copy()\n copy.mutable.append(arc4.Byte(42))\n assert mutable != copy, \"expected copy is different\"\n\n immutable = FrozenAndImmutable(arc4.UInt64(12), arc4.UInt64(34))\n no_copy = immutable\n assert no_copy == immutable\n\n immutable2 = immutable._replace(two=arc4.UInt64(123))\n assert immutable2.two == 123\n assert immutable2.one == immutable.one\n\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n\n@subroutine\ndef add(v1: Vector, v2: Vector) -> Vector:\n return Vector(\n x=add_decimal(v1.x, v2.x),\n y=add_decimal(v1.y, v2.y),\n )\n\n\n@subroutine\ndef check(flags: Flags) -> None:\n assert flags.a.native\n assert not flags.b.native\n assert flags.c.native\n assert not flags.d.native\n\n\n@subroutine\ndef nested_decode(vector_flags: VectorFlags) -> None:\n assert vector_flags.vector.x.bytes == op.itob(35382882839)\n assert vector_flags.flags.c.native\n\n\n@subroutine\ndef add_decimal(x: Decimal, y: Decimal) -> Decimal:\n return Decimal.from_bytes(op.itob(op.btoi(x.bytes) + op.btoi(y.bytes)))\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc4_types\/structs.py","language":"Python","license":"NOASSERTION","size":2413} {"code":"from algopy import Contract, arc4, log\n\nfrom test_cases.arc4_types.structs import Flags\n\n\nclass Arc4StructsFromAnotherModule(Contract):\n def approval_program(self) -> bool:\n flags = Flags(a=arc4.Bool(True), b=arc4.Bool(False), c=arc4.Bool(True), d=arc4.Bool(False))\n log(flags.bytes)\n\n return True\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc4_types\/structs2.py","language":"Python","license":"NOASSERTION","size":386} {"code":"import typing\n\nfrom algopy import Bytes, Contract, UInt64, subroutine\nfrom algopy.arc4 import Bool, Byte, DynamicBytes, String, Tuple, UInt8\n\nTestTuple: typing.TypeAlias = Tuple[UInt8, UInt8, String, String, UInt8]\n\nTestBooleanPacking: typing.TypeAlias = Tuple[\n UInt8, Bool, Bool, Bool, Bool, Bool, Bool, Bool, Bool, Bool, UInt8\n]\n\n\nclass Arc4TuplesTypeContract(Contract):\n def approval_program(self) -> bool:\n my_tuple = Tuple((UInt8(1), UInt8(2), String(\"hello\"), String(\"world\"), UInt8(255)))\n\n assert my_tuple == TestTuple.from_bytes( # type: ignore[comparison-overlap]\n Bytes.from_hex(\"01020007000EFF000568656C6C6F0005776F726C64\")\n )\n boolean_packing = Tuple(\n (\n UInt8(4),\n Bool(True),\n Bool(False),\n Bool(True),\n Bool(True),\n Bool(True),\n Bool(True),\n Bool(False),\n Bool(True),\n Bool(True),\n UInt8(16),\n )\n )\n assert boolean_packing.bytes == Bytes.from_hex(\"04BD8010\")\n a, b, c, d, e, f, g, h, i, j, k = boolean_packing.native\n assert boolean_packing[10] == k\n assert a.native == 4, \"a is 4\"\n assert b and d and e and f and g and i and j, \"b,d,e,f,g,i,j are true\"\n assert not (c or h), \"c and h are false\"\n assert k.native == 16, \"k is 16\"\n\n assert boolean_packing == TestBooleanPacking(boolean_packing.native)\n\n total, concat = self.test_stuff(my_tuple)\n assert concat.native == \"hello world\"\n assert total == 258\n\n self.test_copy()\n\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n @subroutine\n def test_stuff(self, test_tuple: TestTuple) -> tuple[UInt64, String]:\n a, b, c, d, e = test_tuple.native\n\n assert test_tuple[-0] == a\n assert test_tuple[-1] == e\n assert test_tuple[-2] == d\n\n total = a.native + b.native + e.native\n text = c.native + \" \" + d.native\n\n return total, String(text)\n\n @subroutine\n def test_copy(self) -> None:\n tup = Tuple((UInt8(), DynamicBytes()))\n tup[1].append(Byte())\n\n assert tup[1] == DynamicBytes(0)\n\n tup2 = tup.copy()\n tup[1][0] = Byte(1)\n\n assert tup[1] != tup2[1]\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc4_types\/tuples.py","language":"Python","license":"NOASSERTION","size":2373} {"code":"import typing\n\nfrom algopy import (\n ARC4Contract,\n Box,\n BoxMap,\n BoxRef,\n Bytes,\n GlobalState,\n LocalState,\n String,\n TemplateVar,\n UInt64,\n arc4,\n subroutine,\n)\n\n\nclass SharedStruct(arc4.Struct):\n \"\"\"This struct is shared\"\"\"\n\n foo: arc4.DynamicBytes\n bar: arc4.UInt8\n\n\nclass EventOnly(arc4.Struct):\n \"\"\"This struct is only used in an event\"\"\"\n\n x: arc4.UInt64\n y: arc4.UInt64\n\n\nclass TopLevelStruct(arc4.Struct):\n a: arc4.UInt64\n b: arc4.String\n shared: SharedStruct\n\n\nclass StateStruct(arc4.Struct):\n a: arc4.UInt64\n b: arc4.String\n\n\n@subroutine\ndef constant_method() -> UInt64:\n return UInt64(42)\n\n\n@subroutine\ndef echo_number(x: UInt64) -> UInt64:\n return x\n\n\nclass Contract(ARC4Contract):\n \"\"\"Contract docstring\"\"\"\n\n def __init__(self) -> None:\n self.g_struct = GlobalState(StateStruct)\n self.g_uint64 = GlobalState(UInt64, key=b\"gu\")\n self.g_address = GlobalState(arc4.Address, key=b\"ga\")\n\n self.l_struct = LocalState(StateStruct)\n self.l_uint64 = LocalState(UInt64, key=b\"lu\")\n self.l_address = LocalState(arc4.Address, key=b\"la\")\n\n self.b_struct = Box(StateStruct)\n self.b_uint64 = Box(UInt64, key=b\"bu\")\n self.b_address = Box(arc4.Address, key=b\"ba\")\n\n self.box_map_struct = BoxMap(StateStruct, SharedStruct)\n self.box_map_uint64 = BoxMap(UInt64, SharedStruct, key_prefix=b\"bmu\")\n self.box_map_address = BoxMap(arc4.Address, SharedStruct, key_prefix=b\"bma\")\n\n self.box_ref = BoxRef()\n self.box_ref2 = BoxRef(key=b\"br\")\n\n @arc4.baremethod(create=\"allow\", allow_actions=[\"NoOp\", \"OptIn\"])\n def bare_create(self) -> None:\n pass\n\n @arc4.abimethod(create=\"allow\", allow_actions=[\"NoOp\", \"OptIn\"])\n def create(self) -> None:\n \"\"\"Method docstring\"\"\"\n\n @arc4.baremethod(create=\"require\", allow_actions=[\"DeleteApplication\"])\n def transient(self) -> None:\n pass\n\n @arc4.abimethod()\n def struct_arg(self, arg: TopLevelStruct, shared: SharedStruct) -> UInt64:\n \"\"\"Method docstring2\"\"\"\n assert arg.shared == shared, \"this might error\"\n return UInt64(42)\n\n @arc4.abimethod(readonly=True)\n def struct_return(self, arg: TopLevelStruct) -> SharedStruct:\n assert arg.shared == echo(arg.shared), \"this won't error\"\n return arg.shared\n\n @arc4.abimethod(name=\"emits_error\", readonly=True)\n def errors(self, arg: TopLevelStruct) -> None:\n assert arg.a.bytes == arc4.UInt8(0).bytes, \"this will error\"\n\n @arc4.abimethod()\n def emitter(self) -> None:\n arc4.emit(SharedStruct(foo=arc4.DynamicBytes(b\"hello1\"), bar=arc4.UInt8(42)))\n\n arc4.emit(\n \"Anonymous\",\n String(\"hello\"),\n SharedStruct(foo=arc4.DynamicBytes(b\"hello2\"), bar=arc4.UInt8(42)),\n )\n\n @arc4.abimethod()\n def conditional_emit(self, should_emit: bool) -> None:\n if should_emit:\n arc4.emit(\n \"Anonymous2\",\n EventOnly(arc4.UInt64(42), arc4.UInt64(43)),\n SharedStruct(foo=arc4.DynamicBytes(b\"hello3\"), bar=arc4.UInt8(42)),\n )\n\n @arc4.abimethod()\n def template_value(self) -> tuple[SharedStruct, UInt64, String, arc4.UInt8]:\n return (\n TemplateVar[SharedStruct](\"STRUCT\"),\n TemplateVar[UInt64](\"AVM_UINT64\"),\n TemplateVar[String](\"AVM_STRING\"),\n TemplateVar[arc4.UInt8](\"ARC4_UINT8\"),\n )\n\n @arc4.abimethod(\n default_args={\n \"a\": arc4.UInt64(123),\n \"c\": Bytes(b\"123\"),\n \"b\": UInt64(234),\n \"d\": EventOnly(x=arc4.UInt64(1), y=arc4.UInt64(2)),\n \"e\": (UInt64(42), String(\"on the edge\")),\n \"f\": arc4.StaticArray(arc4.String(\"hi\"), arc4.String(\"there!\")),\n \"g\": arc4.DynamicArray(arc4.String(\"one\"), arc4.String(\"two\")),\n \"h\": constant_method(),\n \"i\": echo_number(UInt64(1234)),\n }\n )\n def with_constant_defaults(\n self,\n a: arc4.UInt64,\n b: UInt64,\n c: Bytes,\n d: EventOnly,\n e: tuple[UInt64, String],\n f: arc4.StaticArray[arc4.String, typing.Literal[2]],\n g: arc4.DynamicArray[arc4.String],\n h: UInt64,\n i: UInt64,\n ) -> None:\n assert a\n assert b\n assert c\n assert d.x or d.y\n assert e[0] or e[1]\n assert f[0] == \"hi\"\n assert g.length == 2\n assert h == 42\n assert i == 1234\n\n\n@subroutine\ndef echo(s: SharedStruct) -> SharedStruct:\n return s\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc_56\/contract.py","language":"Python","license":"NOASSERTION","size":4624} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\nclass SharedStruct(algopy.arc4.Struct):\n foo: algopy.arc4.DynamicBytes\n bar: algopy.arc4.UIntN[typing.Literal[8]]\n\nclass TopLevelStruct(algopy.arc4.Struct):\n a: algopy.arc4.UIntN[typing.Literal[64]]\n b: algopy.arc4.String\n shared: SharedStruct\n\nclass EventOnly(algopy.arc4.Struct):\n x: algopy.arc4.UIntN[typing.Literal[64]]\n y: algopy.arc4.UIntN[typing.Literal[64]]\n\nclass Contract(algopy.arc4.ARC4Client, typing.Protocol):\n \"\"\"\n Contract docstring\n \"\"\"\n @algopy.arc4.abimethod(allow_actions=['NoOp', 'OptIn'], create='allow')\n def create(\n self,\n ) -> None:\n \"\"\"\n Method docstring\n \"\"\"\n\n @algopy.arc4.abimethod\n def struct_arg(\n self,\n arg: TopLevelStruct,\n shared: SharedStruct,\n ) -> algopy.arc4.UIntN[typing.Literal[64]]:\n \"\"\"\n Method docstring2\n \"\"\"\n\n @algopy.arc4.abimethod(readonly=True)\n def struct_return(\n self,\n arg: TopLevelStruct,\n ) -> SharedStruct: ...\n\n @algopy.arc4.abimethod(readonly=True)\n def emits_error(\n self,\n arg: TopLevelStruct,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def emitter(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def conditional_emit(\n self,\n should_emit: algopy.arc4.Bool,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def template_value(\n self,\n ) -> algopy.arc4.Tuple[algopy.arc4.Tuple[algopy.arc4.DynamicBytes, algopy.arc4.UIntN[typing.Literal[8]]], algopy.arc4.UIntN[typing.Literal[64]], algopy.arc4.String, algopy.arc4.UIntN[typing.Literal[8]]]: ...\n\n @algopy.arc4.abimethod\n def with_constant_defaults(\n self,\n a: algopy.arc4.UIntN[typing.Literal[64]],\n b: algopy.arc4.UIntN[typing.Literal[64]],\n c: algopy.arc4.DynamicBytes,\n d: EventOnly,\n e: algopy.arc4.Tuple[algopy.arc4.UIntN[typing.Literal[64]], algopy.arc4.String],\n f: algopy.arc4.StaticArray[algopy.arc4.String, typing.Literal[2]],\n g: algopy.arc4.DynamicArray[algopy.arc4.String],\n h: algopy.arc4.UIntN[typing.Literal[64]],\n i: algopy.arc4.UIntN[typing.Literal[64]],\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/arc_56\/out\/client_Contract.py","language":"Python","license":"NOASSERTION","size":2291} {"code":"from algopy import (\n Asset,\n Contract,\n TransactionType,\n UInt64,\n subroutine,\n)\nfrom algopy.op import (\n Global,\n ITxnCreate,\n Txn,\n bzero,\n)\n\n\nclass Reference(Contract):\n def __init__(self) -> None:\n self.asa = Asset()\n\n def approval_program(self) -> bool:\n if Txn.num_app_args == 1:\n if Txn.application_args(0) == b\"opt_in\":\n asset = Txn.assets(0)\n self.opt_into_asset(asset)\n elif Txn.application_args(0) == b\"is_opted_in\":\n asset = Txn.assets(0)\n self.is_opted_asset(asset)\n else:\n assert False, \"Expected opt_in or is_opted_in\"\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n @subroutine\n def opt_into_asset(self, asset: Asset) -> None:\n # Only allow app creator to opt the app account into a ASA\n assert Txn.sender == Global.creator_address, \"Only creator can opt in to ASA\"\n # Verify a ASA hasn't already been opted into\n assert not self.asa, \"ASA already opted in\"\n # Save ASA ID in global state\n self.asa = asset\n\n # Submit opt-in transaction: 0 asset transfer to self\n ITxnCreate.begin()\n ITxnCreate.set_type_enum(TransactionType.AssetTransfer)\n ITxnCreate.set_fee(UInt64(0)) # cover fee with outer txn\n ITxnCreate.set_asset_receiver(Global.current_application_address)\n ITxnCreate.set_xfer_asset(asset)\n ITxnCreate.submit()\n\n @subroutine\n def is_opted_asset(self, asset: Asset) -> None:\n assert self.asa == asset, \"asset self.asa == asset\"\n assert asset.total == 10000000, \"total\"\n assert asset.decimals == 0, \"decimals\"\n assert not asset.default_frozen, \"default frozen\"\n assert asset.unit_name == b\"a\", \"unit_name\"\n assert asset.name == b\"asset a\", \"name\"\n assert asset.url == b\"\", \"URL\"\n assert asset.metadata_hash == bzero(32), \"hash\"\n assert asset.manager == Global.zero_address, \"manager\"\n assert asset.reserve == Global.zero_address, \"reserve\"\n assert asset.freeze == Global.zero_address, \"freeze\"\n assert asset.clawback == Global.zero_address, \"clawback\"\n assert asset.creator == Global.creator_address, \"creator\"\n assert Global.current_application_address.is_opted_in(asset), \"asset opted in\"\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/asset\/contract.py","language":"Python","license":"NOASSERTION","size":2410} {"code":"from algopy import (\n Account,\n BigUInt,\n Bytes,\n Contract,\n LocalState,\n OnCompleteAction,\n UInt64,\n op,\n subroutine,\n)\n\n\nclass Augmented(Contract):\n def __init__(self) -> None:\n self.my_uint = LocalState(UInt64)\n self.my_bytes = LocalState(Bytes)\n self.counter = UInt64()\n self.global_uint = UInt64(0)\n self.global_bytes = Bytes(b\"\")\n\n def approval_program(self) -> bool:\n me = op.Txn.sender\n\n if op.Txn.on_completion == OnCompleteAction.OptIn:\n self.my_uint[me] = UInt64(0)\n self.my_bytes[me] = Bytes(b\"\")\n if op.Txn.application_id:\n # variable augmented assignment\n n = op.Txn.num_app_args\n bytes_to_add = BigUInt(n).bytes\n\n # local augmented assignment\n self.my_uint[me] += n\n self.my_bytes[me] += bytes_to_add\n\n # global augmented assignment\n self.global_uint += n\n self.global_bytes += bytes_to_add\n\n self.counter = UInt64()\n assert self.counter == 0\n self.my_uint[self.get_sender_with_side_effect()] += 1\n assert self.counter == 1, \"this should not error\"\n self.my_uint[self.get_sender_with_side_effect()] -= 1\n assert self.counter == 2, \"this should not error\"\n\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n @subroutine\n def get_sender_with_side_effect(self) -> Account:\n self.counter += 1\n return op.Txn.sender\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/augmented_assignment\/contract.py","language":"Python","license":"NOASSERTION","size":1557} {"code":"from algopy import ARC4Contract, Txn, arc4, op\n\n\nclass Contract(ARC4Contract, avm_version=11):\n @arc4.abimethod\n def test_new_ops(self) -> None:\n # op functions\n assert op.online_stake()\n assert op.mimc(op.MiMCConfigurations.BN254Mp110, op.bzero(32))\n\n # AcctParamsGet, TODO: add to Account once 11 is in mainnet?\n a, b = op.AcctParamsGet.acct_incentive_eligible(Txn.sender)\n c, d = op.AcctParamsGet.acct_last_proposed(Txn.sender)\n e, f = op.AcctParamsGet.acct_last_heartbeat(Txn.sender)\n\n # Block\n assert not op.Block.blk_proposer(0), \"proposer\"\n assert op.Block.blk_fees_collected(0), \"fees collected\"\n assert op.Block.blk_bonus(0), \"bonus\"\n assert op.Block.blk_branch(0), \"branch\"\n assert op.Block.blk_fee_sink(0), \"fee sink\"\n assert op.Block.blk_protocol(0), \"protocol\"\n assert op.Block.blk_txn_counter(0), \"txn counter\"\n assert op.Block.blk_proposer_payout(0), \"proposer payout\"\n\n # Global\n assert op.Global.payouts_enabled, \"payouts_enabled\"\n assert op.Global.payouts_go_online_fee, \"payouts_go_online_fee\"\n assert op.Global.payouts_percent, \"payouts_percent\"\n assert op.Global.payouts_min_balance, \"payouts_min_balance\"\n assert op.Global.payouts_max_balance, \"payouts_max_balance\"\n\n # Voter params\n g, h = op.VoterParamsGet.voter_balance(0)\n i, j = op.VoterParamsGet.voter_incentive_eligible(0)\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/avm_11\/contract.py","language":"Python","license":"NOASSERTION","size":1483} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass Contract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def test_new_ops(\n self,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/avm_11\/out\/client_Contract.py","language":"Python","license":"NOASSERTION","size":241} {"code":"from algopy import ARC4Contract, UInt64, arc4, logicsig, op\n\n\n@logicsig(avm_version=12)\ndef avm_12_sig() -> UInt64:\n return op.sumhash512(b\"\").length\n\n\nclass Contract(ARC4Contract, avm_version=12):\n @arc4.abimethod\n def test_new_ops(self) -> None:\n # op functions\n assert not op.falcon_verify(b\"\", b\"\", op.bzero(1793))\n assert op.sumhash512(b\"\")\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/avm_12\/contract.py","language":"Python","license":"NOASSERTION","size":376} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass Contract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def test_new_ops(\n self,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/avm_12\/out\/client_Contract.py","language":"Python","license":"NOASSERTION","size":241} {"code":"from algopy import BigUInt, Bytes, String, UInt64, arc4\n\n\nclass TestContract(arc4.ARC4Contract):\n @arc4.abimethod(allow_actions=[\"NoOp\"], create=\"require\")\n def create(\n self,\n bool_param: bool,\n uint64_param: UInt64,\n bytes_param: Bytes,\n biguint_param: BigUInt,\n string_param: String,\n tuple_param: tuple[bool, UInt64, Bytes, BigUInt, String],\n ) -> tuple[bool, UInt64, Bytes, BigUInt, String]:\n result = (bool_param, uint64_param, bytes_param, biguint_param, string_param)\n assert result == tuple_param\n return result\n\n @arc4.abimethod\n def tuple_of_arc4(\n self, args: tuple[arc4.UInt8, arc4.Address]\n ) -> tuple[arc4.UInt8, arc4.Address]:\n assert args[0].bytes.length == 1\n assert args[1].bytes.length == 32\n return args\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/avm_types_in_abi\/contract.py","language":"Python","license":"NOASSERTION","size":841} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass TestContract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod(create='require')\n def create(\n self,\n bool_param: algopy.arc4.Bool,\n uint64_param: algopy.arc4.UIntN[typing.Literal[64]],\n bytes_param: algopy.arc4.DynamicBytes,\n biguint_param: algopy.arc4.BigUIntN[typing.Literal[512]],\n string_param: algopy.arc4.String,\n tuple_param: algopy.arc4.Tuple[algopy.arc4.Bool, algopy.arc4.UIntN[typing.Literal[64]], algopy.arc4.DynamicBytes, algopy.arc4.BigUIntN[typing.Literal[512]], algopy.arc4.String],\n ) -> algopy.arc4.Tuple[algopy.arc4.Bool, algopy.arc4.UIntN[typing.Literal[64]], algopy.arc4.DynamicBytes, algopy.arc4.BigUIntN[typing.Literal[512]], algopy.arc4.String]: ...\n\n @algopy.arc4.abimethod\n def tuple_of_arc4(\n self,\n args: algopy.arc4.Tuple[algopy.arc4.UIntN[typing.Literal[8]], algopy.arc4.Address],\n ) -> algopy.arc4.Tuple[algopy.arc4.UIntN[typing.Literal[8]], algopy.arc4.Address]: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/avm_types_in_abi\/out\/client_TestContract.py","language":"Python","license":"NOASSERTION","size":1104} {"code":"from algopy import BigUInt, Contract, op, subroutine\n\n\nclass BiguintBinaryOps(Contract):\n def approval_program(self) -> bool:\n left = BigUInt(58446744073709552000)\n right = BigUInt(18446744073709552000)\n # Math\n assert left + right == BigUInt(76893488147419104000)\n assert left - right == BigUInt(40000000000000000000)\n assert left * right == BigUInt(1078152129869320557630474056040704000000)\n assert left \/\/ right == BigUInt(3)\n assert left % right == BigUInt(3106511852580896000)\n # Boolean\n assert not (left < right)\n assert not (left <= right)\n assert left > right\n assert left >= right\n assert not (left == right) # noqa: SIM201\n assert left != right\n # Bitwise\n assert left | right == BigUInt(58446744073709552000)\n assert left & right == BigUInt(18446744073709552000)\n assert left ^ right == BigUInt(40000000000000000000)\n assert bitwise_ops(left) == bitwise_ops(left)\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n\n@subroutine\ndef bitwise_ops(value: BigUInt) -> BigUInt:\n low128 = BigUInt.from_bytes(op.bzero(16) + ~op.bzero(16))\n wide_value_compl = (value ^ low128) + BigUInt(1)\n\n return wide_value_compl & low128\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/biguint_binary_ops\/contract.py","language":"Python","license":"NOASSERTION","size":1315} {"code":"# ruff: noqa\nfrom algopy import *\n\n\nclass BooleanBinaryOps(Contract):\n def approval_program(self) -> bool:\n test_boolean_binary_ops(true=True, false=False)\n test_boolean_shortcircuit_binary_ops()\n type_coercion()\n test_union_boolean_binary_ops()\n test_literal_boolean_binary_ops()\n test_literal_conditionals(true=True, false=False)\n return True\n\n def clear_state_program(self) -> bool:\n assert bool() == False\n return True\n\n\n@subroutine\ndef test_boolean_binary_ops(*, true: bool, false: bool) -> None:\n assert not (true and false)\n assert not (false and true)\n assert true and true\n assert not (false and false)\n\n assert true or false\n assert false or true\n assert true or true\n assert not (false or false)\n\n\n@subroutine\ndef bool_to_bytes(x: bool) -> Bytes:\n return Bytes(b\"true\" if x else b\"false\")\n\n\n@subroutine\ndef test_boolean_shortcircuit_binary_ops() -> None:\n for lhs in (True, False):\n for rhs in (True, False):\n and_msg = b\"_\" + bool_to_bytes(lhs) + b\"_and_\" + bool_to_bytes(rhs)\n and_result = log_and_return(lhs, b\"lhs\" + and_msg) and log_and_return(\n rhs, b\"rhs\" + and_msg\n )\n assert and_result == (lhs and rhs)\n or_msg = b\"_\" + bool_to_bytes(lhs) + b\"_or_\" + bool_to_bytes(rhs)\n or_result = log_and_return(lhs, b\"lhs\" + or_msg) or log_and_return(\n rhs, b\"rhs\" + or_msg\n )\n assert or_result == (lhs or rhs)\n\n\n@subroutine\ndef log_and_return(x: bool, msg: Bytes) -> bool:\n log(msg)\n return x\n\n\n@subroutine\ndef type_coercion() -> None:\n b = UInt64(0) or OnCompleteAction.OptIn\n assert b > 0\n c = TransactionType.ApplicationCall or UInt64(0) or OnCompleteAction.OptIn\n assert c == TransactionType.ApplicationCall\n\n\n@subroutine\ndef test_union_boolean_binary_ops() -> None:\n ok = bool(Bytes() or UInt64(1))\n assert ok\n\n x = UInt64(0)\n y = Bytes(b\"y\")\n z = String(\"z\")\n assert (x or y) or (y or z)\n assert (x or y) and (x or y)\n assert x or (y or z)\n assert (x or y) or z\n\n assert (String(\"left\") and String(\"right\")).startswith(\"ri\")\n assert String(\"right\").startswith(String(\"le\") and String(\"ri\"))\n\n bytes_to_iterate = Bytes(b\"abc\")\n for idx, b in uenumerate(Bytes(b\"never seen\") and bytes_to_iterate):\n assert b == bytes_to_iterate[idx]\n assert (Bytes(b\"left\") and Bytes(b\"right\"))[1] == b\"i\"\n assert (Bytes(b\"left\") or Bytes(b\"right\"))[0:2] == b\"le\"\n assert \"ight\" in (String(\"left\") and String(\"right\"))\n\n assert (UInt64(1) and UInt64(2)) + 3 == 5\n assert ~(UInt64(1) or UInt64(2)) == ~UInt64(1)\n\n\n@subroutine\ndef test_literal_boolean_binary_ops() -> None:\n assert 0 or 1\n assert \"abc\" and 1\n assert UInt64(0) or 1\n assert False or Bytes(b\"abc\")\n\n a = bool(0 or 1)\n b = bool(\"abc\" and 1)\n c = bool(UInt64(0) or 1)\n d = bool(False or Bytes(b\"abc\"))\n assert a and b and c and d\n\n if 0 and 1:\n assert False\n if \"abc\" and 0:\n assert False\n if UInt64(0) or 0:\n assert False\n if False or Bytes(b\"\"):\n assert False\n\n assert UInt64(1 and 2) == 2\n\n one = UInt64(1)\n assert op.bitlen(one and 4) == 3\n empty_bytes = Bytes()\n assert op.bitlen(empty_bytes or b\"hello\") > 0\n\n\n@subroutine\ndef test_literal_conditionals(*, true: bool, false: bool) -> None:\n assert (3 if false else 0) or 4\n assert 0 or (3 if true else 0)\n assert b\"123\" or (3 if true else 0)\n assert (3 if false else 0) or b\"123\"\n y = UInt64((3 if false else 0) or 4)\n assert y == 4\n z = UInt64(0 or (3 if true else 0))\n assert z == 3\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/boolean_binary_ops\/contract.py","language":"Python","license":"NOASSERTION","size":3705} {"code":"from algopy import Contract, UInt64, subroutine, urange\n\n\n@subroutine(inline=False)\ndef get_bool() -> bool:\n return True\n\n\nclass MyContract(Contract):\n def approval_program(self) -> UInt64:\n val = UInt64(0)\n for _idx in urange(2):\n if get_bool():\n pass\n elif get_bool(): # noqa: SIM102\n if not get_bool():\n val += UInt64(123)\n return val\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/bug_load_store_load_store\/contract.py","language":"Python","license":"NOASSERTION","size":501} {"code":"from algopy import Bytes, Contract, subroutine\n\n\nclass BiguintBinaryOps(Contract):\n def approval_program(self) -> bool:\n do_some_ops(\n left=Bytes.from_hex(\"FF\"),\n right=Bytes.from_hex(\"0F\"),\n concat=Bytes.from_hex(\"FF0F\"),\n bitwise_or=Bytes.from_hex(\"FF\"),\n bitwise_xor=Bytes.from_hex(\"F0\"),\n bitwise_and=Bytes.from_hex(\"0F\"),\n )\n do_augmented_assignment_ops(Bytes.from_hex(\"FF\"))\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n\n@subroutine\ndef do_some_ops(\n *,\n left: Bytes,\n right: Bytes,\n concat: Bytes,\n bitwise_or: Bytes,\n bitwise_xor: Bytes,\n bitwise_and: Bytes,\n) -> None:\n result = left + right\n assert result == concat\n result = left | right\n assert result == bitwise_or\n result = left ^ right\n assert result == bitwise_xor\n result = left & right\n assert result == bitwise_and\n\n\n@subroutine\ndef do_augmented_assignment_ops(seed: Bytes) -> None:\n seed &= Bytes.from_hex(\"00\")\n\n assert seed == Bytes.from_hex(\"00\")\n\n five = Bytes.from_hex(\"05\")\n\n seed |= five\n\n assert seed == five\n\n sixteen = Bytes.from_hex(\"10\")\n\n seed ^= sixteen\n\n assert seed == Bytes.from_hex(\"15\")\n\n seed ^= five\n\n assert seed == sixteen\n\n seed += five\n\n assert seed == Bytes.from_hex(\"1005\")\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/bytes_ops\/contract.py","language":"Python","license":"NOASSERTION","size":1382} {"code":"from algopy import Contract, UInt64, log, subroutine\n\n\nclass MyContract(Contract):\n def approval_program(self) -> UInt64:\n log(42)\n self.echo(UInt64(1), UInt64(2))\n return UInt64(1)\n\n @subroutine\n def echo(self, a: UInt64, b: UInt64) -> None:\n log(a)\n log(b)\n\n def clear_state_program(self) -> UInt64:\n return UInt64(1)\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/callsub\/contract.py","language":"Python","license":"NOASSERTION","size":374} {"code":"import abc\n\nfrom algopy import Bytes, Contract, log, subroutine\n\nWAVE = \"\ud83d\udc4b\".encode()\n\n\nclass BaseContract(Contract, abc.ABC):\n def __init__(self) -> None:\n self.state1 = self.state2 = join_log_and_return(\n right=Bytes(WAVE),\n left=Bytes(b\"Hello, world!\"),\n )\n\n\nclass ChainedAssignment(BaseContract):\n def __init__(self) -> None:\n super().__init__()\n\n def approval_program(self) -> bool:\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n\n@subroutine\ndef join_log_and_return(*, left: Bytes, right: Bytes) -> Bytes:\n result = left + b\" \" + right\n log(result)\n return result\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/chained_assignment\/contract.py","language":"Python","license":"NOASSERTION","size":671} {"code":"","repo_name":"algorandfoundation\/puya","path":"test_cases\/compile\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"from algopy import (\n Account,\n ARC4Contract,\n BigUInt,\n Bytes,\n String,\n TemplateVar,\n UInt64,\n arc4,\n logicsig,\n subroutine,\n)\n\n\n@logicsig\ndef always_approve_sig() -> bool:\n return True\n\n\nclass HelloBase(ARC4Contract):\n def __init__(self) -> None:\n self.greeting = String()\n\n @arc4.abimethod(allow_actions=[\"DeleteApplication\"])\n def delete(self) -> None:\n pass\n\n @arc4.baremethod(allow_actions=[\"UpdateApplication\"])\n def update(self) -> None:\n pass\n\n @arc4.abimethod()\n def greet(self, name: String) -> String:\n return self.greeting + \" \" + name\n\n\nclass LargeProgram(ARC4Contract):\n @arc4.abimethod()\n def get_big_bytes_length(self) -> UInt64:\n return get_big_bytes().length\n\n @arc4.abimethod(allow_actions=[\"DeleteApplication\"])\n def delete(self) -> None:\n pass\n\n\n@subroutine\ndef get_big_bytes() -> Bytes:\n return Bytes.from_hex(\"00\" * 4096)\n\n\nclass Hello(HelloBase):\n @arc4.abimethod(create=\"require\")\n def create(self, greeting: String) -> None:\n self.greeting = greeting\n\n\nclass HelloTmpl(HelloBase):\n def __init__(self) -> None:\n self.greeting = TemplateVar[String](\"GREETING\")\n\n @arc4.abimethod(create=\"require\")\n def create(self) -> None:\n pass\n\n\nclass HelloPrfx(HelloBase):\n def __init__(self) -> None:\n self.greeting = TemplateVar[String](\"GREETING\", prefix=\"PRFX_\")\n\n @arc4.abimethod(create=\"require\")\n def create(self) -> None:\n pass\n\n\nclass HelloOtherConstants(ARC4Contract):\n def __init__(self) -> None:\n self.greeting = TemplateVar[String](\"GREETING\")\n self.num = TemplateVar[BigUInt](\"NUM\")\n self.address = TemplateVar[Account](\"ACCOUNT\")\n self.method = TemplateVar[Bytes](\"METHOD\")\n\n @arc4.abimethod(create=\"require\")\n def create(self) -> UInt64:\n return UInt64(1)\n\n @arc4.abimethod(allow_actions=[\"DeleteApplication\"])\n def delete(self) -> None:\n pass\n\n @arc4.abimethod()\n def greet(self, name: String) -> Bytes:\n num_alpha = (self.num + 48).bytes[-1]\n return (\n self.greeting.bytes + b\" \" + name.bytes + num_alpha + self.address.bytes + self.method\n )\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/compile\/apps.py","language":"Python","license":"NOASSERTION","size":2239} {"code":"from algopy import (\n Account,\n ARC4Contract,\n BigUInt,\n Global,\n OnCompleteAction,\n String,\n UInt64,\n arc4,\n compile_contract,\n compile_logicsig,\n itxn,\n)\n\nfrom test_cases.compile.apps import (\n Hello,\n HelloOtherConstants,\n HelloPrfx,\n HelloTmpl,\n LargeProgram,\n always_approve_sig,\n)\n\n\nclass HelloFactory(ARC4Contract):\n @arc4.abimethod()\n def test_logicsig(self) -> arc4.Address:\n return arc4.Address(compile_logicsig(always_approve_sig).account)\n\n @arc4.abimethod()\n def test_compile_contract(self) -> None:\n # create app\n compiled = compile_contract(Hello)\n hello_app = (\n itxn.ApplicationCall(\n app_args=(arc4.arc4_signature(\"create(string)void\"), arc4.String(\"hello\")),\n approval_program=compiled.approval_program,\n clear_state_program=compiled.clear_state_program,\n global_num_bytes=1,\n )\n .submit()\n .created_app\n )\n\n # call the new app\n txn = itxn.ApplicationCall(\n app_args=(arc4.arc4_signature(\"greet(string)string\"), arc4.String(\"world\")),\n app_id=hello_app,\n ).submit()\n result = arc4.String.from_log(txn.last_log)\n\n # delete the app\n itxn.ApplicationCall(\n app_id=hello_app,\n app_args=(arc4.arc4_signature(\"delete()void\"),),\n on_completion=OnCompleteAction.DeleteApplication,\n ).submit()\n\n assert result == \"hello world\"\n\n @arc4.abimethod()\n def test_compile_contract_tmpl(self) -> None:\n # create app\n greeting = String(\"hey\")\n compiled = compile_contract(HelloTmpl, template_vars={\"GREETING\": greeting})\n hello_app = (\n itxn.ApplicationCall(\n app_args=(arc4.arc4_signature(\"create()void\"),),\n approval_program=compiled.approval_program,\n clear_state_program=compiled.clear_state_program,\n global_num_uint=compiled.global_uints,\n global_num_bytes=compiled.global_bytes,\n local_num_uint=compiled.local_uints,\n local_num_bytes=compiled.local_bytes,\n )\n .submit()\n .created_app\n )\n\n # call the new app\n txn = itxn.ApplicationCall(\n app_args=(arc4.arc4_signature(\"greet(string)string\"), arc4.String(\"world\")),\n app_id=hello_app,\n ).submit()\n result = arc4.String.from_log(txn.last_log)\n\n # delete the app\n itxn.ApplicationCall(\n app_id=hello_app,\n app_args=(arc4.arc4_signature(\"delete()void\"),),\n on_completion=OnCompleteAction.DeleteApplication,\n ).submit()\n\n assert result == \"hey world\"\n\n @arc4.abimethod()\n def test_compile_contract_prfx(self) -> None:\n # create app\n compiled = compile_contract(\n HelloPrfx, template_vars={\"GREETING\": String(\"hi\")}, template_vars_prefix=\"PRFX_\"\n )\n hello_app = (\n itxn.ApplicationCall(\n app_args=(arc4.arc4_signature(\"create()void\"),),\n approval_program=compiled.approval_program,\n clear_state_program=compiled.clear_state_program,\n global_num_bytes=compiled.global_bytes,\n )\n .submit()\n .created_app\n )\n\n # call the new app\n txn = itxn.ApplicationCall(\n app_args=(arc4.arc4_signature(\"greet(string)string\"), arc4.String(\"world\")),\n app_id=hello_app,\n ).submit()\n result = arc4.String.from_log(txn.last_log)\n\n # delete the app\n itxn.ApplicationCall(\n app_id=hello_app,\n app_args=(arc4.arc4_signature(\"delete()void\"),),\n on_completion=OnCompleteAction.DeleteApplication,\n ).submit()\n\n assert result == \"hi world\"\n\n @arc4.abimethod()\n def test_compile_contract_large(self) -> None:\n # create app\n compiled = compile_contract(LargeProgram)\n hello_app = (\n itxn.ApplicationCall(\n approval_program=compiled.approval_program,\n clear_state_program=compiled.clear_state_program,\n extra_program_pages=compiled.extra_program_pages,\n global_num_bytes=compiled.global_bytes,\n )\n .submit()\n .created_app\n )\n\n # call the new app\n txn = itxn.ApplicationCall(\n app_args=(arc4.arc4_signature(\"get_big_bytes_length()uint64\"),),\n app_id=hello_app,\n ).submit()\n result = arc4.UInt64.from_log(txn.last_log)\n\n # delete the app\n itxn.ApplicationCall(\n app_id=hello_app,\n app_args=(arc4.arc4_signature(\"delete()void\"),),\n on_completion=OnCompleteAction.DeleteApplication,\n ).submit()\n\n assert result == 4096\n\n @arc4.abimethod()\n def test_arc4_create(self) -> None:\n # create app\n hello_app = arc4.arc4_create(Hello.create, \"hello\").created_app\n\n # call the new app\n result, _txn = arc4.abi_call(Hello.greet, \"world\", app_id=hello_app)\n\n # delete the app\n arc4.abi_call(\n Hello.delete,\n app_id=hello_app,\n # on_complete is inferred from Hello.delete ARC4 definition\n )\n\n assert result == \"hello world\"\n\n @arc4.abimethod()\n def test_arc4_create_tmpl(self) -> None:\n # create app\n compiled = compile_contract(HelloTmpl, template_vars={\"GREETING\": String(\"tmpl2\")})\n hello_app = arc4.arc4_create(\n HelloTmpl.create,\n compiled=compiled,\n ).created_app\n\n # call the new app\n result, _txn = arc4.abi_call(HelloTmpl.greet, \"world\", app_id=hello_app)\n\n # delete the app\n arc4.abi_call(\n HelloTmpl.delete,\n app_id=hello_app,\n # on_complete is inferred from Hello.delete ARC4 definition\n )\n\n assert result == \"tmpl2 world\"\n\n @arc4.abimethod()\n def test_arc4_create_prfx(self) -> None:\n # create app\n compiled = compile_contract(\n HelloPrfx, template_vars_prefix=\"PRFX_\", template_vars={\"GREETING\": String(\"prfx2\")}\n )\n hello_app = arc4.arc4_create(\n HelloPrfx.create,\n compiled=compiled,\n ).created_app\n\n # call the new app\n result, _txn = arc4.abi_call(HelloPrfx.greet, \"world\", app_id=hello_app)\n\n # delete the app\n arc4.abi_call(\n HelloPrfx.delete,\n app_id=hello_app,\n # on_complete is inferred from Hello.delete ARC4 definition\n )\n\n assert result == \"prfx2 world\"\n\n @arc4.abimethod()\n def test_arc4_create_large(self) -> None:\n # create app\n app = arc4.arc4_create(LargeProgram).created_app\n\n # call the new app\n result, _txn = arc4.abi_call(LargeProgram.get_big_bytes_length, app_id=app)\n assert result == 4096\n\n # delete the app\n arc4.abi_call(\n LargeProgram.delete,\n app_id=app,\n )\n\n @arc4.abimethod()\n def test_arc4_create_modified_compiled(self) -> None:\n compiled = compile_contract(Hello)\n compiled = compiled._replace(\n local_uints=UInt64(3),\n global_uints=UInt64(4),\n local_bytes=UInt64(5),\n global_bytes=UInt64(6),\n )\n app = arc4.arc4_create(\n Hello.create,\n String(\"hey\"),\n compiled=compiled,\n ).created_app\n\n assert app.local_num_uint == 3\n assert app.global_num_uint == 4\n assert app.local_num_bytes == 5\n assert app.global_num_bytes == 6\n\n result, _txn = arc4.abi_call(Hello.greet, \"there\", app_id=app)\n\n assert result == \"hey there\"\n\n # delete the app\n arc4.abi_call(Hello.delete, app_id=app)\n\n @arc4.abimethod()\n def test_arc4_update(self) -> None:\n # create app\n app = arc4.arc4_create(\n HelloTmpl,\n compiled=compile_contract(\n HelloTmpl,\n template_vars={\"GREETING\": String(\"hi\")},\n extra_program_pages=1,\n global_uints=2,\n global_bytes=2,\n local_bytes=2,\n local_uints=2,\n ),\n ).created_app\n\n # call the new app\n result, _txn = arc4.abi_call(HelloTmpl.greet, \"there\", app_id=app)\n assert result == \"hi there\"\n\n # update the app\n arc4.arc4_update(Hello, app_id=app)\n\n # call the updated app\n result, _txn = arc4.abi_call(Hello.greet, \"there\", app_id=app)\n assert result == \"hi there\"\n\n # delete the app\n arc4.abi_call(\n Hello.delete,\n app_id=app,\n # on_complete is inferred from Hello.delete ARC4 definition\n )\n\n @arc4.abimethod()\n def test_other_constants(self) -> None:\n app = arc4.arc4_create(\n HelloOtherConstants,\n compiled=compile_contract(\n HelloOtherConstants,\n template_vars={\n \"NUM\": BigUInt(5),\n \"GREETING\": String(\"hello\"),\n \"ACCOUNT\": Account(\n \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ\"\n ),\n \"METHOD\": arc4.arc4_signature(\"something()void\"),\n },\n ),\n ).created_app\n\n result, _txn = arc4.abi_call(HelloOtherConstants.greet, \"Johnny\", app_id=app)\n\n assert result == (\n b\"hello Johnny5\" + Global.zero_address.bytes + arc4.arc4_signature(\"something()void\")\n )\n\n # delete the app\n arc4.abi_call(HelloOtherConstants.delete, app_id=app)\n\n @arc4.abimethod()\n def test_abi_call_create_params(self) -> None:\n compiled = compile_contract(Hello)\n app = arc4.abi_call(\n Hello.create,\n String(\"hey\"),\n approval_program=compiled.approval_program,\n clear_state_program=compiled.clear_state_program,\n global_num_uint=compiled.global_uints,\n global_num_bytes=compiled.global_bytes,\n local_num_uint=compiled.local_uints,\n local_num_bytes=compiled.local_bytes,\n extra_program_pages=compiled.extra_program_pages,\n ).created_app\n\n result, _txn = arc4.abi_call(Hello.greet, \"there\", app_id=app)\n\n assert result == \"hey there\"\n\n # delete the app\n arc4.abi_call(Hello.delete, app_id=app)\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/compile\/factory.py","language":"Python","license":"NOASSERTION","size":10687} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass Hello(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod(create='require')\n def create(\n self,\n greeting: algopy.arc4.String,\n ) -> None: ...\n\n @algopy.arc4.abimethod(allow_actions=['DeleteApplication'])\n def delete(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def greet(\n self,\n name: algopy.arc4.String,\n ) -> algopy.arc4.String: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/compile\/out\/client_Hello.py","language":"Python","license":"NOASSERTION","size":526} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass HelloBase(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod(allow_actions=['DeleteApplication'])\n def delete(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def greet(\n self,\n name: algopy.arc4.String,\n ) -> algopy.arc4.String: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/compile\/out\/client_HelloBase.py","language":"Python","license":"NOASSERTION","size":397} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass HelloFactory(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def test_logicsig(\n self,\n ) -> algopy.arc4.Address: ...\n\n @algopy.arc4.abimethod\n def test_compile_contract(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_compile_contract_tmpl(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_compile_contract_prfx(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_compile_contract_large(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_arc4_create(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_arc4_create_tmpl(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_arc4_create_prfx(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_arc4_create_large(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_arc4_create_modified_compiled(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_arc4_update(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_other_constants(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_abi_call_create_params(\n self,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/compile\/out\/client_HelloFactory.py","language":"Python","license":"NOASSERTION","size":1390} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass HelloOtherConstants(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod(create='require')\n def create(\n self,\n ) -> algopy.arc4.UIntN[typing.Literal[64]]: ...\n\n @algopy.arc4.abimethod(allow_actions=['DeleteApplication'])\n def delete(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def greet(\n self,\n name: algopy.arc4.String,\n ) -> algopy.arc4.DynamicBytes: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/compile\/out\/client_HelloOtherConstants.py","language":"Python","license":"NOASSERTION","size":541} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass HelloPrfx(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod(create='require')\n def create(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod(allow_actions=['DeleteApplication'])\n def delete(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def greet(\n self,\n name: algopy.arc4.String,\n ) -> algopy.arc4.String: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/compile\/out\/client_HelloPrfx.py","language":"Python","license":"NOASSERTION","size":492} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass HelloTmpl(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod(create='require')\n def create(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod(allow_actions=['DeleteApplication'])\n def delete(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def greet(\n self,\n name: algopy.arc4.String,\n ) -> algopy.arc4.String: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/compile\/out\/client_HelloTmpl.py","language":"Python","license":"NOASSERTION","size":492} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass LargeProgram(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def get_big_bytes_length(\n self,\n ) -> algopy.arc4.UIntN[typing.Literal[64]]: ...\n\n @algopy.arc4.abimethod(allow_actions=['DeleteApplication'])\n def delete(\n self,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/compile\/out\/client_LargeProgram.py","language":"Python","license":"NOASSERTION","size":400} {"code":"from algopy import Contract, subroutine\n\n\nclass ConditionalExecutionContract(Contract):\n def __init__(self) -> None:\n self.did_execute_a = False\n self.did_execute_b = False\n\n def approval_program(self) -> bool:\n # 'or' won't execute rhs if lhs is True\n self.func_a(True) or self.func_b(True)\n self.assert_and_reset(\n self.did_execute_a and not self.did_execute_b,\n )\n\n # 'or' executes rhs if lhs is False\n self.func_a(False) or self.func_b(True)\n self.assert_and_reset(\n self.did_execute_a and self.did_execute_b,\n )\n\n # 'and' won't execute rhs if lhs is False\n self.func_a(False) and self.func_b(True)\n self.assert_and_reset(\n self.did_execute_a and not self.did_execute_b,\n )\n\n # 'and' executes rhs if lhs is True\n self.func_a(True) and self.func_b(True)\n self.assert_and_reset(\n self.did_execute_a and self.did_execute_b,\n )\n\n # Tuples are fully evaluated before indexing is done\n (self.func_a(True), self.func_b(True))[0]\n self.assert_and_reset(\n self.did_execute_a and self.did_execute_b,\n )\n\n # Ternary condition won't execute if condition is True\n self.func_a(True) if self.func_c(True) else self.func_b(True)\n self.assert_and_reset(\n self.did_execute_a and not self.did_execute_b,\n )\n\n # Ternary condition won't execute if condition is False\n self.func_a(True) if self.func_c(False) else self.func_b(True)\n self.assert_and_reset(\n not self.did_execute_a and self.did_execute_b,\n )\n\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n @subroutine\n def assert_and_reset(self, condition: bool) -> None:\n assert condition\n self.did_execute_b = False\n self.did_execute_a = False\n\n @subroutine\n def func_a(self, ret_val: bool) -> bool:\n self.did_execute_a = True\n return ret_val\n\n @subroutine\n def func_b(self, ret_val: bool) -> bool:\n self.did_execute_b = True\n return ret_val\n\n @subroutine\n def func_c(self, ret_val: bool) -> bool:\n return ret_val\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/conditional_execution\/contract.py","language":"Python","license":"NOASSERTION","size":2284} {"code":"","repo_name":"algorandfoundation\/puya","path":"test_cases\/conditional_expressions\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"from algopy import Contract, UInt64, log, op, subroutine\n\n\nclass MyContract(Contract):\n \"\"\"My contract\"\"\"\n\n def approval_program(self) -> UInt64:\n a = UInt64(1)\n b = UInt64(2)\n\n c = a or b\n d = b and a\n\n e = self.expensive_op(UInt64(0)) or self.side_effecting_op(UInt64(1))\n f = self.expensive_op(UInt64(3)) or self.side_effecting_op(UInt64(42))\n\n g = self.side_effecting_op(UInt64(0)) and self.expensive_op(UInt64(42))\n h = self.side_effecting_op(UInt64(2)) and self.expensive_op(UInt64(3))\n\n i = a if b < c else d + e\n\n result = a * b * c * d * f * h - e - g + i\n\n log(op.itob(result))\n\n return result\n\n def clear_state_program(self) -> UInt64:\n return UInt64(0)\n\n @subroutine\n def expensive_op(self, val: UInt64) -> UInt64:\n assert val != 42, \"Can't be 42\"\n log(\"expensive_op\")\n return val\n\n @subroutine\n def side_effecting_op(self, val: UInt64) -> UInt64:\n assert val != 42, \"Can't be 42\"\n log(\"side_effecting_op\")\n return val\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/conditional_expressions\/contract.py","language":"Python","license":"NOASSERTION","size":1085} {"code":"from algopy import Contract, UInt64, subroutine\n\n\nclass Literals(Contract):\n def approval_program(self) -> bool:\n self.with_variable_condition(condition=False)\n self.with_variable_condition(condition=True)\n\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n @subroutine\n def with_variable_condition(self, *, condition: bool) -> None:\n x = UInt64(1 if condition else 0)\n assert bool(x) == condition\n assert x == -(-1 if condition else 0) # test unary op propagation\n y = x + ((1 if condition else 2) - 1) # test binary op with non-literal & literal\n y2 = ((1 if condition else 2) - 1) + x # test binary op with literal & non-literal\n assert y == 1\n assert y2 == 1\n maybe = (1 if condition else 0) < y # test comparison with non-literal\n assert maybe == (not condition)\n assert (1 if condition else 0) != 2 # test comparison with literal\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/conditional_expressions\/literals.py","language":"Python","license":"NOASSERTION","size":969} {"code":"from algopy import Account, Contract, log, op\n\n\nclass AddressConstantContract(Contract):\n def approval_program(self) -> bool:\n some_address = Account()\n assert not some_address\n some_address = Account(SOME_ADDRESS)\n assert some_address\n some_address = Account.from_bytes(some_address.bytes)\n some_address = Account(some_address.bytes)\n\n sender = op.Txn.sender\n sender_bytes = sender.bytes\n log(sender_bytes)\n is_some_address = op.Txn.sender == some_address\n\n return not is_some_address\n\n def clear_state_program(self) -> bool:\n return True\n\n\nSOME_ADDRESS = \"VCMJKWOY5P5P7SKMZFFOCEROPJCZOTIJMNIYNUCKH7LRO45JMJP6UYBIJA\"\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/constants\/address_constant.py","language":"Python","license":"NOASSERTION","size":708} {"code":"from algopy import Bytes, Contract, UInt64, log, op\n\n\nclass ByteConstantsContract(Contract):\n def approval_program(self) -> UInt64:\n base_64 = Bytes.from_base64(\"QmFzZSA2NCBlbmNvZGVk\")\n base_32 = Bytes.from_base32(\"IJQXGZJAGMZCAZLOMNXWIZLE\")\n base_16 = Bytes.from_hex(\"4261736520313620656E636F646564\")\n utf8 = Bytes(b\"UTF-8 Encoded\")\n\n result = base_16 + b\"|\" + base_64 + b\"|\" + base_32 + b\"|\" + utf8\n log(result)\n log(op.itob(result.length))\n return UInt64(1)\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/constants\/byte_constants.py","language":"Python","license":"NOASSERTION","size":584} {"code":"# vim:fileencoding=iso-8859-7\n\nOMEGA = \"\u03a9\".encode(\"iso-8859-7\")\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/constants\/non_utf8.py","language":"Python","license":"NOASSERTION","size":64} {"code":"","repo_name":"algorandfoundation\/puya","path":"test_cases\/contains\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"from algopy import Application, BigUInt, Bytes, Contract, String, UInt64, arc4, subroutine\n\n\nclass MyContract(Contract):\n \"\"\"My contract\"\"\"\n\n def approval_program(self) -> UInt64:\n not_ten = UInt64(15)\n\n one_true = self.is_in_tuple_1(UInt64(10), (UInt64(10), not_ten, Bytes(b\"five\")))\n one_false = self.is_in_tuple_1(UInt64(5), (UInt64(10), not_ten, Bytes(b\"five\")))\n assert one_true, \"Should be true\"\n assert not one_false, \"Should be false\"\n\n two_true = self.is_in_tuple_2(\n Bytes(b\"hello\"), (Bytes(b\"hello\"), UInt64(0), Bytes(b\"bonjour\"))\n )\n two_false = self.is_in_tuple_2(\n Bytes(b\"ciao\"), (Bytes(b\"hello\"), UInt64(0), Bytes(b\"bonjour\"))\n )\n assert two_true, \"Should be true\"\n assert not two_false, \"Should be false\"\n\n three_true = self.is_in_tuple_3(\n BigUInt(32323423423423), (BigUInt(32323423423423), BigUInt(8439439483934))\n )\n three_false = self.is_in_tuple_3(\n BigUInt(32323423423423) + BigUInt(32323423423423),\n (BigUInt(32323423423423), BigUInt(8439439483934)),\n )\n assert three_true, \"Should be true\"\n assert not three_false, \"Should be false\"\n\n self.test_string_types()\n self.test_numeric_types()\n\n return UInt64(1)\n\n def clear_state_program(self) -> UInt64:\n return UInt64(1)\n\n @subroutine\n def is_in_tuple_1(self, x: UInt64, y: tuple[UInt64, UInt64, Bytes]) -> bool:\n return x in y\n\n @subroutine\n def is_in_tuple_2(self, x: Bytes, y: tuple[Bytes, UInt64, Bytes]) -> bool:\n return x in y\n\n @subroutine\n def is_in_tuple_3(self, x: BigUInt, y: tuple[BigUInt, BigUInt]) -> bool:\n return x in y\n\n @subroutine\n def test_string_types(self) -> None:\n assert foo_string() in (foo_string(), baz_string()), \"foo in (foo, baz)\"\n assert foo_string() not in (bar_string(), baz_string()), \"foo not in (bar, baz)\"\n assert foo_string() in (foo_arc4(), baz_string(), bar_string()), \"foo in (foo, baz, bar)\"\n assert foo_arc4() in (foo_string(), baz_string(), bar_string()), \"foo in (foo, baz, bar)\"\n assert foo_string() not in (bar_arc4(), baz_string()), \"foo not in (bar, baz)\"\n assert foo_arc4() not in (bar_arc4(), baz_string()), \"foo not in (bar, baz)\"\n assert foo_string() in (\n bar_arc4(),\n baz_string(),\n foo_string(),\n one_u64(),\n ), \"foo in (bar, baz, foo, 1)\"\n assert foo_arc4() in (\n bar_arc4(),\n baz_string(),\n foo_string(),\n one_u64(),\n ), \"foo in (bar, baz, foo, 1)\"\n assert foo_string() not in (\n bar_arc4(),\n baz_string(),\n one_u64(),\n ), \"foo not in (bar, baz, 1)\"\n assert foo_arc4() not in (bar_arc4(), baz_string(), one_u64()), \"foo not in (bar, baz, 1)\"\n assert Bytes(b\"foo\") not in (\n foo_string(),\n foo_arc4(),\n Bytes(b\"bar\"),\n ), \"b'foo' not in (foo, foo, b'bar')\"\n\n @subroutine\n def test_numeric_types(self) -> None:\n assert one_u64() in (one_u64(), two_u64()), \"1 in (1, 2)\"\n assert one_u64() not in (UInt64(3), two_u64()), \"1 not in (3, 2)\"\n\n assert one_u64() in (one_u64(), UInt64(3), two_u8()), \"1 in (1, 3, 2)\"\n assert one_u64() in (one_arc4u64(), UInt64(4), two_u8()), \"1 in (1, 4, 2)\"\n assert UInt64(2) in (one_arc4u64(), UInt64(3), two_u8()), \"2 in (1, 3, 2)\"\n assert two_u8() in (one_arc4u64(), UInt64(3), two_u8()), \"2 in (1, 3, 2)\"\n assert two_u8() in (one_arc4u64(), UInt64(2), UInt64(3)), \"2 in (1, 2, 3)\"\n assert three_u512() in (UInt64(3), UInt64(4)), \"3 in (3, 4)\"\n assert four_biguint() in (UInt64(5), UInt64(4)), \"4 in (5, 4)\"\n\n assert one_u64() not in (UInt64(5), two_u8()), \"1 not in (5, 2)\"\n assert one_u64() not in (Application(1), UInt64(3), two_u8()), \"1 not in (app(1), 3, 2)\"\n assert one_u64() not in (UInt64(3), two_u8()), \"1 not in (3, 2)\"\n assert UInt64(2) not in (one_arc4u64(), UInt64(3)), \"2 not in (1, 3)\"\n assert two_u8() not in (one_arc4u64(), UInt64(3)), \"2 not in (1, 3)\"\n assert two_u8() not in (one_arc4u64(), UInt64(3)), \"2 not in (1, 3)\"\n assert three_u512() not in (UInt64(5), UInt64(7)), \"3 not in (5, 7)\"\n assert four_biguint() not in (UInt64(2), UInt64(9)), \"4 not in (2, 9)\"\n\n assert one_u64() in (\n foo_string(),\n one_u64(),\n UInt64(3),\n two_u8(),\n ), \"1 in (foo, 1, 3, 2)\"\n assert one_u64() in (one_arc4u64(), bar_string(), two_u8()), \"1 in (1, bar, 2)\"\n assert UInt64(2) in (foo_arc4(), UInt64(3), two_u8()), \"2 in (foo, 3, 2)\"\n assert two_u8() in (bar_arc4(), UInt64(3), two_u8()), \"2 in (bar, 3, 2)\"\n assert two_u8() in (foo_string(), UInt64(2), UInt64(3)), \"2 in foo(2, 3)\"\n assert three_u512() in (UInt64(5), UInt64(3), foo_string()), \"3 in (5, 3, foo)\"\n\n assert one_u64() not in (\n foo_string(),\n UInt64(3),\n two_u8(),\n ), \"1 not in (foo, 3, 2)\"\n assert one_u64() not in (bar_string(), two_u8()), \"1 not in (bar, 2)\"\n assert UInt64(2) not in (foo_arc4(), UInt64(3)), \"2 not in (foo, 3)\"\n assert two_u8() not in (bar_arc4(), UInt64(3)), \"2 not in (bar, 3)\"\n assert two_u8() not in (foo_string(), UInt64(3)), \"2 not in (foo, 3)\"\n assert three_u512() not in (UInt64(5), foo_string()), \"3 not in (5, foo)\"\n assert arc4.UInt8(65) not in (\n Bytes(b\"A\"),\n UInt64(64),\n UInt64(66),\n ), \"65 not in (b'A', 64, 66)\"\n\n\n@subroutine\ndef one_u64() -> UInt64:\n return UInt64(1)\n\n\n@subroutine\ndef one_arc4u64() -> arc4.UInt64:\n return arc4.UInt64(1)\n\n\n@subroutine\ndef two_u64() -> UInt64:\n return UInt64(2)\n\n\n@subroutine\ndef two_u8() -> arc4.UInt8:\n return arc4.UInt8(2)\n\n\n@subroutine\ndef three_u512() -> arc4.UInt512:\n return arc4.UInt512(3)\n\n\n@subroutine\ndef four_biguint() -> BigUInt:\n return BigUInt(4)\n\n\n@subroutine\ndef foo_string() -> String:\n return String(\"foo\")\n\n\n@subroutine\ndef foo_arc4() -> arc4.String:\n return arc4.String(\"foo\")\n\n\n@subroutine\ndef bar_string() -> String:\n return String(\"bar\")\n\n\n@subroutine\ndef bar_arc4() -> arc4.String:\n return arc4.String(\"bar\")\n\n\n@subroutine\ndef baz_string() -> String:\n return String(\"baz\")\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/contains\/contract.py","language":"Python","license":"NOASSERTION","size":6497} {"code":"from algopy import Contract, UInt64, log, op\n\n\nclass MyContract(Contract):\n def approval_program(self) -> bool:\n do_log = False\n match op.Txn.num_app_args:\n case UInt64(1):\n do_log = True\n case UInt64(3):\n do_log = True\n if do_log:\n log(op.itob(op.Txn.num_app_args))\n return True\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/control_op_simplification\/contract.py","language":"Python","license":"NOASSERTION","size":438} {"code":"from algopy import Bytes, TemplateVar, UInt64, arc4, log, subroutine\n\n\nclass DebugContract(arc4.ARC4Contract):\n @arc4.abimethod\n def test(self, x: UInt64, y: UInt64, z: UInt64) -> UInt64:\n a = x * TemplateVar[UInt64](\"A_MULT\")\n b = x + y\n c = b * z\n if b < c:\n a = a + y\n elif a < c:\n a = a + z\n elif b < a:\n a = a * 3\n elif b > a:\n b = b + a\n\n if a + b < c:\n a *= some_func(a, y)\n else:\n b *= some_func(b, z)\n\n bee = itoa(b)\n c = a + b\n cea = itoa(c)\n\n if a < c:\n a += c\n if a < b:\n a += b\n if a < b + c:\n a = a * z\n\n aye = itoa(a)\n log(aye, bee, cea, sep=\" \")\n\n return a\n\n\n@subroutine\ndef some_func(a: UInt64, b: UInt64) -> UInt64:\n a += b\n b *= a\n a += b\n a *= 2\n x = a + b\n y = a * b\n return x if x < y else y\n\n\n@subroutine\ndef itoa(i: UInt64) -> Bytes:\n digits = Bytes(b\"0123456789\")\n radix = digits.length\n if i < radix:\n return digits[i]\n return itoa(i \/\/ radix) + digits[i % radix]\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/debug\/contract.py","language":"Python","license":"NOASSERTION","size":1161} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass DebugContract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def test(\n self,\n x: algopy.arc4.UIntN[typing.Literal[64]],\n y: algopy.arc4.UIntN[typing.Literal[64]],\n z: algopy.arc4.UIntN[typing.Literal[64]],\n ) -> algopy.arc4.UIntN[typing.Literal[64]]: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/debug\/out\/client_DebugContract.py","language":"Python","license":"NOASSERTION","size":421} {"code":"","repo_name":"algorandfoundation\/puya","path":"test_cases\/diamond_mro\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"from algopy import arc4, log\n\nfrom test_cases.diamond_mro.gp import GP\n\n\nclass Base1(GP):\n def __init__(self) -> None:\n log(\"base1.__init__\")\n super().__init__()\n\n @arc4.abimethod\n def method(self) -> None:\n log(\"base1.method\")\n super().method()\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/diamond_mro\/base1.py","language":"Python","license":"NOASSERTION","size":283} {"code":"from algopy import arc4, log\n\nfrom test_cases.diamond_mro.gp import GP\n\n\nclass Base2(GP):\n def __init__(self) -> None:\n log(\"base2.__init__\")\n super().__init__()\n\n @arc4.abimethod\n def method(self) -> None:\n log(\"base2.method\")\n super().method()\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/diamond_mro\/base2.py","language":"Python","license":"NOASSERTION","size":283} {"code":"from algopy import arc4, log\n\nfrom test_cases.diamond_mro.base1 import Base1\nfrom test_cases.diamond_mro.base2 import Base2\n\n\nclass Derived(Base1, Base2):\n def __init__(self) -> None:\n log(\"derived.__init__\")\n super().__init__()\n\n @arc4.abimethod\n def method(self) -> None:\n log(\"derived.method\")\n super().method()\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/diamond_mro\/derived.py","language":"Python","license":"NOASSERTION","size":352} {"code":"import abc\n\nfrom algopy import ARC4Contract, arc4, log\n\n\nclass GP(ARC4Contract, abc.ABC):\n def __init__(self) -> None:\n log(\"gp.__init__\")\n super().__init__()\n\n @arc4.abimethod(create=\"require\")\n def create(self) -> None:\n pass\n\n @arc4.abimethod\n def method(self) -> None:\n log(\"gp.method\")\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/diamond_mro\/gp.py","language":"Python","license":"NOASSERTION","size":334} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass Base1(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def method(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod(create='require')\n def create(\n self,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/diamond_mro\/out\/client_Base1.py","language":"Python","license":"NOASSERTION","size":327} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass Base2(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def method(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod(create='require')\n def create(\n self,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/diamond_mro\/out\/client_Base2.py","language":"Python","license":"NOASSERTION","size":327} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass Derived(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def method(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod(create='require')\n def create(\n self,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/diamond_mro\/out\/client_Derived.py","language":"Python","license":"NOASSERTION","size":329} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass GP(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod(create='require')\n def create(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def method(\n self,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/diamond_mro\/out\/client_GP.py","language":"Python","license":"NOASSERTION","size":324} {"code":"from algopy import Contract, Txn\n\n\nclass MyContract(Contract):\n def approval_program(self) -> bool:\n a = Txn.application_args(0)\n b = Txn.application_args(1)\n\n assert a + b\n return (b + a).length > 0\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/dup2_optimization_bug\/crash.py","language":"Python","license":"NOASSERTION","size":295} {"code":"from algopy import Contract, UInt64, log, op\n\n\nclass VerifyContract(Contract):\n def approval_program(self) -> bool:\n assert op.Txn.num_app_args == 3\n result = op.ed25519verify_bare(\n op.Txn.application_args(0),\n op.Txn.application_args(1),\n op.Txn.application_args(2),\n )\n log(op.itob(UInt64(1) if result else UInt64(0)))\n return True\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/edverify\/contract.py","language":"Python","license":"NOASSERTION","size":470} {"code":"from algopy import Bytes, Contract, UInt64, subroutine, uenumerate, urange\n\n\nclass EnumerationContract(Contract):\n def approval_program(self) -> bool:\n iteration_count, item_sum, index_sum = enumerate_urange(UInt64(10), UInt64(21), UInt64(5))\n\n assert iteration_count == 6\n assert item_sum == 90\n assert index_sum == 3\n\n iteration_count, item_concat, index_sum = enumerate_tuple(\n (Bytes(b\"How\"), Bytes(b\"Now\"), Bytes(b\"Brown\"), Bytes(b\"Cow\"))\n )\n\n assert iteration_count == 8\n assert item_concat == Bytes(b\"HowNowBrownCowHowNowBrownCow\")\n assert index_sum == 6\n\n iteration_count, item_concat, index_sum = enumerate_bytes(Bytes(b\"abcdefg\"))\n\n assert iteration_count == 14\n assert item_concat == Bytes(b\"abcdefgabcdefg\")\n assert index_sum == 21\n\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n\n@subroutine\ndef enumerate_urange(start: UInt64, stop: UInt64, step: UInt64) -> tuple[UInt64, UInt64, UInt64]:\n iteration_count = UInt64(0)\n item_sum = UInt64(0)\n index_sum = UInt64(0)\n\n for item in urange(start, stop, step):\n iteration_count += 1\n item_sum += item\n\n for index, item in uenumerate(urange(start, stop, step)):\n iteration_count += 1\n item_sum += item\n index_sum += index\n\n return iteration_count, item_sum, index_sum\n\n\n@subroutine\ndef enumerate_tuple(tup: tuple[Bytes, Bytes, Bytes, Bytes]) -> tuple[UInt64, Bytes, UInt64]:\n iteration_count = UInt64(0)\n item_concat = Bytes(b\"\")\n index_sum = UInt64(0)\n\n for item in tup:\n iteration_count += 1\n item_concat += item\n for index, item in uenumerate(tup):\n iteration_count += 1\n item_concat += item\n index_sum += index\n\n return iteration_count, item_concat, index_sum\n\n\n@subroutine\ndef enumerate_bytes(bytes_: Bytes) -> tuple[UInt64, Bytes, UInt64]:\n iteration_count = UInt64(0)\n item_concat = Bytes(b\"\")\n index_sum = UInt64(0)\n\n for item in bytes_:\n iteration_count += 1\n item_concat += item\n for index, item in uenumerate(bytes_):\n iteration_count += 1\n item_concat += item\n index_sum += index\n\n return iteration_count, item_concat, index_sum\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/enumeration\/contract.py","language":"Python","license":"NOASSERTION","size":2299} {"code":"","repo_name":"algorandfoundation\/puya","path":"test_cases\/everything\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"import typing as t\n\n__all__ = [\n \"BANNED\",\n]\n__all__ += [\n \"EXT_ZERO\",\n \"EXT_ONE\",\n]\n\nBANNED = HACKER = \"VCMJKWOY5P5P7SKMZFFOCEROPJCZOTIJMNIYNUCKH7LRO45JMJP6UYBIJA\"\nEXT_ZERO: t.Final = 0\nEXT_ONE = 1\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/everything\/constants.py","language":"Python","license":"NOASSERTION","size":208} {"code":"from algopy import (\n Account,\n ARC4Contract,\n LocalState,\n OnCompleteAction,\n UInt64,\n op,\n subroutine,\n)\nfrom algopy.arc4 import (\n String,\n UInt64 as arc4_UInt64,\n abimethod,\n)\n\nfrom test_cases.everything.constants import BANNED, EXT_ONE\nfrom test_cases.everything.my_base import MyMiddleBase, multiplicative_identity\n\nZERO = ZER0 = 0 # lol\nONE = ZERO + (ZER0 * 2) + (2 - 1) \/\/ EXT_ONE\n\n\n@subroutine\ndef get_banned() -> Account:\n addr = Account(BANNED)\n return addr\n\n\n@subroutine\ndef add_one(x: UInt64) -> UInt64:\n new_value = x\n one = UInt64(ONE)\n new_value += one\n return new_value\n\n\nclass Everything(ARC4Contract, MyMiddleBase, name=\"MyContract\"):\n def __init__(self) -> None:\n self.name = LocalState(String)\n\n @abimethod(create=\"require\")\n def create(self) -> None:\n self._check_ban_list()\n self.remember_creator()\n self.counter = UInt64(ZERO)\n\n @abimethod(allow_actions=[\"NoOp\", \"OptIn\"])\n def register(self, name: String) -> None:\n self._check_ban_list()\n if op.Txn.on_completion == OnCompleteAction.OptIn:\n sender_name, sender_name_existed = self.name.maybe(account=0)\n if not sender_name_existed:\n self.counter += multiplicative_identity() # has full FuncDef\n self.name[0] = name\n\n @abimethod\n def say_hello(self) -> String:\n self._check_ban_list()\n name, exists = self.name.maybe(account=0)\n if not exists:\n return String(\"Howdy stranger!\")\n return \"Hello, \" + name + \"!\"\n\n @abimethod\n def calculate(self, a: arc4_UInt64, b: arc4_UInt64) -> arc4_UInt64:\n c = super().calculate(a, b)\n return arc4_UInt64(c.native * b.native)\n\n @abimethod(allow_actions=[\"CloseOut\"])\n def close_out(self) -> None:\n self._remove_sender()\n\n def clear_state_program(self) -> bool:\n self._remove_sender()\n return True\n\n @subroutine\n def _check_ban_list(self) -> None:\n assert op.Txn.sender != get_banned(), \"You are banned, goodbye\"\n\n @subroutine\n def _remove_sender(self) -> None:\n self.counter -= positive_one()\n\n\n@subroutine\ndef positive_one() -> UInt64:\n return UInt64(1)\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/everything\/contract.py","language":"Python","license":"NOASSERTION","size":2240} {"code":"from abc import ABC\n\nfrom algopy import Contract, UInt64, arc4, op, subroutine\n\n\nclass MyBase(Contract, ABC):\n @subroutine\n def remember_creator(self) -> None:\n self.creator = op.Txn.sender\n\n\nclass MyMiddleBase(MyBase, ABC):\n @subroutine\n def calculate(self, a: arc4.UInt64, b: arc4.UInt64) -> arc4.UInt64:\n return arc4.UInt64(a.native + b.native)\n\n\n@subroutine\ndef multiplicative_identity() -> UInt64:\n return UInt64(1)\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/everything\/my_base.py","language":"Python","license":"NOASSERTION","size":450} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass MyContract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod(create='require')\n def create(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod(allow_actions=['NoOp', 'OptIn'])\n def register(\n self,\n name: algopy.arc4.String,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def say_hello(\n self,\n ) -> algopy.arc4.String: ...\n\n @algopy.arc4.abimethod\n def calculate(\n self,\n a: algopy.arc4.UIntN[typing.Literal[64]],\n b: algopy.arc4.UIntN[typing.Literal[64]],\n ) -> algopy.arc4.UIntN[typing.Literal[64]]: ...\n\n @algopy.arc4.abimethod(allow_actions=['CloseOut'])\n def close_out(\n self,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/everything\/out\/client_MyContract.py","language":"Python","license":"NOASSERTION","size":816} {"code":"","repo_name":"algorandfoundation\/puya","path":"test_cases\/group_side_effects\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"from algopy import ARC4Contract, Global, UInt64, arc4, gtxn, op\n\n\nclass AppExpectingEffects(ARC4Contract):\n @arc4.abimethod\n def create_group(\n self,\n asset_create: gtxn.AssetConfigTransaction,\n app_create: gtxn.ApplicationCallTransaction,\n ) -> tuple[UInt64, UInt64]:\n assert asset_create.created_asset.id, \"expected asset created\"\n assert (\n op.gaid(asset_create.group_index) == asset_create.created_asset.id\n ), \"expected correct asset id\"\n assert app_create.created_app.id, \"expected app created\"\n assert (\n op.gaid(app_create.group_index) == app_create.created_app.id\n ), \"expected correct app id\"\n\n return asset_create.created_asset.id, app_create.created_app.id\n\n @arc4.abimethod\n def log_group(self, app_call: gtxn.ApplicationCallTransaction) -> None:\n assert app_call.app_args(0) == arc4.arc4_signature(\n \"some_value()uint64\"\n ), \"expected correct method called\"\n assert app_call.num_logs == 1, \"expected logs\"\n assert (\n arc4.UInt64.from_log(app_call.last_log)\n == (app_call.group_index + 1) * Global.group_size\n )\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/group_side_effects\/contract.py","language":"Python","license":"NOASSERTION","size":1200} {"code":"from algopy import ARC4Contract, Global, Txn, UInt64, arc4\n\n\nclass AppCall(ARC4Contract):\n @arc4.abimethod()\n def some_value(self) -> UInt64:\n return Global.group_size * (Txn.group_index + 1)\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/group_side_effects\/other.py","language":"Python","license":"NOASSERTION","size":205} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass AppCall(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def some_value(\n self,\n ) -> algopy.arc4.UIntN[typing.Literal[64]]: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/group_side_effects\/out\/client_AppCall.py","language":"Python","license":"NOASSERTION","size":271} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass AppExpectingEffects(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def create_group(\n self,\n asset_create: algopy.gtxn.AssetConfigTransaction,\n app_create: algopy.gtxn.ApplicationCallTransaction,\n ) -> algopy.arc4.Tuple[algopy.arc4.UIntN[typing.Literal[64]], algopy.arc4.UIntN[typing.Literal[64]]]: ...\n\n @algopy.arc4.abimethod\n def log_group(\n self,\n app_call: algopy.gtxn.ApplicationCallTransaction,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/group_side_effects\/out\/client_AppExpectingEffects.py","language":"Python","license":"NOASSERTION","size":599} {"code":"","repo_name":"algorandfoundation\/puya","path":"test_cases\/inheritance\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"import algopy\n\nfrom test_cases.inheritance.grandparent import GrandParentContract\nfrom test_cases.inheritance.parent import ParentContract\n\n\nclass ChildContract(ParentContract):\n @algopy.subroutine\n def method(self) -> bool:\n algopy.log(\"ChildContract.method called\")\n return GrandParentContract.method(self)\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/inheritance\/child.py","language":"Python","license":"NOASSERTION","size":329} {"code":"import algopy\n\n\nclass GreatGrandParentContract(algopy.Contract):\n def approval_program(self) -> bool:\n return self.method()\n\n def clear_state_program(self) -> bool:\n return True\n\n @algopy.subroutine\n def method(self) -> bool:\n algopy.log(\"GrandParentContract.method called\")\n return True\n\n\nclass GrandParentContract(GreatGrandParentContract):\n pass\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/inheritance\/grandparent.py","language":"Python","license":"NOASSERTION","size":392} {"code":"import algopy\n\nfrom test_cases.inheritance.grandparent import GrandParentContract\n\n\nclass ParentContract(GrandParentContract):\n @algopy.subroutine\n def method(self) -> bool:\n algopy.log(\"ParentContract.method called\")\n return super().method()\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/inheritance\/parent.py","language":"Python","license":"NOASSERTION","size":263} {"code":"import typing\n\nfrom algopy import Contract, UInt64, arc4, op, subroutine\n\n\nclass MyContract(Contract):\n def approval_program(self) -> bool:\n z = zero()\n a = one()\n b = one()\n assert z + a + b == 2\n never_returns()\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n\n@subroutine(inline=True)\ndef never_returns() -> typing.Never:\n op.err()\n\n\n@subroutine(inline=True)\ndef one() -> UInt64:\n return zero() + 1\n\n\n@subroutine(inline=True)\ndef zero() -> UInt64:\n return UInt64(0)\n\n\nclass NeverReturns(arc4.ARC4Contract):\n @arc4.abimethod()\n def err(self) -> None:\n op.err()\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/inlining\/contract.py","language":"Python","license":"NOASSERTION","size":660} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass NeverReturns(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def err(\n self,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/inlining\/out\/client_NeverReturns.py","language":"Python","license":"NOASSERTION","size":236} {"code":"from algopy import (\n ARC4Contract,\n Bytes,\n arc4,\n itxn,\n)\n\nLOG_1ST_ARG_AND_APPROVE = (\n b\"\\x09\" # pragma version 9\n b\"\\x36\\x1a\\x00\" # txna ApplicationArgs 0\n b\"\\xb0\" # log\n b\"\\x81\\x01\" # pushint 1\n)\nALWAYS_APPROVE = (\n b\"\\x09\" # pragma version 9\n b\"\\x81\\x01\" # pushint 1\n)\n\n\nclass ArrayAccessContract(ARC4Contract):\n @arc4.abimethod\n def test_branching_array_call(self, maybe: arc4.Bool) -> None:\n if maybe:\n create_app_txn = itxn.ApplicationCall(\n approval_program=ALWAYS_APPROVE,\n clear_state_program=ALWAYS_APPROVE,\n app_args=(Bytes(b\"1\"), Bytes(b\"2\")),\n ).submit()\n else:\n create_app_txn = itxn.ApplicationCall(\n approval_program=ALWAYS_APPROVE,\n clear_state_program=ALWAYS_APPROVE,\n app_args=(Bytes(b\"3\"), Bytes(b\"4\"), Bytes(b\"5\")),\n note=b\"different param set\",\n ).submit()\n if maybe:\n assert create_app_txn.app_args(0) == b\"1\", \"correct args used 1\"\n assert create_app_txn.app_args(1) == b\"2\", \"correct args used 2\"\n else:\n assert create_app_txn.app_args(0) == b\"3\", \"correct args used 1\"\n assert create_app_txn.app_args(1) == b\"4\", \"correct args used 2\"\n assert create_app_txn.app_args(2) == b\"5\", \"correct args used 3\"\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/inner_transactions\/array_access.py","language":"Python","license":"NOASSERTION","size":1404} {"code":"from algopy import (\n ARC4Contract,\n Global,\n arc4,\n itxn,\n op,\n)\n\n\nclass CreateAndTransferContract(ARC4Contract):\n @arc4.abimethod()\n def create_and_transfer(self) -> None:\n # create\n new_asset = (\n itxn.AssetConfig(\n total=1000,\n asset_name=\"test\",\n unit_name=\"TST\",\n decimals=0,\n manager=op.Global.current_application_address,\n clawback=op.Global.current_application_address,\n )\n .submit()\n .created_asset\n )\n\n # transfer\n itxn.AssetTransfer(\n asset_sender=new_asset.creator,\n asset_receiver=Global.current_application_address,\n asset_amount=1000,\n xfer_asset=new_asset,\n ).submit()\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/inner_transactions\/asset_transfer.py","language":"Python","license":"NOASSERTION","size":827} {"code":"from algopy import Application, ARC4Contract, Bytes, UInt64, arc4, itxn, log\n\nfrom test_cases.inner_transactions.programs import HELLO_WORLD_APPROVAL_HEX, HELLO_WORLD_CLEAR\n\n\nclass Greeter(ARC4Contract):\n def __init__(self) -> None:\n self.hello_app = Application()\n\n @arc4.abimethod()\n def bootstrap(self) -> UInt64:\n assert not self.hello_app, \"already bootstrapped\"\n self.hello_app = (\n itxn.ApplicationCall(\n approval_program=Bytes.from_hex(HELLO_WORLD_APPROVAL_HEX),\n clear_state_program=HELLO_WORLD_CLEAR,\n )\n .submit()\n .created_app\n )\n return self.hello_app.id\n\n @arc4.abimethod()\n def log_greetings(self, name: arc4.String) -> None:\n hello_call = itxn.ApplicationCall(\n app_id=self.hello_app,\n app_args=(arc4.arc4_signature(\"hello(string)string\"), name),\n ).submit()\n greeting = arc4.String.from_log(hello_call.last_log)\n log(\"HelloWorld returned: \", greeting.native)\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/inner_transactions\/c2c.py","language":"Python","license":"NOASSERTION","size":1050} {"code":"from algopy import (\n Bytes,\n Contract,\n OnCompleteAction,\n itxn,\n op,\n subroutine,\n)\n\nLOG_1ST_ARG_AND_APPROVE = (\n b\"\\x09\" # pragma version 9\n b\"\\x36\\x1a\\x00\" # txna ApplicationArgs 0\n b\"\\xb0\" # log\n b\"\\x81\\x01\" # pushint 1\n)\nALWAYS_APPROVE = (\n b\"\\x09\" # pragma version 9\n b\"\\x81\\x01\" # pushint 1\n)\n\n\nclass MyContract(Contract):\n def __init__(self) -> None:\n self.name = Bytes(b\"\")\n\n def approval_program(self) -> bool:\n if op.Txn.num_app_args:\n match op.Txn.application_args(0):\n case Bytes(b\"test1\"):\n self.test1()\n case Bytes(b\"test2\"):\n self.test2()\n case Bytes(b\"test3\"):\n self.test3()\n case Bytes(b\"test4\"):\n self.test4()\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n @subroutine\n def test1(self) -> None:\n self.name = Bytes(b\"AST1\")\n asset_params = itxn.AssetConfig(\n total=1000,\n asset_name=self.name,\n unit_name=b\"unit\",\n decimals=3,\n manager=op.Global.current_application_address,\n reserve=op.Global.current_application_address,\n )\n self.name = Bytes(b\"AST2\")\n asset1_txn = asset_params.submit()\n\n asset_params.set(\n asset_name=self.name,\n )\n\n asset2_txn = asset_params.submit()\n\n assert asset1_txn.asset_name == b\"AST1\", \"asset1_txn is correct\"\n assert asset2_txn.asset_name == b\"AST2\", \"asset2_txn is correct\"\n\n assert asset1_txn.created_asset.name == b\"AST1\", \"created asset 1 is correct\"\n assert asset2_txn.created_asset.name == b\"AST2\", \"created asset 2 is correct\"\n\n app_create_params = itxn.ApplicationCall(\n approval_program=b\"\\x09\\x81\\x01\",\n clear_state_program=Bytes.from_hex(\"098101\"),\n fee=0,\n )\n\n asset_params.set(\n asset_name=Bytes(b\"AST3\"),\n )\n\n app_create_txn, asset3_txn = itxn.submit_txns(app_create_params, asset_params)\n\n assert app_create_txn.created_app, \"created app\"\n assert asset3_txn.asset_name == b\"AST3\", \"asset3_txn is correct\"\n\n app_create_params.set(note=b\"3rd\")\n asset_params.set(note=b\"3rd\")\n # unassigned result\n itxn.submit_txns(app_create_params, asset_params)\n\n @subroutine\n def test2(self) -> None:\n if op.Txn.num_app_args:\n args = Bytes(b\"1\"), Bytes(b\"2\")\n create_app_params = itxn.ApplicationCall(\n approval_program=ALWAYS_APPROVE,\n clear_state_program=ALWAYS_APPROVE,\n app_args=args,\n on_completion=OnCompleteAction.NoOp,\n note=b\"with args param set\",\n )\n else:\n create_app_params = itxn.ApplicationCall(\n approval_program=ALWAYS_APPROVE,\n clear_state_program=ALWAYS_APPROVE,\n app_args=(Bytes(b\"3\"), Bytes(b\"4\"), Bytes(b\"5\")),\n note=b\"no args param set\",\n )\n create_app_txn = create_app_params.submit()\n assert create_app_txn.app_args(0) == b\"1\", \"correct args used 1\"\n assert create_app_txn.app_args(1) == b\"2\", \"correct args used 2\"\n\n if op.Txn.num_app_args > 1:\n create_app_txn2 = itxn.ApplicationCall(\n approval_program=ALWAYS_APPROVE,\n clear_state_program=ALWAYS_APPROVE,\n on_completion=OnCompleteAction.DeleteApplication,\n app_args=(Bytes(b\"42\"),),\n ).submit()\n assert create_app_txn2.app_args(0) == b\"42\", \"correct args used 2\"\n assert create_app_txn.note == b\"with args param set\"\n\n @subroutine\n def test3(self) -> None:\n app_p_1 = itxn.ApplicationCall(\n approval_program=LOG_1ST_ARG_AND_APPROVE,\n clear_state_program=ALWAYS_APPROVE,\n on_completion=OnCompleteAction.DeleteApplication,\n app_args=(Bytes(b\"1\"),),\n )\n\n app_p_2 = app_p_1.copy().copy()\n app_p_2.set(app_args=(Bytes(b\"2\"),))\n\n app_p_3 = app_p_1.copy()\n app_p_3.set(app_args=(Bytes(b\"3\"),))\n\n app_p_4 = app_p_1.copy()\n app_p_4.set(app_args=(Bytes(b\"4\"),))\n\n app_p_5 = app_p_1.copy()\n app_p_5.set(app_args=(Bytes(b\"5\"),))\n\n app_p_6 = app_p_1.copy()\n app_p_6.set(app_args=(Bytes(b\"6\"),))\n\n app_p_7 = app_p_1.copy()\n app_p_7.set(app_args=(Bytes(b\"7\"),))\n\n app_p_8 = app_p_1.copy()\n app_p_8.set(app_args=(Bytes(b\"8\"),))\n\n app_p_9 = app_p_1.copy()\n app_p_9.set(app_args=(Bytes(b\"9\"),))\n\n app_p_10 = app_p_1.copy()\n app_p_10.set(app_args=(Bytes(b\"10\"),))\n\n app_p_11 = app_p_1.copy()\n app_p_11.set(app_args=(Bytes(b\"11\"),))\n\n app_p_12 = app_p_1.copy()\n app_p_12.set(app_args=(Bytes(b\"12\"),))\n\n app_p_13 = app_p_1.copy()\n app_p_13.set(app_args=(Bytes(b\"13\"),))\n\n app_p_14 = app_p_1.copy()\n app_p_14.set(app_args=(Bytes(b\"14\"),))\n\n app_p_15 = app_p_1.copy()\n app_p_15.set(app_args=(Bytes(b\"15\"),))\n\n app_p_16 = app_p_1.copy()\n app_p_16.set(app_args=(Bytes(b\"16\"),))\n (\n app1,\n app2,\n app3,\n app4,\n app5,\n app6,\n app7,\n app8,\n app9,\n app10,\n app11,\n app12,\n app13,\n app14,\n app15,\n app16,\n ) = itxn.submit_txns(\n app_p_1,\n app_p_2,\n app_p_3,\n app_p_4,\n app_p_5,\n app_p_6,\n app_p_7,\n app_p_8,\n app_p_9,\n app_p_10,\n app_p_11,\n app_p_12,\n app_p_13,\n app_p_14,\n app_p_15,\n app_p_16,\n )\n\n assert app1.logs(0) == b\"1\"\n assert app2.logs(0) == b\"2\"\n assert app3.logs(0) == b\"3\"\n assert app4.logs(0) == b\"4\"\n assert app5.logs(0) == b\"5\"\n assert app6.logs(0) == b\"6\"\n assert app7.logs(0) == b\"7\"\n assert app8.logs(0) == b\"8\"\n assert app9.logs(0) == b\"9\"\n assert app10.logs(0) == b\"10\"\n assert app11.logs(0) == b\"11\"\n assert app12.logs(0) == b\"12\"\n assert app13.logs(0) == b\"13\"\n assert app14.logs(0) == b\"14\"\n assert app15.logs(0) == b\"15\"\n assert app16.logs(0) == b\"16\"\n\n @subroutine\n def test4(self) -> None:\n lots_of_bytes = op.bzero(2044)\n approval_1 = Bytes(ALWAYS_APPROVE)\n approval_2 = (\n Bytes(\n b\"\\x80\" # pushbytes\n b\"\\xfc\\x0f\" # varuint 2044\n )\n + lots_of_bytes\n + Bytes(b\"\\x48\") # pop\n )\n app_p_1 = itxn.ApplicationCall(\n approval_program=(approval_1, approval_2, approval_2, approval_2),\n clear_state_program=ALWAYS_APPROVE,\n on_completion=OnCompleteAction.DeleteApplication,\n app_args=(Bytes(b\"1\"),),\n extra_program_pages=3,\n )\n app_1 = app_p_1.submit()\n assert app_1.extra_program_pages == 3, \"extra_pages == 3\"\n assert app_1.num_approval_program_pages == 2, \"approval_pages == 2\"\n assert (\n app_1.approval_program_pages(0) == approval_1 + approval_2 + approval_2[:-3]\n ), \"expected approval page 0\"\n assert (\n app_1.approval_program_pages(1) == approval_2[-3:] + approval_2\n ), \"expected approval page 1\"\n assert app_1.num_clear_state_program_pages == 1, \"clear_state_pages == 1\"\n assert app_1.clear_state_program_pages(0) == ALWAYS_APPROVE, \"expected clear_state_pages\"\n\n\n@subroutine\ndef echo(v: Bytes) -> Bytes:\n return v\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/inner_transactions\/contract.py","language":"Python","license":"NOASSERTION","size":7946} {"code":"from algopy import (\n ARC4Contract,\n Bytes,\n OnCompleteAction,\n String,\n UInt64,\n arc4,\n itxn,\n op,\n)\n\nLOG_1ST_ARG_AND_APPROVE = (\n b\"\\x09\" # pragma version 9\n b\"\\x36\\x1a\\x00\" # txna ApplicationArgs 0\n b\"\\xb0\" # log\n b\"\\x81\\x01\" # pushint 1\n)\nALWAYS_APPROVE = (\n b\"\\x09\" # pragma version 9\n b\"\\x81\\x01\" # pushint 1\n)\n\n\nclass FieldTupleContract(ARC4Contract):\n @arc4.abimethod\n def test_assign_tuple(self) -> None:\n create_txns = (\n itxn.ApplicationCall(\n approval_program=ALWAYS_APPROVE,\n clear_state_program=ALWAYS_APPROVE,\n on_completion=OnCompleteAction.DeleteApplication,\n app_args=(\n Bytes(b\"1a\"),\n Bytes(b\"2a\"),\n b\"hello\",\n \"world\",\n String(\"!\"),\n UInt64(42),\n True,\n ),\n ),\n itxn.ApplicationCall(\n approval_program=ALWAYS_APPROVE,\n clear_state_program=ALWAYS_APPROVE,\n on_completion=OnCompleteAction.DeleteApplication,\n app_args=(Bytes(b\"3a\"), Bytes(b\"4a\"), Bytes(b\"5a\")),\n note=b\"different param set\",\n ),\n )\n txn_1, txn_2 = itxn.submit_txns(create_txns[0], create_txns[1])\n\n assert txn_1.app_args(0) == b\"1a\"\n assert txn_1.app_args(1) == b\"2a\"\n assert txn_1.app_args(2) == b\"hello\"\n assert txn_1.app_args(3) == b\"world\"\n assert txn_1.app_args(4) == b\"!\"\n assert txn_1.app_args(5) == op.itob(42)\n assert txn_1.app_args(6) == op.itob(1)\n assert txn_2.app_args(0) == b\"3a\"\n assert txn_2.app_args(1) == b\"4a\"\n assert txn_2.app_args(2) == b\"5a\"\n\n create_txns[0].set(app_args=(Bytes(b\"1b\"), Bytes(b\"2b\")))\n create_txns[1].set(app_args=(Bytes(b\"3b\"), Bytes(b\"4b\"), Bytes(b\"5b\")))\n\n txn_1, txn_2 = itxn.submit_txns(create_txns[1], create_txns[0])\n\n assert txn_2.app_args(0) == b\"1b\"\n assert txn_2.app_args(1) == b\"2b\"\n assert txn_1.app_args(0) == b\"3b\"\n assert txn_1.app_args(1) == b\"4b\"\n assert txn_1.app_args(2) == b\"5b\"\n\n create_txns[0].set(app_args=(Bytes(b\"1c\"), Bytes(b\"2c\")))\n create_txns[1].set(app_args=(Bytes(b\"3c\"), Bytes(b\"4c\"), Bytes(b\"5c\")))\n\n txn_tuple = itxn.submit_txns(create_txns[0], create_txns[1])\n\n assert txn_tuple[0].app_args(0) == b\"1c\"\n assert txn_tuple[0].app_args(1) == b\"2c\"\n assert txn_tuple[1].app_args(0) == b\"3c\"\n assert txn_tuple[1].app_args(1) == b\"4c\"\n assert txn_tuple[1].app_args(2) == b\"5c\"\n\n @arc4.abimethod\n def test_assign_tuple_mixed(self) -> None:\n tuple_with_txn_fields = (\n itxn.ApplicationCall(\n approval_program=ALWAYS_APPROVE,\n clear_state_program=ALWAYS_APPROVE,\n on_completion=OnCompleteAction.DeleteApplication,\n app_args=(Bytes(b\"1a\"), Bytes(b\"2a\")),\n ),\n Bytes(b\"some other value\"),\n )\n result_with_txn = tuple_with_txn_fields[0].submit(), tuple_with_txn_fields[1]\n\n assert result_with_txn[0].app_args(0) == b\"1a\"\n assert result_with_txn[0].app_args(1) == b\"2a\"\n assert result_with_txn[1] == b\"some other value\"\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/inner_transactions\/field_tuple_assignment.py","language":"Python","license":"NOASSERTION","size":3392} {"code":"from algopy import (\n Bytes,\n Contract,\n OnCompleteAction,\n UInt64,\n itxn,\n log,\n op,\n urange,\n)\n\nfrom test_cases.inner_transactions import programs\n\n\nclass MyContract(Contract, name=\"itxn_loop\"):\n def clear_state_program(self) -> bool:\n return True\n\n def approval_program(self) -> bool:\n note = Bytes(b\"ABCDE\")\n app_params = itxn.ApplicationCall(\n approval_program=programs.ALWAYS_APPROVE,\n clear_state_program=programs.ALWAYS_APPROVE,\n on_completion=OnCompleteAction.DeleteApplication,\n note=b\"\",\n )\n for i in urange(4):\n i_note = op.extract(note, 0, i)\n match i:\n case UInt64(1):\n app_params.set(note=i_note, app_args=(Bytes(b\"1\"),))\n case UInt64(2):\n app_params.set(note=i_note, app_args=(Bytes(b\"2\"), Bytes(b\"1\")))\n case UInt64(3):\n app_params.set(\n note=i_note,\n app_args=(Bytes(b\"3\"), Bytes(b\"2\"), Bytes(b\"1\")),\n )\n app_txn = app_params.submit()\n log(app_txn.note)\n log(app_txn.num_app_args)\n\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/inner_transactions\/itxn_loop.py","language":"Python","license":"NOASSERTION","size":1251} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass ArrayAccessContract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def test_branching_array_call(\n self,\n maybe: algopy.arc4.Bool,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/inner_transactions\/out\/client_ArrayAccessContract.py","language":"Python","license":"NOASSERTION","size":298} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass CreateAndTransferContract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def create_and_transfer(\n self,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/inner_transactions\/out\/client_CreateAndTransferContract.py","language":"Python","license":"NOASSERTION","size":265} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass FieldTupleContract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def test_assign_tuple(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_assign_tuple_mixed(\n self,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/inner_transactions\/out\/client_FieldTupleContract.py","language":"Python","license":"NOASSERTION","size":350} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass Greeter(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def bootstrap(\n self,\n ) -> algopy.arc4.UIntN[typing.Literal[64]]: ...\n\n @algopy.arc4.abimethod\n def log_greetings(\n self,\n name: algopy.arc4.String,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/inner_transactions\/out\/client_Greeter.py","language":"Python","license":"NOASSERTION","size":388} {"code":"LOG_1ST_ARG_AND_APPROVE = (\n b\"\\x0a\" # pragma version 10\n b\"\\x36\\x1a\\x00\" # txna ApplicationArgs 0\n b\"\\xb0\" # log\n b\"\\x81\\x01\" # pushint 1\n)\nALWAYS_APPROVE = (\n b\"\\x0a\" # pragma version 10\n b\"\\x81\\x01\" # pushint 1\n)\nHELLO_WORLD_CLEAR = ALWAYS_APPROVE\nHELLO_WORLD_APPROVAL_HEX = (\n \"0a200101311b410026800402bece1136\"\n \"1a008e0100010031191444311844361a\"\n \"018800158004151f7c754c50b0224331\"\n \"1914443118144422438a01018bff5702\"\n \"00800748656c6c6f2c204c5049151657\"\n \"06004c5089\"\n)\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/inner_transactions\/programs.py","language":"Python","license":"NOASSERTION","size":518} {"code":"from algopy import (\n ARC4Contract,\n Bytes,\n Txn,\n arc4,\n itxn,\n subroutine,\n)\n\n\nclass Contract(ARC4Contract):\n @arc4.abimethod\n def test_itxn_slice(self) -> None:\n acfg = itxn.AssetConfig(\n unit_name=\"TST\",\n asset_name=\"TEST\",\n note=\"acfg\",\n total=1,\n )\n pay1 = itxn.Payment(receiver=Txn.sender, amount=0, note=\"pay1\")\n pay2 = pay1.copy()\n pay2.set(note=\"pay2\")\n pay3 = pay2.copy()\n pay3.set(note=\"pay3\")\n sliced_txns = itxn.submit_txns(pay1, acfg, pay2, pay3)[1:-1]\n assert sliced_txns[0].note == b\"acfg\"\n assert sliced_txns[1].note == b\"pay2\"\n\n @arc4.abimethod\n def test_itxn_nested(self) -> None:\n acfg = itxn.AssetConfig(\n unit_name=\"TST\",\n asset_name=\"TEST\",\n note=\"acfg\",\n total=1,\n )\n pay1 = itxn.Payment(receiver=Txn.sender, amount=0, note=\"pay1\")\n pay2 = pay1.copy()\n pay2.set(note=\"pay2\")\n pay3 = pay2.copy()\n pay3.set(note=\"pay3\")\n nested_tuple = (\n echo(Bytes(b\"hi\")),\n itxn.submit_txns(pay1, acfg, pay2, pay3)[1:-1],\n echo(Bytes(b\"there\")),\n )\n assert nested_tuple[0] == b\"hi\"\n assert nested_tuple[1][0].note == b\"acfg\"\n assert nested_tuple[1][1].note == b\"pay2\"\n assert nested_tuple[2] == b\"there\"\n nested_tuple_copy = nested_tuple\n\n acfg.set(note=\"acfg2\")\n pay2.set(note=\"pay4\")\n pay3.set(note=\"pay5\")\n\n if echo(Bytes(b\"maybe\")) == b\"maybe\":\n nested_tuple = (\n echo(Bytes(b\"hi2\")),\n itxn.submit_txns(pay1, acfg, pay3)[1:],\n echo(Bytes(b\"there2\")),\n )\n assert nested_tuple[0] == b\"hi2\"\n assert nested_tuple[1][0].note == b\"acfg2\"\n assert nested_tuple[1][1].note == b\"pay5\"\n assert nested_tuple[2] == b\"there2\"\n\n mish_mash = nested_tuple_copy[1][0], nested_tuple_copy[1][1], nested_tuple[1]\n\n assert mish_mash[0].note == b\"acfg\"\n assert mish_mash[1].note == b\"pay2\"\n assert mish_mash[2][0].note == b\"acfg2\"\n assert mish_mash[2][1].note == b\"pay5\"\n\n\n@subroutine\ndef echo(value: Bytes) -> Bytes:\n return value\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/inner_transactions_assignment\/contract.py","language":"Python","license":"NOASSERTION","size":2302} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass Contract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def test_itxn_slice(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_itxn_nested(\n self,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/inner_transactions_assignment\/out\/client_Contract.py","language":"Python","license":"NOASSERTION","size":331} {"code":"from algopy import (\n Bytes,\n Contract,\n OnCompleteAction,\n TransactionType,\n UInt64,\n)\nfrom algopy.op import (\n GITxn,\n GTxn,\n ITxn,\n ITxnCreate,\n Txn,\n)\n\n\nclass ImmediateVariants(Contract):\n def approval_program(self) -> bool:\n num_app_args = Txn.num_app_args\n assert GTxn.num_app_args(0) == num_app_args\n assert GTxn.num_app_args(UInt64(0)) == num_app_args\n first_arg = Txn.application_args(0)\n assert Txn.application_args(UInt64(0)) == first_arg\n assert GTxn.application_args(0, 0) == first_arg\n assert GTxn.application_args(0, UInt64(0)) == first_arg\n assert GTxn.application_args(UInt64(0), 0) == first_arg\n assert GTxn.application_args(UInt64(0), UInt64(0)) == first_arg\n\n ITxnCreate.begin()\n ITxnCreate.set_type_enum(TransactionType.ApplicationCall)\n ITxnCreate.set_on_completion(OnCompleteAction.DeleteApplication)\n ITxnCreate.set_approval_program(Bytes.from_hex(\"068101\"))\n ITxnCreate.set_clear_state_program(Bytes.from_hex(\"068101\"))\n ITxnCreate.set_fee(0) # cover fee with outer txn\n ITxnCreate.set_fee(UInt64(0)) # cover fee with outer txn\n ITxnCreate.set_application_args(first_arg)\n second_arg = first_arg + b\"2\"\n ITxnCreate.set_application_args(second_arg)\n ITxnCreate.submit()\n\n assert ITxn.num_app_args() == 2\n assert ITxn.application_args(0) == first_arg\n assert ITxn.application_args(UInt64(1)) == second_arg\n\n assert GITxn.num_app_args(0) == 2\n assert GITxn.application_args(0, UInt64(0)) == first_arg\n assert GITxn.application_args(0, UInt64(1)) == second_arg\n assert GITxn.application_args(0, 0) == first_arg\n assert GITxn.application_args(0, 1) == second_arg\n\n return True\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/intrinsics\/immediate_variants.py","language":"Python","license":"NOASSERTION","size":1899} {"code":"from algopy import Contract, GlobalState, UInt64, op\n\n\nclass Overloaded(Contract):\n def __init__(self) -> None:\n self.key = GlobalState(UInt64(0))\n\n def approval_program(self) -> bool:\n assert op.AppGlobal.get_uint64(b\"key\") == op.AppGlobal.get_uint64(b\"key\")\n assert self.key.maybe()[0] == self.key.maybe()[0]\n assert op.setbit_uint64(0, 0, 1) == op.setbit_uint64(0, 0, 1)\n assert op.select_uint64(0, 1, True) == op.select_uint64(1, 0, False)\n assert op.getbit(op.setbit_uint64(2**64 - 1, 3, 0), 3) == 0\n assert op.getbit(op.setbit_uint64(123, 4, 1), 4) == 1\n return True\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/intrinsics\/overloaded.py","language":"Python","license":"NOASSERTION","size":699} {"code":"","repo_name":"algorandfoundation\/puya","path":"test_cases\/iteration\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"import abc\n\nfrom algopy import Bytes, Contract, UInt64, log, subroutine\n\n\nclass IterationTestBase(Contract, abc.ABC):\n def approval_program(self) -> bool:\n log(\"test_forwards\")\n self.test_forwards()\n log(\"test_reversed\")\n self.test_reversed()\n log(\"test_forwards_with_forwards_index\")\n self.test_forwards_with_forwards_index()\n log(\"test_forwards_with_reverse_index\")\n self.test_forwards_with_reverse_index()\n log(\"test_reverse_with_forwards_index\")\n self.test_reverse_with_forwards_index()\n log(\"test_reverse_with_reverse_index\")\n self.test_reverse_with_reverse_index()\n log(\"test_empty\")\n self.test_empty()\n log(\"test_break\")\n self.test_break()\n log(\"test_tuple_target\")\n self.test_tuple_target()\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n @subroutine\n def _log_with_index(self, idx: UInt64, value: Bytes) -> None:\n digits = Bytes(b\"0123456789\")\n log(digits[idx], value, sep=\"=\")\n\n @subroutine\n @abc.abstractmethod\n def test_forwards(self) -> None: ...\n\n @subroutine\n @abc.abstractmethod\n def test_reversed(self) -> None: ...\n\n @subroutine\n @abc.abstractmethod\n def test_forwards_with_forwards_index(self) -> None: ...\n\n @subroutine\n @abc.abstractmethod\n def test_forwards_with_reverse_index(self) -> None: ...\n\n @subroutine\n @abc.abstractmethod\n def test_reverse_with_forwards_index(self) -> None: ...\n\n @subroutine\n @abc.abstractmethod\n def test_reverse_with_reverse_index(self) -> None: ...\n\n @subroutine\n @abc.abstractmethod\n def test_empty(self) -> None: ...\n\n @subroutine\n @abc.abstractmethod\n def test_break(self) -> None: ...\n\n @subroutine\n @abc.abstractmethod\n def test_tuple_target(self) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/iteration\/base.py","language":"Python","license":"NOASSERTION","size":1886} {"code":"import typing\n\nfrom algopy import Bytes, log, subroutine, uenumerate\n\nfrom test_cases.iteration.base import IterationTestBase\n\n\nclass IndexableIterationTest(IterationTestBase):\n @typing.override\n @subroutine\n def test_forwards(self) -> None:\n for i in Bytes(b\"abc\"):\n log(i)\n\n @typing.override\n @subroutine\n def test_reversed(self) -> None:\n for i in reversed(Bytes(b\"abc\")):\n log(i)\n\n @typing.override\n @subroutine\n def test_forwards_with_forwards_index(self) -> None:\n for idx, i in uenumerate(Bytes(b\"abc\")):\n self._log_with_index(idx, i)\n idx += 1\n\n @typing.override\n @subroutine\n def test_forwards_with_reverse_index(self) -> None:\n for idx, i in reversed(uenumerate(reversed(Bytes(b\"abc\")))):\n self._log_with_index(idx, i)\n idx += 1\n\n @typing.override\n @subroutine\n def test_reverse_with_forwards_index(self) -> None:\n for idx, i in uenumerate(reversed(Bytes(b\"abc\"))):\n self._log_with_index(idx, i)\n idx += 1\n\n @typing.override\n @subroutine\n def test_reverse_with_reverse_index(self) -> None:\n for idx, i in reversed(uenumerate(Bytes(b\"abc\"))):\n self._log_with_index(idx, i)\n idx += 1\n\n @typing.override\n @subroutine\n def test_empty(self) -> None:\n for i in Bytes():\n log(i)\n for i in reversed(Bytes()):\n log(i)\n for idx, i in uenumerate(Bytes()):\n self._log_with_index(idx, i)\n for idx, i in reversed(uenumerate(reversed(Bytes()))):\n self._log_with_index(idx, i)\n for idx, i in uenumerate(reversed(Bytes())):\n self._log_with_index(idx, i)\n for idx, i in reversed(uenumerate(Bytes())):\n self._log_with_index(idx, i)\n\n @typing.override\n @subroutine\n def test_break(self) -> None:\n for b in Bytes(b\"abc\"):\n log(b)\n break\n\n @typing.override\n @subroutine\n def test_tuple_target(self) -> None:\n for tup in uenumerate(Bytes(b\"t\")):\n self._log_with_index(tup[0], tup[1])\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/iteration\/iterate_indexable.py","language":"Python","license":"NOASSERTION","size":2159} {"code":"import typing\n\nfrom algopy import Bytes, log, subroutine, uenumerate\n\nfrom test_cases.iteration.base import IterationTestBase\n\n\nclass TupleIterationTest(IterationTestBase):\n @typing.override\n @subroutine\n def test_forwards(self) -> None:\n for i in (Bytes(b\"a\"), Bytes(b\"b\"), Bytes(b\"c\")):\n log(i)\n\n @typing.override\n @subroutine\n def test_reversed(self) -> None:\n for i in reversed((Bytes(b\"a\"), Bytes(b\"b\"), Bytes(b\"c\"))):\n log(i)\n\n @typing.override\n @subroutine\n def test_forwards_with_forwards_index(self) -> None:\n for idx, i in uenumerate((Bytes(b\"a\"), Bytes(b\"b\"), Bytes(b\"c\"))):\n self._log_with_index(idx, i)\n idx += 1\n\n @typing.override\n @subroutine\n def test_forwards_with_reverse_index(self) -> None:\n for idx, i in reversed(uenumerate(reversed((Bytes(b\"a\"), Bytes(b\"b\"), Bytes(b\"c\"))))):\n self._log_with_index(idx, i)\n idx += 1\n\n @typing.override\n @subroutine\n def test_reverse_with_forwards_index(self) -> None:\n for idx, i in uenumerate(reversed((Bytes(b\"a\"), Bytes(b\"b\"), Bytes(b\"c\")))):\n self._log_with_index(idx, i)\n idx += 1\n\n @typing.override\n @subroutine\n def test_reverse_with_reverse_index(self) -> None:\n for idx, i in reversed(uenumerate((Bytes(b\"a\"), Bytes(b\"b\"), Bytes(b\"c\")))):\n self._log_with_index(idx, i)\n idx += 1\n\n @typing.override\n @subroutine\n def test_empty(self) -> None:\n \"\"\"empty tuples not supported (yet)\"\"\"\n # i: Bytes\n # for i in ():\n # log(i)\n # for i in reversed(()):\n # log(i)\n # for idx, i in uenumerate(()):\n # log(idx)\n # log(i)\n # for idx, i in reversed(uenumerate(reversed(()))):\n # log(idx)\n # log(i)\n # for idx, i in uenumerate(reversed(())):\n # log(idx)\n # log(i)\n # for idx, i in reversed(uenumerate(())):\n # log(idx)\n # log(i)\n\n @typing.override\n @subroutine\n def test_break(self) -> None:\n for x in (Bytes(b\"a\"), Bytes(b\"b\"), Bytes(b\"c\")):\n log(x)\n break\n\n @typing.override\n @subroutine\n def test_tuple_target(self) -> None:\n for tup in uenumerate((Bytes(b\"t\"),)):\n self._log_with_index(tup[0], tup[1])\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/iteration\/iterate_tuple.py","language":"Python","license":"NOASSERTION","size":2404} {"code":"import typing\n\nfrom algopy import Bytes, log, subroutine, uenumerate, urange\n\nfrom test_cases.iteration.base import IterationTestBase\n\n\nclass URangeIterationTest(IterationTestBase):\n @typing.override\n @subroutine\n def test_forwards(self) -> None:\n values = Bytes(b\" a b c\")\n for i in urange(1, 7, 2):\n log(values[i])\n i += 1\n\n @typing.override\n @subroutine\n def test_reversed(self) -> None:\n values = Bytes(b\" a b c\")\n for i in reversed(urange(1, 7, 2)):\n log(values[i])\n i += 1\n\n @typing.override\n @subroutine\n def test_forwards_with_forwards_index(self) -> None:\n values = Bytes(b\" a b c\")\n for idx, i in uenumerate(urange(1, 7, 2)):\n self._log_with_index(idx, values[i])\n i += 1\n idx += 1\n\n @typing.override\n @subroutine\n def test_forwards_with_reverse_index(self) -> None:\n values = Bytes(b\" a b c\")\n for idx, i in reversed(uenumerate(reversed(urange(1, 7, 2)))):\n self._log_with_index(idx, values[i])\n i += 1\n idx += 1\n\n @typing.override\n @subroutine\n def test_reverse_with_forwards_index(self) -> None:\n values = Bytes(b\" a b c\")\n for idx, i in uenumerate(reversed(urange(1, 7, 2))):\n self._log_with_index(idx, values[i])\n i += 1\n idx += 1\n\n @typing.override\n @subroutine\n def test_reverse_with_reverse_index(self) -> None:\n values = Bytes(b\" a b c\")\n for idx, i in reversed(uenumerate(urange(1, 7, 2))):\n self._log_with_index(idx, values[i])\n i += 1\n idx += 1\n\n @typing.override\n @subroutine\n def test_empty(self) -> None:\n for i in urange(0):\n log(i)\n for i in reversed(urange(0)):\n log(i)\n for idx, i in uenumerate(urange(0)):\n log(idx, i)\n for idx, i in reversed(uenumerate(reversed(urange(0)))):\n log(idx, i)\n for idx, i in uenumerate(reversed(urange(0))):\n log(idx, i)\n for idx, i in reversed(uenumerate(urange(0))):\n log(idx, i)\n\n @typing.override\n @subroutine\n def test_break(self) -> None:\n values = Bytes(b\" a b c\")\n for i in urange(1, 7, 2):\n log(values[i])\n break\n\n @typing.override\n @subroutine\n def test_tuple_target(self) -> None:\n values = Bytes(b\"t\")\n for tup in uenumerate(urange(1)):\n self._log_with_index(tup[0], values[tup[1]])\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/iteration\/iterate_urange.py","language":"Python","license":"NOASSERTION","size":2565} {"code":"from algopy import Contract, UInt64\n\n\nclass MyContract(Contract):\n \"\"\"My contract\"\"\"\n\n def approval_program(self) -> UInt64:\n a = UInt64(75)\n c = UInt64(77)\n b = a + c\n a = b + 5\n c = b + a\n\n return c\n\n def clear_state_program(self) -> UInt64:\n return UInt64(1)\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/koopman\/contract.py","language":"Python","license":"NOASSERTION","size":320} {"code":"","repo_name":"algorandfoundation\/puya","path":"test_cases\/less_simple\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"# ruff: noqa: F403, F405\nfrom algopy import * # note: star import here to explicitly test that\n\n\nclass MyContract(Contract):\n \"\"\"My contract\"\"\"\n\n def approval_program(self) -> UInt64:\n a = UInt64(1)\n sum_of_evens = UInt64(0)\n product_of_odds = UInt64(0)\n while a < 100:\n if a % 5 == 0:\n continue\n if not a % 21:\n break\n if a % 2 == 0:\n sum_of_evens += a\n else: # noqa: PLR5501\n if product_of_odds == 0:\n product_of_odds = a\n else:\n product_of_odds *= a\n a += 1\n return product_of_odds - sum_of_evens\n\n def clear_state_program(self) -> UInt64:\n sum_of_squares = UInt64(0)\n for i in urange(1, 100):\n square_root = op.sqrt(i)\n if square_root * square_root == i:\n sum_of_squares += i\n if sum_of_squares > 200:\n break\n return sum_of_squares\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/less_simple\/contract.py","language":"Python","license":"NOASSERTION","size":1034} {"code":"# ruff: noqa\nfrom algopy import *\n\n\n@subroutine\ndef unary_str() -> None:\n assert not \"\"\n assert not (not \"abc\")\n\n\n@subroutine\ndef compare_str() -> None:\n assert not (\"a\" == \"b\") # type: ignore[comparison-overlap]\n assert \"a\" != \"b\" # type: ignore[comparison-overlap]\n assert \"a\" < \"b\"\n assert \"a\" <= \"b\"\n assert not (\"a\" > \"b\")\n assert not (\"a\" >= \"b\")\n assert \"a\" not in \"b\"\n assert not (\"a\" in \"b\")\n assert \"a\" in \"abc\"\n\n b = String(\"b\")\n assert not (\"a\" == b)\n assert \"a\" != b\n assert \"a\" not in b\n assert not (\"a\" in b)\n assert \"a\" in String(\"abc\")\n\n\n@subroutine\ndef binary_op_str() -> None:\n assert \"a\" and \"b\"\n assert \"a\" or \"b\"\n assert \"\" or \"b\"\n assert not (\"a\" and \"\")\n assert not (\"\" or \"\")\n assert (\"a\" + \"\") == \"a\"\n\n\n@subroutine\ndef unary_bytes() -> None:\n assert not b\"\"\n assert not (not b\"abc\")\n\n\n@subroutine\ndef unary_int() -> None:\n assert not 0\n assert not (not 1)\n assert -1 == (0 - 1)\n assert +1 == (0 + 1)\n assert ~0 == -1\n\n\n@subroutine\ndef compare_int() -> None:\n assert not (0 == 1) # type: ignore[comparison-overlap]\n assert 0 != 1 # type: ignore[comparison-overlap]\n assert 0 < 1\n assert 0 <= 1\n assert not (0 > 1)\n assert not (0 >= 1)\n\n one = UInt64(1)\n assert not (0 == one)\n assert 0 != one\n assert 0 < one\n assert 0 <= one\n assert not (0 > one)\n assert not (0 >= one)\n\n\n@subroutine\ndef unary_bool() -> None:\n assert not False\n assert not (not True)\n assert -True == -1\n assert +False == 0\n assert ~True == -2\n\n\n@subroutine\ndef tuples() -> None:\n assert (97, UInt64(98), 99) == tuple(b\"abc\") # type: ignore[comparison-overlap]\n assert (\"a\", \"b\", \"c\") == tuple(\"abc\")\n assert (97, UInt64(98), 99) == tuple(\n arc4.StaticArray(arc4.UInt64(97), arc4.UInt64(98), arc4.UInt64(99))\n ) # type: ignore[comparison-overlap]\n assert (1, 2) == tuple((1, 2))\n\n\nclass LiteralFolding(Contract):\n def approval_program(self) -> bool:\n unary_str()\n compare_str()\n binary_op_str()\n unary_bytes()\n unary_int()\n compare_int()\n unary_bool()\n tuples()\n return True\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/literals\/folding.py","language":"Python","license":"NOASSERTION","size":2270} {"code":"from algopy import BigUInt, Bytes, Contract, log, op\n\n\nclass MyContract(Contract):\n def approval_program(self) -> bool:\n log(0)\n log(b\"1\")\n log(\"2\")\n log(op.Txn.num_app_args + 3)\n log(Bytes(b\"4\") if op.Txn.num_app_args else Bytes())\n log(\n b\"5\",\n 6,\n op.Txn.num_app_args + 7,\n BigUInt(8),\n Bytes(b\"9\") if op.Txn.num_app_args else Bytes(),\n )\n log(\n b\"5\",\n 6,\n op.Txn.num_app_args + 7,\n BigUInt(8),\n Bytes(b\"9\") if op.Txn.num_app_args else Bytes(),\n sep=b\"_\",\n )\n log(\n b\"5\",\n 6,\n op.Txn.num_app_args + 7,\n BigUInt(8),\n Bytes(b\"9\") if op.Txn.num_app_args else Bytes(),\n sep=\"_\",\n )\n return True\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/log\/contract.py","language":"Python","license":"NOASSERTION","size":932} {"code":"from algopy import logicsig\n\n\n@logicsig(name=\"always_allow\")\ndef some_sig() -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/logic_signature\/always_allow.py","language":"Python","license":"NOASSERTION","size":101} {"code":"from algopy import Account, Asset, TemplateVar, UInt64, gtxn, logicsig, subroutine\nfrom algopy.op import Global\n\n\n@logicsig\ndef pre_approved_sale() -> bool:\n \"\"\"\n Allows for pre-authorising the sale of an asset for a pre-determined price, but to an\n undetermined buyer.\n\n The checks here are not meant to be exhaustive\n \"\"\"\n pay_txn = gtxn.PaymentTransaction(0)\n asset_txn = gtxn.AssetTransferTransaction(1)\n assert_correct_payment(pay_txn)\n assert_correct_asset(asset_txn)\n assert pay_txn.sender == asset_txn.asset_receiver\n assert Global.group_size == 2\n return True\n\n\n@subroutine\ndef assert_correct_payment(txn: gtxn.PaymentTransaction) -> None:\n assert txn.receiver == TemplateVar[Account](\"SELLER\") and (\n txn.amount == TemplateVar[UInt64](\"PRICE\")\n )\n\n\n@subroutine\ndef assert_correct_asset(txn: gtxn.AssetTransferTransaction) -> None:\n assert (\n txn.asset_amount == 1\n and txn.sender == TemplateVar[Account](\"SELLER\")\n and txn.xfer_asset == TemplateVar[Asset](\"ASSET_ID\")\n and txn.asset_close_to == Global.zero_address\n and txn.rekey_to == Global.zero_address\n )\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/logic_signature\/signature.py","language":"Python","license":"NOASSERTION","size":1159} {"code":"# ruff: noqa: F403, F405\nfrom algopy import *\n\n\nclass LoopElseContract(Contract):\n def approval_program(self) -> bool:\n test_empty_loop(UInt64(0))\n\n arg_idx = UInt64(0)\n while arg_idx < Txn.num_app_args:\n for i in urange(10):\n if i == 0:\n break\n assert False, \"unreachable\"\n if Txn.application_args(arg_idx) == b\"while_secret\":\n secret_index = arg_idx\n for account_index in urange(Txn.num_accounts):\n account = Txn.accounts(account_index)\n if account == Global.zero_address:\n break\n else:\n assert False, \"access denied, missing secret account\"\n break\n arg_idx += 1\n else:\n assert False, \"access denied, missing secret argument\"\n log(\n \"found secret argument at idx=\",\n op.itob(secret_index + 48)[-1],\n \" and secret account at idx=\",\n op.itob(account_index + 48)[-1],\n )\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n\n@subroutine\ndef test_empty_loop(count: UInt64) -> None:\n assert count == 0\n result = UInt64(0)\n for i in reversed(urange(count)):\n if i == 0:\n break\n else:\n result += 1\n assert result == 1\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/loop_else\/loop_else.py","language":"Python","license":"NOASSERTION","size":1407} {"code":"import algopy\n\n\nclass MyContract(algopy.Contract):\n def approval_program(self) -> bool:\n self.case_one = algopy.UInt64(1)\n self.case_two = algopy.UInt64(2)\n self.match_uint64()\n self.match_biguint()\n self.match_bytes()\n self.match_address()\n self.match_attributes()\n self.match_bools()\n return True\n\n @algopy.subroutine\n def match_uint64(self) -> None:\n n = algopy.op.Txn.num_app_args\n match n:\n case 0:\n hello = algopy.Bytes(b\"Hello\")\n algopy.log(hello)\n case algopy.UInt64(10):\n hello = algopy.Bytes(b\"Hello There\")\n algopy.log(hello)\n\n @algopy.subroutine\n def match_bytes(self) -> None:\n n = algopy.op.Txn.application_args(0)\n match n:\n case algopy.Bytes(b\"\"):\n hello = algopy.Bytes(b\"Hello bytes\")\n algopy.log(hello)\n case algopy.Bytes(b\"10\"):\n hello = algopy.Bytes(b\"Hello There bytes\")\n algopy.log(hello)\n\n @algopy.subroutine\n def match_biguint(self) -> None:\n n = algopy.op.Txn.num_app_args * algopy.BigUInt(10)\n match n:\n case algopy.BigUInt(0):\n hello = algopy.Bytes(b\"Hello biguint\")\n algopy.log(hello)\n case algopy.BigUInt(10):\n hello = algopy.Bytes(b\"Hello There biguint\")\n algopy.log(hello)\n\n @algopy.subroutine\n def match_address(self) -> None:\n n = algopy.op.Txn.sender\n match n:\n case algopy.Account(\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ\"):\n hello = algopy.Bytes(b\"Hello address\")\n algopy.log(hello)\n case algopy.Account(\"VCMJKWOY5P5P7SKMZFFOCEROPJCZOTIJMNIYNUCKH7LRO45JMJP6UYBIJA\"):\n hello = algopy.Bytes(b\"Hello There address\")\n algopy.log(hello)\n\n @algopy.subroutine\n def match_attributes(self) -> None:\n n = algopy.op.Txn.num_app_args\n match n:\n case self.case_one:\n hello = algopy.Bytes(b\"Hello one\")\n algopy.log(hello)\n case self.case_two:\n hello = algopy.Bytes(b\"Hello two\")\n algopy.log(hello)\n case _:\n hello = algopy.Bytes(b\"Hello default\")\n algopy.log(hello)\n\n @algopy.subroutine\n def match_bools(self) -> None:\n n = algopy.op.Txn.num_app_args > 0\n match n:\n case True:\n hello = algopy.Bytes(b\"Hello True\")\n algopy.log(hello)\n case False:\n hello = algopy.Bytes(b\"Hello False\")\n algopy.log(hello)\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/match\/contract.py","language":"Python","license":"NOASSERTION","size":2827} {"code":"import algopy\n\n\nclass Counter(algopy.Contract):\n def __init__(self) -> None:\n self.counter = algopy.UInt64(0)\n\n def approval_program(self) -> bool:\n match algopy.Txn.on_completion:\n case algopy.OnCompleteAction.NoOp:\n self.increment_counter()\n return True\n case _:\n # reject all OnCompletionAction's other than NoOp\n return False\n\n def clear_state_program(self) -> bool:\n return True\n\n @algopy.subroutine\n def increment_counter(self) -> None:\n self.counter += 1\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/match\/counter.py","language":"Python","license":"NOASSERTION","size":587} {"code":"","repo_name":"algorandfoundation\/puya","path":"test_cases\/module_consts\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"import typing as t\n\n__all__ = [\n \"BANNED\",\n]\n__all__ += [\n \"EXT_ZERO\",\n \"EXT_ONE\",\n]\n\nBANNED = HACKER = \"VCMJKWOY5P5P7SKMZFFOCEROPJCZOTIJMNIYNUCKH7LRO45JMJP6UYBIJA\"\nEXT_ZERO: t.Final = 0\nEXT_ONE = 1\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/module_consts\/constants.py","language":"Python","license":"NOASSERTION","size":208} {"code":"USE_CONSTANTS2 = \"USE_CONSTANTS2\"\nUNUSED_CONSTANT2 = \"UNUSED\"\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/module_consts\/constants2.py","language":"Python","license":"NOASSERTION","size":62} {"code":"__all__ = [\n \"USED_CONSTANTS3\",\n]\n\n\nUSED_CONSTANTS3 = \"USED_CONSTANTS3\"\nUNUSED_CONSTANT3 = \"UNUSED\"\nUSED_UNLISTED_CONSTANT3 = \"USED_UNLISTED_CONSTANT3\"\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/module_consts\/constants3.py","language":"Python","license":"NOASSERTION","size":155} {"code":"from test_cases.module_consts import constants3 as constants3 # noqa: PLC0414\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/module_consts\/constants4.py","language":"Python","license":"NOASSERTION","size":79} {"code":"# ruff: noqa: T201, F403, F405, PLR0133\n\nimport typing\n\nfrom algopy import Contract, Txn\n\nimport test_cases.module_consts.constants as consts\nfrom test_cases.module_consts import constants, constants4\nfrom test_cases.module_consts.constants import BANNED, EXT_ONE, EXT_ZERO\nfrom test_cases.module_consts.constants2 import *\nfrom test_cases.module_consts.constants3 import *\n\nT = True and (1 == 1)\n\n\nif typing.TYPE_CHECKING:\n TruthyType = bool | typing.Literal[0, 1]\n _T = typing.TypeVar(\"_T\")\n\n def identity(x: _T) -> _T:\n return x\n\nelif False:\n print(\"HOW DO I GET HERE\")\nelif 0 > 1:\n print(\"please sir can I have some more consistency\")\nelse:\n SNEAKY_CONST = \"so sneak\"\n\n\nNO = b'\"no'\nNOO = b\"no'\"\nZERO = ZER0 = 0 # lol\nZEROS = f\"{ZERO:.3f}\"\nONE = ZERO + (ZER0 * 2) + (2 - 1) \/\/ EXT_ONE\nYES = \"y\" + \"es\"\nAAAAAAAAAA = EXT_ZERO or \"a\" * 48\nMAYBE = f\"\"\"{YES}\n or\n nooo\n\"\"\"\nBANNED_F = f\"{BANNED!r}\"\nBANNED_F2 = f\"{BANNED:2s}\"\nF_CODE = f\"{'lol' if EXT_ONE else 'no'}\"\nMAYBE1 = f\"{MAYBE}\"\nMAYBE2 = f'{MAYBE}\"'\nMAYBE3 = f\"\"\"{MAYBE}\"\"\"\nMAYBE4 = f'''{MAYBE}\"'''\nMAYBE6 = rf\"{MAYBE}\"\nMAYBE8 = rf'{MAYBE}\"'\n# fmt: off\nMAYBE5 = fr\"{MAYBE}\"\nMAYBE7 = fr'{MAYBE}\"'\n# fmt: on\nMAYBE_MORE = f\"{MAYBE} \\\n maybe not\"\nTWO = consts.EXT_ONE + constants.EXT_ONE + consts.EXT_ZERO\nEXT_NAME_REF_F_STR = f\"{consts.BANNED}\"\nYES_TWICE_AND_NO = 2 * f\"2{YES}\" + f\"1{NO!r}\"\nSHOULD_BE_1 = EXT_ONE if not typing.TYPE_CHECKING else EXT_ZERO\nSHOULD_BE_0 = EXT_ONE if False else EXT_ZERO\n\nSTAR1 = USE_CONSTANTS2\nSTAR2 = USED_CONSTANTS3\n# STAR3: str = USED_UNLISTED_CONSTANT3 # type: ignore[name-defined]\nFOOOO = constants4.constants3.USED_CONSTANTS3\n\nJOINED = \", \".join([\"1\", ZEROS])\n\n\nyes_votes = 42_572_654\nno_votes = 43_132_495\npercentage = (100 * yes_votes) \/\/ (yes_votes + no_votes)\nFORMATTED = f\"{yes_votes:-9} YES votes {percentage:2.2%}\"\n\n\nclass MyContract(Contract):\n def approval_program(self) -> bool:\n assert Txn.num_app_args == 0, MAYBE_MORE\n assert Txn.sender != consts.HACKER, consts.HACKER\n return True\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/module_consts\/contract.py","language":"Python","license":"NOASSERTION","size":2109} {"code":"","repo_name":"algorandfoundation\/puya","path":"test_cases\/mylib\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"from algopy import Bytes, UInt64, op, subroutine, urange\n\nONE = 1\nHELLO = \"\ud83d\udc4b\".encode()\n\n\n@subroutine\ndef three() -> UInt64:\n a = UInt64(1) + ONE\n b = a + 1\n return b\n\n\n@subroutine\ndef hello_world() -> Bytes:\n hello = Bytes(HELLO)\n comma = Bytes.from_base64(\"4aCI\")\n world = Bytes(b\" world\")\n return hello + comma + world\n\n\n@subroutine\ndef safe_add(x: UInt64, y: UInt64) -> tuple[UInt64, bool]:\n \"\"\"Add two UInt64 and return the result as well as whether it overflowed or not\"\"\"\n hi, lo = op.addw(x, y)\n did_overflow = hi > 0\n return lo, did_overflow\n\n\n@subroutine\ndef safe_six() -> tuple[UInt64, bool]:\n \"\"\"lollll\"\"\"\n return safe_add(three(), three())\n\n\n@subroutine\ndef itoa(i: UInt64) -> Bytes:\n \"\"\"Itoa converts an integer to the ascii byte string it represents\"\"\"\n digits = Bytes(b\"0123456789\")\n radix = digits.length\n if i < radix:\n return digits[i]\n return itoa(i \/\/ radix) + digits[i % radix]\n\n\n@subroutine\ndef itoa_loop(num: UInt64) -> Bytes:\n \"\"\"Itoa converts an integer to the ascii byte string it represents\"\"\"\n digits = Bytes(b\"0123456789\")\n result = Bytes(b\"\")\n while num >= 10:\n result = digits[num % 10] + result\n num \/\/= 10\n result = digits[num] + result\n return result\n\n\n@subroutine\ndef inefficient_multiply(a: UInt64, b: UInt64) -> UInt64:\n if a == 0 or b == 0:\n return a\n if a < b:\n smaller = a\n bigger = b\n else:\n smaller = b\n bigger = a\n result = UInt64(0)\n for _i in urange(smaller):\n result += bigger\n return result\n\n\n@subroutine\ndef test_and_uint64() -> UInt64:\n return UInt64(1) and UInt64(2)\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/mylib\/simple_functions.py","language":"Python","license":"NOASSERTION","size":1676} {"code":"import typing\n\nfrom algopy import BigUInt, Bytes, String, Txn, UInt64, arc4, subroutine\n\n\nclass TestTuple(typing.NamedTuple):\n \"\"\"This is a test tuple\"\"\"\n\n a: UInt64\n b: BigUInt\n c: String\n d: Bytes\n\n\nclass NamedTuplesContract(arc4.ARC4Contract):\n @arc4.abimethod()\n def build_tuple(self, a: UInt64, b: BigUInt, c: String, d: Bytes) -> TestTuple:\n t1 = self.build_tuple_by_name(a, b, c, d)\n t2 = self.build_tuple_by_position(a, b, c, d)\n assert t1 == t2\n return t1\n\n @subroutine\n def build_tuple_by_name(self, a: UInt64, b: BigUInt, c: String, d: Bytes) -> TestTuple:\n return TestTuple(a=a, b=b, c=c, d=d)\n\n @subroutine\n def build_tuple_by_position(self, a: UInt64, b: BigUInt, c: String, d: Bytes) -> TestTuple:\n return TestTuple(a, b, c, d)\n\n @arc4.abimethod()\n def test_tuple(self, value: TestTuple) -> None:\n assert value.a < 1000\n assert value.b < 2**65\n assert value.c.bytes.length > 1\n assert value.d == Txn.sender.bytes\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/named_tuples\/contract.py","language":"Python","license":"NOASSERTION","size":1037} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\nclass TestTuple(algopy.arc4.Struct):\n a: algopy.arc4.UIntN[typing.Literal[64]]\n b: algopy.arc4.BigUIntN[typing.Literal[512]]\n c: algopy.arc4.String\n d: algopy.arc4.DynamicBytes\n\nclass NamedTuplesContract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def build_tuple(\n self,\n a: algopy.arc4.UIntN[typing.Literal[64]],\n b: algopy.arc4.BigUIntN[typing.Literal[512]],\n c: algopy.arc4.String,\n d: algopy.arc4.DynamicBytes,\n ) -> TestTuple: ...\n\n @algopy.arc4.abimethod\n def test_tuple(\n self,\n value: TestTuple,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/named_tuples\/out\/client_NamedTuplesContract.py","language":"Python","license":"NOASSERTION","size":724} {"code":"from algopy import Contract, UInt64, log, op, uenumerate, urange\n\nLOOP_ITERATIONS = 2 # max op code budget is exceeded with more\n\n\nclass Nested(Contract):\n def approval_program(self) -> UInt64:\n n = UInt64(LOOP_ITERATIONS)\n x = UInt64(0)\n\n for a in urange(n):\n for b in urange(n):\n for c in urange(n):\n for d in urange(n):\n for e in urange(n):\n for f in urange(n):\n x += a + b + c + d + e + f\n # Iterator variable should be mutable, but mutating it\n # should not affect the next iteration\n a += n\n\n log(op.itob(x))\n\n y = UInt64(0)\n for index, item in uenumerate(urange(UInt64(10))):\n y += item * index\n\n log(op.itob(y))\n return x\n\n def clear_state_program(self) -> UInt64:\n return UInt64(1)\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/nested_loops\/contract.py","language":"Python","license":"NOASSERTION","size":931} {"code":"from algopy import ARC4Contract, Txn\nfrom algopy.arc4 import Bool, DynamicArray, String, Tuple, UInt256, abimethod\n\n\nclass Issue118(ARC4Contract):\n # ref: https:\/\/github.com\/algorandfoundation\/puya\/issues\/118\n @abimethod\n def verify(self, values: DynamicArray[UInt256]) -> Tuple[Bool, String]:\n val1 = Bool(\n bool(Txn.num_app_args)\n ) # use a non constant value so the repeated expression is not simplified\n if values.length != 2:\n return Tuple((val1, String(\"\")))\n return Tuple((val1, String(\"\")))\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/regression_tests\/issue_118.py","language":"Python","license":"NOASSERTION","size":559} {"code":"from algopy import Contract, UInt64\n\n\nclass Issue194(Contract):\n # ref: https:\/\/github.com\/algorandfoundation\/puya\/issues\/194\n def approval_program(self) -> bool:\n assert bool(UInt64(1)) == bool(UInt64(2))\n two = UInt64(2)\n match bool(two):\n case True:\n return True\n case _:\n return False\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/regression_tests\/issue_194.py","language":"Python","license":"NOASSERTION","size":432} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass Issue118(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def verify(\n self,\n values: algopy.arc4.DynamicArray[algopy.arc4.BigUIntN[typing.Literal[256]]],\n ) -> algopy.arc4.Tuple[algopy.arc4.Bool, algopy.arc4.String]: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/regression_tests\/out\/client_Issue118.py","language":"Python","license":"NOASSERTION","size":371} {"code":"import algopy as a\n\n\nclass TealSwitchInlining(a.Contract):\n \"\"\"Test for an issue introduced by TEAL block optimizations,\n whereby a target that is referenced multiple times by the same source block\n might be incorrectly inlined, when it should remain a labelled destination.\n \"\"\"\n\n def approval_program(self) -> bool:\n match a.Txn.num_app_args:\n # at -O2, this block and the default block will be de-duplicated,\n # resulting in there being a reference to the default block in the `switch` cases\n # also, which cannot be inlined an must be preserved despite only having a single\n # predecessor block\n case 0:\n return True\n case 1:\n return False\n case _:\n return True\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/regression_tests\/teal_switch_inlining.py","language":"Python","license":"NOASSERTION","size":874} {"code":"from algopy import ARC4Contract, BigUInt, Bytes, arc4, subroutine\n\n\nclass Contract(ARC4Contract):\n @arc4.abimethod()\n def bytes_to_bool(self) -> bool:\n return bool(Bytes())\n\n @arc4.abimethod()\n def test_bytes_to_biguint(self) -> None:\n assert bytes_to_biguint()\n\n\n@subroutine\ndef bytes_to_biguint() -> BigUInt:\n return BigUInt.from_bytes(Bytes())\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/reinterpret_cast\/contract.py","language":"Python","license":"NOASSERTION","size":376} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass Contract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def bytes_to_bool(\n self,\n ) -> algopy.arc4.Bool: ...\n\n @algopy.arc4.abimethod\n def test_bytes_to_biguint(\n self,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/reinterpret_cast\/out\/client_Contract.py","language":"Python","license":"NOASSERTION","size":346} {"code":"from algopy import Bytes, Contract, Txn, UInt64, op, urange\n\nTWO = 2\nTWENTY = 20\n\n\nclass MyContract(Contract, scratch_slots=(1, TWO, urange(3, TWENTY))):\n def approval_program(self) -> bool:\n op.Scratch.store(UInt64(1), 5 if Txn.application_id == 0 else 0)\n\n hello_world = Bytes(b\"Hello World\")\n op.Scratch.store(TWO, hello_world)\n\n for i in urange(3, 20):\n op.Scratch.store(i, i)\n\n assert op.Scratch.load_uint64(1) == UInt64(5)\n\n assert op.Scratch.load_bytes(2) == b\"Hello World\"\n\n assert op.Scratch.load_uint64(5) == UInt64(5)\n\n op.Scratch.store(TWENTY - 1, b\"last\")\n assert op.Scratch.load_bytes(TWENTY - 1) == b\"last\"\n return True\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/scratch_slots\/contract.py","language":"Python","license":"NOASSERTION","size":783} {"code":"import typing\n\nimport algopy\nfrom algopy import Bytes, UInt64, op, subroutine, urange\n\nfrom test_cases.scratch_slots.contract import MyContract\n\nRenamedURange: typing.TypeAlias = urange\n\n\nclass MyContract2(\n MyContract,\n scratch_slots=[5, 25, urange(50, 53, 2), RenamedURange(100, 105), algopy.urange(110, 115)],\n):\n @subroutine\n def my_sub(self) -> None:\n op.Scratch.store(UInt64(1), Bytes(b\"abc\"))\n\n op.Scratch.store(52, Bytes(b\"52\"))\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/scratch_slots\/contract2.py","language":"Python","license":"NOASSERTION","size":463} {"code":"from algopy import Contract, urange\n\n\nclass MyOtherContract(Contract, scratch_slots=urange(0, -1, -1)):\n def approval_program(self) -> bool:\n return True\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/scratch_slots\/contract3.py","language":"Python","license":"NOASSERTION","size":228} {"code":"","repo_name":"algorandfoundation\/puya","path":"test_cases\/simple\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"import algopy as algo\n\nfrom test_cases.simple import pkg_a, subs\n\n\nclass MyContract(algo.Contract):\n \"\"\"My contract\"\"\"\n\n def approval_program(self) -> algo.UInt64:\n a = algo.UInt64(1) + 2\n b = algo.UInt64(4) * 5\n if a == (1 + 2) * (4 - 3):\n if b < 2:\n b = 3 + algo.UInt64(2)\n return a + b\n else:\n b = 2 * a\n if ((3 * 4) + 2) * b:\n return algo.UInt64(2)\n else:\n return algo.UInt64(3)\n else:\n return pkg_a.MyUInt64(4)\n\n def clear_state_program(self) -> algo.UInt64:\n assert pkg_a.Txn2.num_app_args == 0\n return subs.zero() * pkg_a.pkg_1.subs.one()\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/simple\/contract.py","language":"Python","license":"NOASSERTION","size":743} {"code":"from algopy import UInt64 as MyUInt64\nfrom algopy.op import Txn\n\nfrom . import pkg_1\n\n__all__ = [\n \"MyUInt64\",\n \"pkg_1\",\n \"Txn2\",\n]\n\nTxn2 = Txn\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/simple\/pkg_a\/__init__.py","language":"Python","license":"NOASSERTION","size":153} {"code":"from . import subs # noqa: F401\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/simple\/pkg_a\/pkg_1\/__init__.py","language":"Python","license":"NOASSERTION","size":33} {"code":"import algopy\n\n\n@algopy.subroutine\ndef one() -> algopy.UInt64:\n return algopy.UInt64(1)\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/simple\/pkg_a\/pkg_1\/subs.py","language":"Python","license":"NOASSERTION","size":91} {"code":"import algopy\n\n\n@algopy.subroutine\ndef zero() -> algopy.UInt64:\n return algopy.UInt64(0)\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/simple\/subs.py","language":"Python","license":"NOASSERTION","size":92} {"code":"","repo_name":"algorandfoundation\/puya","path":"test_cases\/simplish\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"import abc\n\nfrom algopy import Bytes, Contract, LocalState, UInt64, subroutine\n\n\nclass CallCounter(Contract, abc.ABC):\n def __init__(self) -> None:\n self.counter = UInt64(0)\n self.name = LocalState(Bytes)\n\n @subroutine\n def increment_counter(self) -> None:\n self.counter += 1\n\n @subroutine\n def set_sender_nickname(self, nickname: Bytes) -> None:\n self.name[0] = nickname\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/simplish\/base_class.py","language":"Python","license":"NOASSERTION","size":415} {"code":"from algopy import (\n Bytes,\n OnCompleteAction,\n UInt64,\n log,\n subroutine,\n)\nfrom algopy.op import (\n AppGlobal,\n AssetHoldingGet,\n Base64,\n Global,\n Txn,\n base64_decode,\n btoi,\n divmodw,\n gload_bytes,\n setbit_bytes,\n setbit_uint64,\n)\n\nfrom test_cases.simplish.base_class import CallCounter\n\nSCALE = 100000\n# SCALED_PI = int(3.14159 * SCALE) # hmmmm\nSCALED_PI = 314159\n\n\nclass Simplish(CallCounter):\n def approval_program(self) -> bool:\n if Txn.application_id == 0:\n return True\n oca = Txn.on_completion\n sender = Txn.sender\n if oca in (\n OnCompleteAction.UpdateApplication,\n OnCompleteAction.DeleteApplication,\n ):\n if oca == OnCompleteAction.DeleteApplication:\n log(Bytes(b\"I was used \") + itoa(self.counter) + b\" time(s) before I died\")\n return Global.creator_address == sender\n\n if oca == OnCompleteAction.OptIn:\n if Txn.num_app_args > 0:\n self.set_sender_nickname(Txn.application_args(0))\n return True\n if oca != OnCompleteAction.NoOp:\n return False\n\n if (num_app_args := Txn.num_app_args) > 0:\n method_name = Txn.application_args(0)\n msg, result = self.call(method_name, num_app_args)\n elif Txn.num_assets == 1:\n asset_balance, asset_exists = AssetHoldingGet.asset_balance(sender, 0)\n if not asset_exists:\n msg = Bytes(b\"You do not have any of the asset\")\n else:\n msg = Bytes(b\"You have asset balance: \") + itoa(asset_balance)\n result = True\n else:\n msg = Bytes(b\"not enough app args or foreign assets\")\n result = False\n log(msg)\n self.increment_counter()\n return result\n\n def clear_state_program(self) -> bool:\n return True\n\n @subroutine\n def call(self, method_name: Bytes, num_app_args: UInt64) -> tuple[Bytes, bool]:\n assert num_app_args == 2, \"insufficient arguments\"\n radius = btoi(Txn.application_args(1))\n\n status = True\n if method_name == b\"circle_area\":\n area = circle_area(radius)\n result = itoa(area)\n elif method_name == b\"circle_circumference\":\n circumference = circle_circumference(radius)\n result = itoa(circumference)\n elif method_name == b\"circle_report\":\n area, circumference = circle_area(radius), circle_circumference(radius)\n result = (\n Bytes(b\"Approximate area and circumference of circle with radius \")\n + itoa(radius)\n + b\" = \"\n + itoa(area)\n + b\", \"\n + itoa(circumference)\n )\n else:\n status = False\n result = Bytes(b\"unknown method name\")\n return result, status\n\n @subroutine\n def increment_counter(self) -> None:\n log(\"Incrementing counter!\")\n super().increment_counter()\n\n\n@subroutine\ndef circle_circumference(radius: UInt64) -> UInt64:\n # PI * 2r\n two_pi = UInt64(2) * SCALED_PI\n return radius * two_pi \/\/ SCALE\n\n\n@subroutine\ndef circle_area(radius: UInt64) -> UInt64:\n # PI * r ^ 2\n result = radius**2 * SCALED_PI \/\/ SCALE\n return result\n\n\n@subroutine\ndef itoa(i: UInt64) -> Bytes:\n \"\"\"Itoa converts an integer to the ascii byte string it represents\"\"\"\n digits = Bytes(b\"0123456789\")\n radix = digits.length\n if i < radix:\n return digits[i]\n return itoa(i \/\/ radix) + digits[i % radix]\n\n\n@subroutine\ndef test_intrinsics() -> UInt64:\n _ii = gload_bytes(1, 1)\n _si = gload_bytes(UInt64(2), 2)\n _ss = gload_bytes(UInt64(3), UInt64(3))\n _is = gload_bytes(4, UInt64(4))\n _foo_uint: UInt64 = setbit_uint64(UInt64(32), 0, 3)\n _foo_int = setbit_uint64(32, 0, 3)\n _foo_bytes: Bytes = setbit_bytes(Bytes(b\"32\"), 0, 3)\n test = AppGlobal.get_bytes(b\"foo\")\n AppGlobal.put(b\"b\", b\"yeah\")\n AppGlobal.delete(b\"foo\")\n _expect_bytes: Bytes = test\n _abcd = divmodw(1, 2, 3, 4)\n _hello_str = base64_decode(Base64.StdEncoding, Bytes(b\"SGVsbG8=\"))\n return UInt64(0)\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/simplish\/contract.py","language":"Python","license":"NOASSERTION","size":4222} {"code":"","repo_name":"algorandfoundation\/puya","path":"test_cases\/ssa\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"from algopy import Contract, UInt64, log, op, subroutine, urange\n\n\nclass MyContract(Contract):\n \"\"\"My contract\"\"\"\n\n def approval_program(self) -> UInt64:\n a = UInt64(1) + 2\n b = UInt64(4) * 5\n\n a = a * b\n b = a + b\n\n while a < UInt64(5):\n b = b + a\n a = a + 1\n\n for i in urange(5):\n b = b + a\n a = a + i\n\n if a < b:\n if b < 2:\n b = 3 + UInt64(2)\n c = a + b\n else:\n b = 2 * a\n if ((3 * 4) + 2) * b:\n c = UInt64(2)\n else:\n return UInt64(3)\n elif b == a:\n c = a * b\n else:\n c = a - b\n c = c + one_hundred(c)\n c_bytes = op.itob(c)\n log(c_bytes)\n assert phi_in_equiv_class(UInt64(3), True) == 4\n assert phi_in_equiv_class(UInt64(3), False) == 4\n return c\n\n def clear_state_program(self) -> UInt64:\n return one_hundred(UInt64(40))\n\n\n@subroutine\ndef one_hundred(c: UInt64) -> UInt64:\n a = UInt64(25)\n b = UInt64(2)\n if a < c:\n b = UInt64(1)\n a = UInt64(100)\n\n b *= b\n return a * b\n\n\n@subroutine\ndef phi_in_equiv_class(y: UInt64, b: bool) -> UInt64:\n if b:\n tmp1 = y\n x = tmp1\n else:\n tmp2 = y\n x = tmp2\n x += 1\n return x\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/ssa\/contract.py","language":"Python","license":"NOASSERTION","size":1405} {"code":"","repo_name":"algorandfoundation\/puya","path":"test_cases\/ssa2\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"from algopy import Contract, UInt64, subroutine, urange\n\n\nclass MyContract(Contract):\n \"\"\"My contract\"\"\"\n\n def approval_program(self) -> UInt64:\n a = UInt64(1) + 2\n b = UInt64(4) * 5\n\n # while a < UInt64(5):\n # b = b + a\n # a = a + 1\n\n for i in urange(5):\n b = b + a\n a = a + i\n return a + b\n\n # if a < b:\n # if b < 2:\n # b = 3 + UInt64(2)\n # c = a + b\n # else:\n # b = 2 * a\n # if ((3 * 4) + 2) * b:\n # c = UInt64(2)\n # else:\n # return UInt64(3)\n # elif b == a:\n # c = a * b\n # else:\n # c = a - b\n # c = c + one_hundred(c)\n # return c\n\n def clear_state_program(self) -> UInt64:\n return one_hundred(UInt64(40))\n\n\n@subroutine\ndef one_hundred(c: UInt64) -> UInt64:\n a = UInt64(25)\n b = UInt64(2)\n if a < c:\n b = UInt64(1)\n a = UInt64(100)\n\n b *= b\n return a * b\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/ssa2\/contract.py","language":"Python","license":"NOASSERTION","size":1075} {"code":"from algopy import (\n Account,\n ARC4Contract,\n Box,\n BoxMap,\n GlobalState,\n LocalState,\n Txn,\n arc4,\n subroutine,\n)\n\n\nclass MyStruct(arc4.Struct):\n bar: arc4.UInt64\n baz: arc4.String\n\n\nMyArray = arc4.DynamicArray[MyStruct]\n\n\nclass Contract(ARC4Contract):\n def __init__(self) -> None:\n self.glob = GlobalState(MyArray)\n self.loc = LocalState(MyArray)\n self.box = Box(MyArray)\n self.map = BoxMap(Account, MyArray)\n\n @arc4.baremethod(allow_actions=[\"OptIn\"])\n def opt_in(self) -> None:\n self.glob.value = MyArray()\n self.box.value = MyArray()\n self.loc[Txn.sender] = MyArray()\n self.map[Txn.sender] = MyArray()\n\n @arc4.abimethod\n def append(self) -> None:\n struct = get_struct()\n self.glob.value.append(struct.copy())\n self.loc[Txn.sender].append(struct.copy())\n self.box.value.append(struct.copy())\n self.map[Txn.sender].append(struct.copy())\n\n @arc4.abimethod\n def modify(self) -> None:\n self.glob.value[0].baz = arc4.String(\"modified\")\n self.loc[Txn.sender][0].baz = arc4.String(\"modified\")\n self.box.value[0].baz = arc4.String(\"modified\")\n self.map[Txn.sender][0].baz = arc4.String(\"modified\")\n\n @arc4.abimethod\n def get(self) -> MyArray:\n a1 = self.glob.value.copy()\n a2 = self.loc[Txn.sender].copy()\n a3 = self.box.value.copy()\n a4 = self.map[Txn.sender].copy()\n\n assert a1 == a2, \"expected local == global\"\n assert a1 == a3, \"expected box == global\"\n assert a1 == a4, \"expected map == global\"\n return a1\n\n\n@subroutine\ndef get_struct() -> MyStruct:\n return MyStruct(\n bar=arc4.UInt64(1),\n baz=arc4.String(\"baz\"),\n )\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/state_mutations\/contract.py","language":"Python","license":"NOASSERTION","size":1774} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass Contract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def append(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def modify(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def get(\n self,\n ) -> algopy.arc4.DynamicArray[algopy.arc4.Tuple[algopy.arc4.UIntN[typing.Literal[64]], algopy.arc4.String]]: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/state_mutations\/out\/client_Contract.py","language":"Python","license":"NOASSERTION","size":484} {"code":"from algopy import (\n ARC4Contract,\n GlobalState,\n LocalState,\n StateTotals,\n Txn,\n UInt64,\n arc4,\n)\n\n\nclass StateProxyContract(ARC4Contract, state_totals=StateTotals(global_uints=3)):\n def __init__(self) -> None:\n self.local1 = LocalState(UInt64, key=\"l1\", description=\"l1 description\")\n self.local2 = LocalState[UInt64](UInt64, key=b\"l2\", description=\"l2 description\")\n self.global1 = GlobalState(UInt64, key=\"g1\", description=\"g1 description\")\n self.global2 = GlobalState[UInt64](UInt64(0), key=b\"g2\", description=\"g2 description\")\n funky_town = (\n GlobalState(UInt64, key=\"funky\")\n if Txn.num_app_args\n else GlobalState(UInt64, key=\"town\")\n )\n funky_town.value = UInt64(123)\n\n @arc4.abimethod(allow_actions=[\"OptIn\"], create=\"require\")\n def create(self) -> None:\n self.global1.value = UInt64(1)\n self.local1[Txn.sender] = UInt64(2)\n self.local2[Txn.sender] = UInt64(3)\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/state_proxies\/contract.py","language":"Python","license":"NOASSERTION","size":1006} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass StateProxyContract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod(allow_actions=['OptIn'], create='require')\n def create(\n self,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/state_proxies\/out\/client_StateProxyContract.py","language":"Python","license":"NOASSERTION","size":288} {"code":"from algopy import Bytes, GlobalState, LocalState, StateTotals, UInt64, arc4\n\nGLOBAL_UINTS = 3\n\n\nclass Contract(\n arc4.ARC4Contract,\n state_totals=StateTotals(local_bytes=1, global_uints=GLOBAL_UINTS),\n):\n def __init__(self) -> None:\n self.local_one = LocalState(UInt64)\n self.global_one = GlobalState(Bytes)\n\n @arc4.baremethod(create=\"require\")\n def create(self) -> None:\n pass\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/state_totals\/contract.py","language":"Python","license":"NOASSERTION","size":415} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass Contract(algopy.arc4.ARC4Client, typing.Protocol):\n pass\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/state_totals\/out\/client_Contract.py","language":"Python","license":"NOASSERTION","size":168} {"code":"from algopy import Contract, UInt64, subroutine\n\n\nclass BruteForceRotationSearch(Contract):\n def approval_program(self) -> bool:\n (\n a,\n b,\n c,\n d,\n e,\n f,\n g,\n h,\n i,\n j,\n k,\n l, # noqa: E741\n m,\n n,\n ) = do_some_ops(UInt64(0), UInt64(0))\n\n assert a == 0\n assert b == 1\n assert c == 2\n assert d == 3\n assert e == 4\n assert f == 5\n assert g == 6\n assert h == 7\n assert i == 8\n assert j == 9\n assert k == 10\n assert l == 11\n assert m == 12\n assert n == 13\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n\n@subroutine\ndef do_some_ops(\n a: UInt64, b: UInt64\n) -> tuple[\n UInt64,\n UInt64,\n UInt64,\n UInt64,\n UInt64,\n UInt64,\n UInt64,\n UInt64,\n UInt64,\n UInt64,\n UInt64,\n UInt64,\n UInt64,\n UInt64,\n]:\n c = a + b\n return (\n c,\n c + 1,\n c + 2,\n c + 3,\n c + 4,\n c + 5,\n c + 6,\n c + 7,\n c + 8,\n c + 9,\n c + 10,\n c + 11,\n c + 12,\n c + 13,\n )\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/stress_tests\/brute_force_rotation_search.py","language":"Python","license":"NOASSERTION","size":1291} {"code":"from algopy import Bytes, Contract\n\n\nclass MyContract(Contract):\n def approval_program(self) -> bool:\n assert Bytes(b\"brown fox\") in Bytes(b\"The quick brown fox jumped over the lazy dog\")\n assert b\"brown fox\" in Bytes(b\"The quick brown fox jumped over the lazy dog\")\n assert Bytes(b\"red fox\") not in Bytes(b\"The quick brown fox jumped over the lazy dog\")\n assert b\"red fox\" not in Bytes(b\"The quick brown fox jumped over the lazy dog\")\n\n return True\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/string_ops\/contract.py","language":"Python","license":"NOASSERTION","size":552} {"code":"import typing\n\nfrom algopy import ARC4Contract, arc4\n\nfrom test_cases.struct_by_name.mod import StructTwo as StructThree\n\n\nclass StructOne(typing.NamedTuple):\n x: arc4.UInt8\n y: arc4.UInt8\n\n\nclass StructTwo(typing.NamedTuple):\n x: arc4.UInt8\n y: arc4.UInt8\n\n\nclass DemoContract(ARC4Contract):\n \"\"\"\n Verify that even though named tuples with different names but the same structure should be\n considered 'comparable' in the type system, they should be output separately when being\n interpreted as an arc4 Struct in an abi method\n \"\"\"\n\n @arc4.abimethod()\n def get_one(self) -> StructOne:\n return StructOne(\n x=arc4.UInt8(1),\n y=arc4.UInt8(1),\n )\n\n @arc4.abimethod()\n def get_two(self) -> StructTwo:\n return StructTwo(\n x=arc4.UInt8(1),\n y=arc4.UInt8(1),\n )\n\n @arc4.abimethod()\n def get_three(self) -> StructThree:\n return StructThree(\n x=arc4.UInt8(1),\n y=arc4.UInt8(1),\n )\n\n @arc4.abimethod()\n def compare(self) -> bool:\n return self.get_one() == self.get_two() and self.get_two() == self.get_three()\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/struct_by_name\/contract.py","language":"Python","license":"NOASSERTION","size":1165} {"code":"import typing\n\nfrom algopy import arc4\n\n\nclass StructTwo(typing.NamedTuple):\n x: arc4.UInt8\n y: arc4.UInt8\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/struct_by_name\/mod.py","language":"Python","license":"NOASSERTION","size":113} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\nclass StructOne(algopy.arc4.Struct):\n x: algopy.arc4.UIntN[typing.Literal[8]]\n y: algopy.arc4.UIntN[typing.Literal[8]]\n\nclass StructTwo(algopy.arc4.Struct):\n x: algopy.arc4.UIntN[typing.Literal[8]]\n y: algopy.arc4.UIntN[typing.Literal[8]]\n\nclass test_cases_struct_by_name_mod_StructTwo(algopy.arc4.Struct):\n x: algopy.arc4.UIntN[typing.Literal[8]]\n y: algopy.arc4.UIntN[typing.Literal[8]]\n\nclass DemoContract(algopy.arc4.ARC4Client, typing.Protocol):\n \"\"\"\n\n Verify that even though named tuples with different names but the same structure should be\n considered 'comparable' in the type system, they should be output separately when being\n interpreted as an arc4 Struct in an abi method\n \n \"\"\"\n @algopy.arc4.abimethod\n def get_one(\n self,\n ) -> StructOne: ...\n\n @algopy.arc4.abimethod\n def get_two(\n self,\n ) -> StructTwo: ...\n\n @algopy.arc4.abimethod\n def get_three(\n self,\n ) -> test_cases_struct_by_name_mod_StructTwo: ...\n\n @algopy.arc4.abimethod\n def compare(\n self,\n ) -> algopy.arc4.Bool: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/struct_by_name\/out\/client_DemoContract.py","language":"Python","license":"NOASSERTION","size":1212} {"code":"from algopy import BigUInt, Contract, Txn, UInt64, op, subroutine\n\n\nclass BigUIntContract(Contract):\n def approval_program(self) -> bool:\n one = BigUInt(1)\n compare_biguints(one, BigUInt(2))\n compare_biguint_vs_uint64(one, UInt64(2))\n compare_uint64_vs_biguint(UInt64(1), BigUInt(2))\n assert BigUInt(1 if Txn.num_app_args else 5) == 5, \"constructor expressions supported\"\n assert op.bsqrt(BigUInt(9)) == op.bsqrt(10)\n assert one == +one\n return True\n\n def clear_state_program(self) -> bool:\n assert BigUInt() == 0\n return True\n\n\n@subroutine\ndef compare_biguints(one: BigUInt, two: BigUInt) -> None:\n assert one < two\n assert one <= two\n assert one == one # noqa: PLR0124\n assert two > one\n assert two >= one\n assert one != two\n\n\n@subroutine\ndef compare_biguint_vs_uint64(one: BigUInt, two: UInt64) -> None:\n assert one < two\n assert one <= two\n assert one == one # noqa: PLR0124\n assert two > one\n assert two >= one\n assert one != two\n\n\n@subroutine\ndef compare_uint64_vs_biguint(one: UInt64, two: BigUInt) -> None:\n assert one < two\n assert one <= two\n assert one == one # noqa: PLR0124\n assert two > one\n assert two >= one\n assert one != two\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/stubs\/biguint.py","language":"Python","license":"NOASSERTION","size":1276} {"code":"from algopy import Bytes, Contract, Txn, UInt64, log, subroutine\n\n\nclass BytesContract(Contract):\n def approval_program(self) -> UInt64:\n base_64 = Bytes.from_base64(\"QmFzZSA2NCBlbmNvZGVk\")\n assert base_64 == Bytes(b\"Base 64 encoded\")\n base_32 = Bytes.from_base32(\"IJQXGZJAGMZCAZLOMNXWIZLE\")\n assert base_32 == Bytes(b\"Base 32 encoded\")\n base_16 = Bytes.from_hex(\"4261736520313620656E636F646564\")\n assert base_16 == Bytes(b\"Base 16 encoded\")\n\n empty = Bytes(b\"\")\n assert base_64, \"Non empty bytes should be Truthy\"\n assert not empty, \"Empty bytes should be Falsy\"\n\n assert Bytes(b\"a\") + Bytes(b\"b\") == Bytes(b\"ab\")\n\n c = Bytes(b\"c\")\n c += b\"d\"\n assert c == Bytes(b\"cd\")\n\n abc = Bytes(b\"abc\")\n assert abc[0] == b\"a\"\n\n assert abc[1:] == b\"bc\"\n assert abc[1:1] == b\"\"\n assert abc[:1] == b\"a\"\n assert abc[:-1] == b\"ab\"\n assert abc[-2:] == b\"bc\"\n assert abc[-2:-1] == b\"b\"\n assert Bytes(b\"1234567\")[1:-1] == b\"23456\"\n assert abc[-10:10] == b\"abc\"\n\n true = Bytes(b\"1\")\n false = Bytes(b\"\")\n\n x = (true and true) == true\n assert x\n assert (true and true) == true\n assert (true and false) == false\n assert (false and true) == false\n assert (false and false) == false\n assert (true or true) == true\n assert (true or false) == true\n assert (false or true) == true\n assert (false or false) == false\n\n a, b, c, d = (\n Bytes.from_hex(\"00\"),\n Bytes.from_hex(\"0F\"),\n Bytes.from_hex(\"F0\"),\n Bytes.from_hex(\"FF\"),\n )\n\n assert a & b == a\n assert b | c == d\n assert b ^ d == c\n\n y = a\n y &= d\n assert y == a\n y |= d\n assert y == d\n y ^= c\n assert y == b\n\n check_slicing_with_uint64(abc)\n check_end_before_start_slicing(abc)\n\n assert (\n Bytes(b\"args\" if Txn.num_app_args else b\"no args\") == b\"no args\"\n ), \"constructor expressions supported\"\n\n return UInt64(1)\n\n def clear_state_program(self) -> bool:\n return True\n\n\n@subroutine\ndef check_slicing_with_uint64(abc: Bytes) -> None:\n one = UInt64(1)\n ten = UInt64(10)\n assert abc[one:] == b\"bc\"\n assert abc[one:one] == b\"\"\n assert abc[:one] == b\"a\"\n assert one_to_seven()[one:-1] == b\"23456\"\n assert abc[UInt64(0) : ten] == b\"abc\"\n\n\n@subroutine\ndef check_end_before_start_slicing(abc: Bytes) -> None:\n assert abc[10:1] == b\"\"\n assert abc[-10:-12] == b\"\"\n one = UInt64(1)\n ten = UInt64(10)\n assert abc[ten:one] == b\"\"\n\n\n@subroutine\ndef one_to_seven() -> Bytes:\n log(\"one_to_seven called\")\n return Bytes(b\"1234567\")\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/stubs\/bytes.py","language":"Python","license":"NOASSERTION","size":2814} {"code":"from algopy import Contract, String, Txn\n\n\nclass StringContract(Contract):\n def approval_program(self) -> bool:\n empty = String()\n assert not empty, \"Empty bytes should be False\"\n non_empty = String(\" \")\n assert non_empty, \"Non-empty bytes should be True\"\n\n assert String(\"a\") + \"b\" == \"ab\"\n assert String(\"a\") + \"b\" == String(\"ab\")\n assert \"a\" + String(\"b\") == String(\"ab\")\n\n assert empty != non_empty\n\n c = String(\"c\")\n c += \"d\"\n c += String(\"e\")\n assert c == \"cde\"\n\n assert \"brown fox\" in String(\"The quick brown fox jumped over the lazy dog\")\n assert String(\"red fox\") not in String(\"The quick brown fox jumped over the lazy dog\")\n\n alpha = String(\"abcdefg\")\n assert alpha.startswith(\"\")\n assert alpha.startswith(\"a\")\n assert alpha.startswith(\"ab\")\n assert not alpha.startswith(\"b\")\n assert alpha.startswith(alpha)\n assert not alpha.startswith(alpha + \"!\")\n\n assert alpha.endswith(\"\")\n assert alpha.endswith(\"g\")\n assert alpha.endswith(\"fg\")\n assert not alpha.endswith(\"f\")\n assert alpha.endswith(alpha)\n assert not alpha.endswith(\"!\" + alpha)\n\n d, e, f = String(\"d\"), String(\"e\"), String(\"f\")\n assert String(\".\").join((d, e, f)) == \"d.e.f\"\n assert String(\".\").join((d, \"e\", f)) == \"d.e.f\"\n assert String(\".\").join((\"d\", \"e\", \"f\")) == \"d.e.f\"\n assert String(\".\").join(tuple(\"def\")) == \"d.e.f\"\n assert String(\"\").join((d, e, f)) == \"def\"\n assert String(\".\").join((d,)) == \"d\"\n assert String(\"\").join((d,)) == \"d\"\n assert (\n String(\"args\" if Txn.num_app_args else \"no args\") == \"no args\"\n ), \"constructor expressions supported\"\n\n return True\n\n def clear_state_program(self) -> bool:\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/stubs\/string.py","language":"Python","license":"NOASSERTION","size":1888} {"code":"from algopy import Contract, Txn, UInt64, op\n\n\nclass Uint64Contract(Contract):\n def approval_program(self) -> UInt64:\n zero = UInt64(0)\n one = UInt64(1)\n two = UInt64(2)\n five = UInt64(5)\n three = UInt64(3)\n sixty = UInt64(60)\n\n assert one, \"Any non-zero number should be Truthy\"\n assert not zero, \"Zero should beFalsy\"\n\n assert one < five\n assert five > one\n assert one <= one # noqa: PLR0124\n assert five >= five # noqa: PLR0124\n\n assert one + five == 6\n\n c = five\n c += sixty\n assert c == 65\n\n assert sixty - five == 55\n c -= five\n assert c == 60\n\n assert sixty \/\/ five == 12\n c \/\/= five\n\n assert c == 12\n\n assert five * sixty == 300\n\n assert five**three == 125\n\n c **= 2\n\n assert c == 144\n\n assert one << two == 4\n c >>= 6\n assert c == 2\n c <<= 6\n assert c == 128\n assert five >> three == 0\n\n assert ~one == 0xFFFFFFFFFFFFFFFE\n\n true = UInt64(1)\n false = UInt64(0)\n assert (true and true) == true\n assert (true and false) == false\n assert (false and true) == false\n assert (false and false) == false\n assert (true or true) == true\n assert (true or false) == true\n assert (false or true) == true\n assert (false or false) == false\n\n assert one & five == one\n assert sixty | five == 61\n assert sixty ^ five == 57\n\n y = UInt64(0b11111110)\n y &= UInt64(0b00011111)\n assert y == 0b00011110\n y |= 0b00110110\n assert y == 0b00111110\n y ^= 0b11111111\n assert y == 0b11000001\n\n assert op.sqrt(UInt64(17)) == op.sqrt(16)\n\n assert one == +one\n\n assert UInt64(1 if Txn.num_app_args else 5) == 5, \"constructor expressions supported\"\n\n return UInt64(1)\n\n def clear_state_program(self) -> bool:\n assert UInt64() == 0\n assert UInt64(False) == 0\n return True\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/stubs\/uint64.py","language":"Python","license":"NOASSERTION","size":2073} {"code":"from algopy import BigUInt, Bytes, TemplateVar, UInt64, arc4\nfrom algopy.arc4 import UInt512\n\n\nclass TemplateVariablesContract(arc4.ARC4Contract):\n @arc4.abimethod()\n def get_bytes(self) -> Bytes:\n return TemplateVar[Bytes](\"SOME_BYTES\")\n\n @arc4.abimethod()\n def get_big_uint(self) -> UInt512:\n x = TemplateVar[BigUInt](\"SOME_BIG_UINT\")\n return UInt512(x)\n\n @arc4.baremethod(allow_actions=[\"UpdateApplication\"])\n def on_update(self) -> None:\n assert TemplateVar[bool](\"UPDATABLE\")\n\n @arc4.baremethod(allow_actions=[\"DeleteApplication\"])\n def on_delete(self) -> None:\n assert TemplateVar[UInt64](\"DELETABLE\")\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/template_variables\/contract.py","language":"Python","license":"NOASSERTION","size":667} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass TemplateVariablesContract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def get_bytes(\n self,\n ) -> algopy.arc4.DynamicBytes: ...\n\n @algopy.arc4.abimethod\n def get_big_uint(\n self,\n ) -> algopy.arc4.BigUIntN[typing.Literal[512]]: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/template_variables\/out\/client_TemplateVariablesContract.py","language":"Python","license":"NOASSERTION","size":395} {"code":"from algopy import Bytes, Contract, op, subroutine\n\n\nclass MyContract(Contract):\n def approval_program(self) -> bool:\n a = op.Txn.application_args(0)\n b = op.Txn.application_args(1)\n c = op.Txn.application_args(2)\n d = op.Txn.application_args(3)\n\n assert (a != c) or (b != d)\n assert four_args(a, b, c, d)\n two_args(a, b)\n two_args(c, d)\n\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n\n@subroutine\ndef four_args(a: Bytes, b: Bytes, c: Bytes, d: Bytes) -> bool:\n return (a + b + c + d).length > 0\n\n\n@subroutine\ndef two_args(a: Bytes, b: Bytes) -> None:\n assert a + b\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/too_many_permutations\/contract.py","language":"Python","license":"NOASSERTION","size":670} {"code":"from algopy import (\n Bytes,\n arc4,\n gtxn,\n op,\n subroutine,\n uenumerate,\n)\n\n\nclass TransactionContract(arc4.ARC4Contract):\n @arc4.abimethod(create=\"require\")\n def create(self) -> None:\n pass\n\n @subroutine\n def _common_checks(self, txn: gtxn.TransactionBase) -> None:\n assert txn.txn_id, \"txn_id\"\n assert txn.sender == op.Global.creator_address, \"sender\"\n assert txn.fee, \"fee\"\n assert txn.type, \"type\"\n assert txn.type_bytes, \"type_bytes\"\n assert txn.note == Bytes(b\"\"), \"note\"\n assert txn.group_index == 0, \"group_index\"\n assert txn.first_valid, \"first_valid\"\n # assert txn.first_valid_time, \"first_valid_time\" # this value can be flaky in tests\n assert txn.last_valid, \"last_valid\"\n assert txn.lease, \"lease\"\n assert txn.rekey_to == op.Global.zero_address, \"rekey_to\"\n\n @arc4.abimethod\n def pay(self, txn: gtxn.PaymentTransaction) -> None:\n self._common_checks(txn)\n assert (\n txn.receiver == op.Global.current_application_address\n ), \"Payment should be for this app\"\n assert txn.amount > 1000, \"Payment should be for >1000 micro algos\"\n assert txn.close_remainder_to == op.Global.zero_address, \"close_remainder_to\"\n\n @arc4.abimethod\n def key(self, txn: gtxn.KeyRegistrationTransaction) -> None:\n self._common_checks(txn)\n assert txn.vote_key, \"vote_key\"\n assert txn.selection_key, \"selection_key\"\n assert txn.vote_key_dilution, \"vote_key_dilution\"\n assert txn.vote_first, \"vote_first\"\n assert txn.vote_last, \"vote_last\"\n assert txn.non_participation, \"non_participation\"\n assert txn.state_proof_key, \"state_proof_key\"\n\n @arc4.abimethod\n def asset_config(self, txn: gtxn.AssetConfigTransaction) -> None:\n self._common_checks(txn)\n\n assert txn.config_asset, \"config_asset\"\n assert txn.total, \"total\"\n assert txn.decimals, \"decimals\"\n assert txn.default_frozen, \"default_frozen\"\n assert txn.unit_name, \"unit_name\"\n assert txn.asset_name, \"asset_name\"\n assert txn.url, \"url\"\n assert txn.metadata_hash, \"metadata_hash\"\n assert txn.manager, \"manager\"\n assert txn.reserve, \"reserve\"\n assert txn.freeze, \"freeze\"\n assert txn.clawback, \"clawback\"\n\n @arc4.abimethod\n def asset_transfer(self, txn: gtxn.AssetTransferTransaction) -> None:\n self._common_checks(txn)\n assert txn.xfer_asset, \"xfer_asset\"\n assert txn.asset_amount, \"asset_amount\"\n assert txn.asset_sender, \"asset_sender\"\n assert txn.asset_receiver, \"asset_receiver\"\n assert txn.asset_close_to, \"asset_close_to\"\n\n @arc4.abimethod\n def asset_freeze(self, txn: gtxn.AssetFreezeTransaction) -> None:\n self._common_checks(txn)\n\n assert txn.freeze_asset, \"freeze_asset\"\n assert txn.freeze_account, \"freeze_account\"\n assert txn.frozen, \"frozen\"\n\n @arc4.abimethod\n def application_call(self, txn: gtxn.ApplicationCallTransaction) -> None:\n self._common_checks(txn)\n assert txn.app_id, \"app_id\"\n assert txn.on_completion, \"on_completion\"\n assert txn.num_app_args, \"num_app_args\"\n assert txn.num_accounts, \"num_accounts\"\n assert txn.approval_program, \"approval_program\"\n assert txn.clear_state_program, \"clear_state_program\"\n assert txn.num_assets, \"num_assets\"\n assert txn.num_apps, \"num_apps\"\n assert txn.global_num_uint, \"global_num_uint\"\n assert txn.global_num_bytes, \"global_num_bytes\"\n assert txn.local_num_uint, \"local_num_uint\"\n assert txn.local_num_bytes, \"local_num_bytes\"\n assert txn.extra_program_pages, \"extra_program_pages\"\n assert txn.last_log, \"last_log\"\n assert txn.num_approval_program_pages, \"num_approval_program_pages\"\n assert txn.num_clear_state_program_pages, \"num_clear_state_program_pages\"\n assert txn.app_args(0), \"app_args(0)\"\n assert txn.accounts(0), \"accounts(0)\"\n assert txn.assets(0), \"assets(0)\"\n assert txn.apps(0), \"apps(0)\"\n assert txn.approval_program_pages(0), \"approval_program_pages(0)\"\n assert txn.clear_state_program_pages(0), \"clear_state_program_pages(0)\"\n\n @arc4.abimethod\n def multiple_txns(\n self,\n txn1: gtxn.ApplicationCallTransaction,\n txn2: gtxn.ApplicationCallTransaction,\n txn3: gtxn.ApplicationCallTransaction,\n ) -> None:\n for index, app in uenumerate((txn1, txn2, txn3)):\n assert app.group_index == index\n\n @arc4.abimethod\n def any_txn(\n self,\n txn1: gtxn.Transaction,\n txn2: gtxn.Transaction,\n txn3: gtxn.Transaction,\n ) -> None:\n for index, txn in uenumerate((txn1, txn2, txn3)):\n assert txn.group_index == index\n\n @arc4.abimethod\n def group_init(\n self,\n txn1: gtxn.Transaction,\n txn2: gtxn.Transaction,\n txn3: gtxn.Transaction,\n ) -> None:\n for txn in (txn1, txn2, txn3):\n txn_from_index = gtxn.Transaction(txn.group_index)\n assert txn.txn_id == txn_from_index.txn_id\n assert txn1.txn_id == gtxn.Transaction(0).txn_id\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/transaction\/contract.py","language":"Python","license":"NOASSERTION","size":5286} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass TransactionContract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod(create='require')\n def create(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def pay(\n self,\n txn: algopy.gtxn.PaymentTransaction,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def key(\n self,\n txn: algopy.gtxn.KeyRegistrationTransaction,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def asset_config(\n self,\n txn: algopy.gtxn.AssetConfigTransaction,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def asset_transfer(\n self,\n txn: algopy.gtxn.AssetTransferTransaction,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def asset_freeze(\n self,\n txn: algopy.gtxn.AssetFreezeTransaction,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def application_call(\n self,\n txn: algopy.gtxn.ApplicationCallTransaction,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def multiple_txns(\n self,\n txn1: algopy.gtxn.ApplicationCallTransaction,\n txn2: algopy.gtxn.ApplicationCallTransaction,\n txn3: algopy.gtxn.ApplicationCallTransaction,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def any_txn(\n self,\n txn1: algopy.gtxn.Transaction,\n txn2: algopy.gtxn.Transaction,\n txn3: algopy.gtxn.Transaction,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def group_init(\n self,\n txn1: algopy.gtxn.Transaction,\n txn2: algopy.gtxn.Transaction,\n txn3: algopy.gtxn.Transaction,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/transaction\/out\/client_TransactionContract.py","language":"Python","license":"NOASSERTION","size":1689} {"code":"import typing\n\nfrom algopy import ARC4Contract, Bytes, String, UInt64, arc4, op, subroutine\n\n\nclass Child(typing.NamedTuple):\n a: UInt64\n b: Bytes\n c: String\n\n\nclass Parent(typing.NamedTuple):\n foo: UInt64\n foo_arc: arc4.UInt64\n child: Child\n\n\nclass NestedTuples(ARC4Contract):\n def __init__(self) -> None:\n self.build_nested_call_count = UInt64(0)\n\n @arc4.abimethod()\n def run_tests(self) -> bool:\n x = (String(\"Hi\"), String(\"There\"))\n assert test_swap(x) == (String(\"There\"), String(\"Hi\"))\n y = (UInt64(1), x)\n z = (UInt64(0), UInt64(2), y)\n z2 = z[2]\n z2_1 = z2[1]\n _x, z2_1_1 = z2_1\n assert z2_1_1 == \"There\"\n\n (a, b, (c, d, (e,))) = test_rearrange(x[0], _b=x[1], args=z)\n assert (a, b) == (String(\"Hi\"), UInt64(0))\n assert (c, d) == (UInt64(2), UInt64(1))\n assert e == String(\"There\")\n\n test_intrinsics(UInt64(1), UInt64(2))\n test_nested_slicing()\n test_nested_singles(UInt64(1), reassign=True)\n test_nested_singles(UInt64(1), reassign=False)\n test_nested_mutation()\n\n assert z[2] == y\n\n test_nested_iteration()\n\n self.test_single_evaluation_nested()\n return True\n\n @arc4.abimethod()\n def nested_tuple_params(\n self, args: tuple[String, tuple[Bytes, tuple[UInt64]]]\n ) -> tuple[Bytes, tuple[String, UInt64]]:\n (s, (b, (u,))) = args\n return b, (s, u)\n\n @arc4.abimethod()\n def named_tuple(self, args: Child) -> Child:\n a, b, c = args\n return Child(a, b, c)\n\n @arc4.abimethod()\n def nested_named_tuple_params(self, args: Parent) -> Parent:\n foo, foo_arc, (a, b, c) = args\n return Parent(foo, foo_arc, Child(a, b, c))\n\n @subroutine\n def build_nested(self) -> tuple[tuple[String, UInt64], Bytes]:\n self.build_nested_call_count += 1\n return (String(\"hi\"), UInt64(1)), Bytes(b\"hmmm\")\n\n @subroutine\n def test_single_evaluation_nested(self) -> None:\n self.build_nested_call_count = UInt64(0)\n result = self.build_nested() or self.build_nested()\n assert result[0][0] == \"hi\"\n assert self.build_nested_call_count == 1\n\n\n@subroutine\ndef test_rearrange(\n _a: String, args: tuple[UInt64, UInt64, tuple[UInt64, tuple[String, String]]], _b: String\n) -> tuple[String, UInt64, tuple[UInt64, UInt64, tuple[String]]]:\n (a, b, (c, (d, e))) = args\n\n return d, a, (b, c, (e,))\n\n\n@subroutine\ndef test_swap(args: tuple[String, String]) -> tuple[String, String]:\n (a, b) = args\n return b, a\n\n\n@subroutine\ndef test_intrinsics(num1: UInt64, num2: UInt64) -> None:\n nt = (UInt64(1), op.addw(num1, num2), UInt64(42))\n assert nt[0] == 1\n assert nt[-1] == 42\n assert nt[1] == (0, num1 + num2) # type: ignore[comparison-overlap]\n assert nt[1][:1] == (0,) # type: ignore[comparison-overlap]\n assert nt[1][1:] == (num1 + num2,)\n ((x, y),) = nt[1:2]\n assert x == 0\n assert y == num1 + num2\n\n\n@subroutine\ndef test_nested_slicing() -> None:\n nt = (\n UInt64(1),\n UInt64(2),\n (\n UInt64(3),\n (\n String(\"a\"),\n String(\"b\"),\n ),\n UInt64(4),\n ),\n UInt64(5),\n UInt64(6),\n )\n (a, b, c) = nt[1:4]\n assert b[-1] == 4\n assert ((a, c),) == ((2, 5),) # type: ignore[comparison-overlap]\n assert b[1][:] == (\"a\", \"b\") # type: ignore[comparison-overlap]\n\n\n@subroutine\ndef test_nested_singles(one: UInt64, *, reassign: bool) -> None:\n s = (\n (UInt64(0),),\n (one,),\n (UInt64(2),),\n )\n assert s[0][0] == 0\n assert s[0] == (0,) # type: ignore[comparison-overlap]\n assert s[1][0] == 1\n assert s[1] == (one,)\n assert s[2][0] == 2\n assert s[2] == (2,) # type: ignore[comparison-overlap]\n t = s[1]\n if reassign:\n s = (\n (UInt64(3),),\n (UInt64(4),),\n (UInt64(5),),\n )\n assert s[0][0] == (3 if reassign else 0)\n (tmp,) = s[2]\n assert tmp == (5 if reassign else 2)\n assert t == (one,)\n\n s0, (s1,), s2 = s\n s1 += one\n assert s1 == (5 if reassign else 2)\n assert s[1][0] == (4 if reassign else 1)\n\n\n@subroutine\ndef test_nested_mutation() -> None:\n x = (\n (\n arc4.DynamicArray(\n arc4.UInt64(0),\n ),\n ),\n )\n x[0][0].append(arc4.UInt64(1))\n assert x[0][0].length == 2\n\n\n@subroutine\ndef test_nested_iteration() -> None:\n x = UInt64(1)\n y = UInt64(2)\n total = UInt64(0)\n\n for t in ((x, y), (y, x), (x, x), (y, y)):\n a, b = t\n total += a + b\n\n for a, b in ((x, y), (y, x), (x, x), (y, y)):\n total += a + b\n\n assert total \/\/ 8 == 3\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/tuple_support\/nested_tuples.py","language":"Python","license":"NOASSERTION","size":4773} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\nclass Child(algopy.arc4.Struct):\n a: algopy.arc4.UIntN[typing.Literal[64]]\n b: algopy.arc4.DynamicBytes\n c: algopy.arc4.String\n\nclass Parent(algopy.arc4.Struct):\n foo: algopy.arc4.UIntN[typing.Literal[64]]\n foo_arc: algopy.arc4.UIntN[typing.Literal[64]]\n child: Child\n\nclass NestedTuples(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def run_tests(\n self,\n ) -> algopy.arc4.Bool: ...\n\n @algopy.arc4.abimethod\n def nested_tuple_params(\n self,\n args: algopy.arc4.Tuple[algopy.arc4.String, algopy.arc4.Tuple[algopy.arc4.DynamicBytes, algopy.arc4.Tuple[algopy.arc4.UIntN[typing.Literal[64]]]]],\n ) -> algopy.arc4.Tuple[algopy.arc4.DynamicBytes, algopy.arc4.Tuple[algopy.arc4.String, algopy.arc4.UIntN[typing.Literal[64]]]]: ...\n\n @algopy.arc4.abimethod\n def named_tuple(\n self,\n args: Child,\n ) -> Child: ...\n\n @algopy.arc4.abimethod\n def nested_named_tuple_params(\n self,\n args: Parent,\n ) -> Parent: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/tuple_support\/out\/client_NestedTuples.py","language":"Python","license":"NOASSERTION","size":1127} {"code":"from algopy import Contract, String, UInt64, log, subroutine\n\n\nclass TupleComparisons(Contract):\n def approval_program(self) -> bool:\n test_tuple_cmp_eval()\n test_tuple_cmp_empty()\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n\n@subroutine\ndef test_tuple_cmp_eval() -> None:\n assert (\n String(\"abc\"),\n log_and_return(UInt64(42)),\n ) != (String(\"abc\"),) # type: ignore[comparison-overlap]\n tmp = (\n String(\"abc\"),\n log_and_return(UInt64(43)),\n ) == (String(\"abc\"),) # type: ignore[comparison-overlap]\n assert not tmp\n\n assert (String(\"abc\"),) != (\n String(\"abc\"),\n log_and_return(UInt64(44)),\n ) # type: ignore[comparison-overlap]\n tmp = (String(\"abc\"),) == (\n String(\"abc\"),\n log_and_return(UInt64(45)),\n ) # type: ignore[comparison-overlap]\n assert not tmp\n\n assert (UInt64(1), UInt64(2)) != (UInt64(3), log_and_return(UInt64(46)))\n tmp = (UInt64(1), UInt64(2)) == (UInt64(3), log_and_return(UInt64(47)))\n assert not tmp\n\n\n@subroutine\ndef test_tuple_cmp_empty() -> None:\n assert () == ()\n tmp = () != ()\n assert not tmp\n\n assert () != (\"a\",) # type: ignore[comparison-overlap]\n tmp = () == (\"a\",) # type: ignore[comparison-overlap]\n assert not tmp\n\n\n@subroutine\ndef log_and_return(val: UInt64) -> UInt64:\n log(val)\n return val\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/tuple_support\/tuple_comparisons.py","language":"Python","license":"NOASSERTION","size":1409} {"code":"from algopy import Bytes, Contract, UInt64, log, op, subroutine, urange\n\n\nclass TupleSupport(Contract):\n def __init__(self) -> None:\n self.state = UInt64(0)\n\n def approval_program(self) -> UInt64:\n total = add_three_values((UInt64(101), UInt64(102), UInt64(103)))\n log(total)\n (a, b) = (UInt64(1), UInt64(2))\n (did_overflow, self.state) = op.addw(a, b)\n assert not did_overflow, \"overflow!\"\n ab = (a, b)\n assert ab[-1] == ab[1]\n result = op.addw(a, b)\n assert not result[0], \"overflow!\"\n c = d = UInt64(3)\n ((a2, b2), cd, ab2) = (ab, (c, d), ab)\n if a == b:\n tup = ab2\n else:\n tup = cd\n assert a2 == a\n assert b2 == b\n assert cd[0] == tup[0]\n assert cd[1] == tup[1]\n\n (m, n) = get_tuple(a, b) or get_tuple(b, a)\n assert (m, n) == (a, b)\n\n # assert ab2 == ab # TODO: support ths\n # foobar = ((a, b), (c, d)) # TODO: negative test for this\n log(bytes_combine((Bytes(b\"Hello, \"), Bytes(b\"world!\"))))\n max_uint64 = UInt64(2**64 - 1)\n hi, mid, lo = addw2(op.addw(max_uint64, max_uint64), op.addw(a, b))\n log(hi)\n log(mid)\n log(lo)\n log(bytes_multiply((Bytes(b\"na\"), UInt64(5))))\n test_tuple_swap(zero=UInt64(0))\n slicing(\n (\n UInt64(1),\n UInt64(2),\n UInt64(3),\n UInt64(4),\n UInt64(5),\n UInt64(6),\n UInt64(7),\n UInt64(8),\n )\n )\n bin_ops()\n if non_empty_tuple():\n log(\"not empty\")\n if (get_uint_with_side_effect(),): # noqa: F634\n log(\"not empty2\")\n single_tuple()\n\n x = tuple[UInt64, Bytes]((UInt64(), Bytes()))\n assert x[0] == 0\n assert x[1] == b\"\"\n test_empty()\n return a + b\n\n def clear_state_program(self) -> UInt64:\n return UInt64(0)\n\n\n@subroutine\ndef get_tuple(a: UInt64, b: UInt64) -> tuple[UInt64, UInt64]:\n return a, b\n\n\n@subroutine\ndef single_tuple() -> None:\n tup = (UInt64(1),)\n assert tup[0] == 1\n\n\n@subroutine\ndef get_uint_with_side_effect() -> UInt64:\n log(\"get_uint_with_side_effect called\")\n return UInt64(4)\n\n\n@subroutine\ndef non_empty_tuple() -> tuple[UInt64, UInt64]:\n log(\"non_empty_tuple called\")\n return UInt64(4), UInt64(2)\n\n\n@subroutine\ndef bin_ops() -> None:\n a = (UInt64(1),) * 3\n assert a[0] == 1\n assert a[1] == 1\n assert a[2] == 1\n\n tup = (UInt64(1), UInt64(2))\n b = tup * 3\n assert b[0] == 1\n assert b[1] == 2\n assert b[2] == 1\n assert b[3] == 2\n assert b[4] == 1\n assert b[5] == 2\n\n c = (UInt64(1),) + (Bytes(b\"2\"), UInt64(3)) # noqa: RUF005\n assert c[0] == 1\n assert c[1] == b\"2\"\n assert c[2] == 3\n\n d = tup + tup\n assert d[0] == 1\n assert d[1] == 2\n assert d[2] == 1\n assert d[3] == 2\n\n\n@subroutine\ndef bytes_combine(arg: tuple[Bytes, Bytes]) -> Bytes:\n a, b = arg\n result = a + b\n return result\n\n\n@subroutine\ndef bytes_multiply(arg: tuple[Bytes, UInt64]) -> Bytes:\n b, count = arg\n result = Bytes()\n for _i in urange(count):\n result += b\n return result\n\n\n@subroutine\ndef add_three_values(values: tuple[UInt64, UInt64, UInt64]) -> UInt64:\n total = UInt64(0)\n for value in values:\n total += value\n\n return total\n\n\n@subroutine\ndef addw2(a: tuple[UInt64, UInt64], b: tuple[UInt64, UInt64]) -> tuple[UInt64, UInt64, UInt64]:\n a_hi, a_lo = a\n b_hi, b_lo = b\n lo_carry, c_lo = op.addw(a_lo, b_lo)\n hi_carry1, c_mid = op.addw(a_hi, b_hi)\n hi_carry2, c_mid = op.addw(c_mid, lo_carry)\n did_overflow, c_hi = op.addw(hi_carry1, hi_carry2)\n assert not did_overflow, \"is such a thing even possible? \ud83d\udc7d\"\n return c_hi, c_mid, c_lo\n\n\n@subroutine\ndef test_tuple_swap(zero: UInt64) -> None:\n a = zero + 1\n b = zero + 2\n (a, b) = (b, a)\n assert a == 2, \"a should be two\"\n assert b == 1, \"b should be one\"\n\n\n@subroutine\ndef slicing(values: tuple[UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64]) -> None:\n one_to_three = values[0:3]\n assert add_three_values(one_to_three) == values[0] + values[1] + values[2]\n\n assert one_to_three[-2:-1][0] == one_to_three[1]\n\n assert one_to_three == one_to_three[:]\n\n\n@subroutine\ndef test_empty() -> None:\n empty = ()\n empty2 = empty\n () = empty\n () = ()\n assert not empty\n assert not empty2\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/tuple_support\/tuple_support.py","language":"Python","license":"NOASSERTION","size":4540} {"code":"import typing\n\nfrom algopy import (\n Account,\n Application,\n ARC4Contract,\n Asset,\n BigUInt,\n Bytes,\n String,\n Txn,\n UInt64,\n arc4,\n log,\n)\n\nLOG_METHOD_NAME = \"log\"\n\n\nclass LogMessage(typing.NamedTuple):\n level: UInt64\n message: String\n\n\nclass Logger(ARC4Contract):\n @arc4.abimethod\n def is_a_b(self, a: Bytes, b: Bytes) -> None:\n assert a == b\"a\", \"a is not a\"\n assert b == b\"b\", \"b is not b\"\n\n @arc4.abimethod\n def echo(self, value: arc4.String) -> arc4.String:\n return \"echo: \" + value\n\n @arc4.abimethod\n def no_args(self) -> UInt64:\n return UInt64(42)\n\n @arc4.abimethod(name=LOG_METHOD_NAME)\n def log_uint64(self, value: arc4.UInt64) -> None:\n log(value)\n\n @arc4.abimethod(name=LOG_METHOD_NAME)\n def log_uint512(self, value: arc4.UInt512) -> None:\n log(value)\n\n @arc4.abimethod(name=LOG_METHOD_NAME)\n def log_string(self, value: arc4.String) -> None:\n log(value.native) # decode to remove header\n\n @arc4.abimethod(name=LOG_METHOD_NAME)\n def log_bool(self, value: arc4.Bool) -> None:\n log(Bytes(b\"True\") if value.native else Bytes(b\"False\"))\n\n @arc4.abimethod(name=LOG_METHOD_NAME)\n def log_bytes(self, value: arc4.DynamicBytes) -> None:\n log(value.native)\n\n @arc4.abimethod(name=LOG_METHOD_NAME)\n def log_asset_account_app(self, asset: Asset, account: Account, app: Application) -> None:\n log(asset.name, account.bytes, app.address)\n\n @arc4.abimethod\n def echo_native_string(self, value: String) -> String:\n return \"echo: \" + value\n\n @arc4.abimethod\n def echo_native_bytes(self, value: Bytes) -> Bytes:\n return b\"echo: \" + value\n\n @arc4.abimethod\n def echo_native_uint64(self, value: UInt64) -> UInt64:\n return value + 1\n\n @arc4.abimethod\n def echo_native_biguint(self, value: BigUInt) -> BigUInt:\n return value + 1\n\n @arc4.abimethod\n def echo_native_tuple(\n self, s: String, b: Bytes, u: UInt64, bu: BigUInt\n ) -> tuple[String, Bytes, UInt64, BigUInt]:\n return \"echo: \" + s, b\"echo: \" + b, u + 1, bu + 1\n\n @arc4.abimethod\n def echo_nested_tuple(\n self, tuple_of_tuples: tuple[tuple[String, arc4.String], tuple[UInt64, arc4.UInt64, Bytes]]\n ) -> tuple[tuple[String, arc4.String], tuple[UInt64, arc4.UInt64, Bytes]]:\n (string, arc4_string), (u64, arc4_u64, bytez) = tuple_of_tuples\n return (\"echo: \" + string, \"echo: \" + arc4_string), (\n u64 + 1,\n arc4.UInt64(arc4_u64.native + 1),\n b\"echo: \" + bytez,\n )\n\n @arc4.abimethod\n def return_args_after_14th(\n self,\n _a1: arc4.UInt64,\n _a2: arc4.UInt64,\n _a3: arc4.UInt64,\n _a4: arc4.UInt64,\n _a5: arc4.UInt64,\n _a6: arc4.UInt64,\n _a7: arc4.UInt64,\n _a8: arc4.UInt64,\n _a9: arc4.UInt64,\n _a10: arc4.UInt64,\n _a11: arc4.UInt64,\n _a12: arc4.UInt64,\n _a13: arc4.UInt64,\n _a14: arc4.UInt64,\n a15: arc4.UInt8,\n a16: arc4.UInt8,\n a17: arc4.UInt8,\n a18: arc4.UInt8,\n a19: arc4.Tuple[arc4.UInt8, arc4.UInt8, arc4.UInt8, arc4.UInt8],\n a20: arc4.UInt8,\n ) -> arc4.DynamicBytes:\n last_arg = arc4.Tuple((a15, a16, a17, a18, a19, a20))\n assert Txn.application_args(15) == last_arg.bytes\n return arc4.DynamicBytes(last_arg.bytes)\n\n @arc4.abimethod\n def logs_are_equal(self, log_1: LogMessage, log_2: LogMessage) -> bool:\n return log_1 == log_2\n\n\nclass LoggerClient(arc4.ARC4Client, typing.Protocol):\n @arc4.abimethod\n def echo(self, value: arc4.String) -> arc4.String: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/typed_abi_call\/logger.py","language":"Python","license":"NOASSERTION","size":3710} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass Greeter(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def test_is_a_b(\n self,\n a: algopy.arc4.DynamicBytes,\n b: algopy.arc4.DynamicBytes,\n app: algopy.Application,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_method_selector_kinds(\n self,\n app: algopy.Application,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_method_overload(\n self,\n app: algopy.Application,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_arg_conversion(\n self,\n app: algopy.Application,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_15plus_args(\n self,\n app: algopy.Application,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_void(\n self,\n app: algopy.Application,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_ref_types(\n self,\n app: algopy.Application,\n asset: algopy.Asset,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_native_string(\n self,\n app: algopy.Application,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_native_bytes(\n self,\n app: algopy.Application,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_native_uint64(\n self,\n app: algopy.Application,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_native_biguint(\n self,\n app: algopy.Application,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_native_tuple(\n self,\n app: algopy.Application,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_native_tuple_method_ref(\n self,\n app: algopy.Application,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_nested_tuples(\n self,\n app: algopy.Application,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_no_args(\n self,\n app: algopy.Application,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_named_tuples(\n self,\n app: algopy.Application,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/typed_abi_call\/out\/client_Greeter.py","language":"Python","license":"NOASSERTION","size":2203} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\nclass LogMessage(algopy.arc4.Struct):\n level: algopy.arc4.UIntN[typing.Literal[64]]\n message: algopy.arc4.String\n\nclass Logger(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def is_a_b(\n self,\n a: algopy.arc4.DynamicBytes,\n b: algopy.arc4.DynamicBytes,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def echo(\n self,\n value: algopy.arc4.String,\n ) -> algopy.arc4.String: ...\n\n @algopy.arc4.abimethod\n def no_args(\n self,\n ) -> algopy.arc4.UIntN[typing.Literal[64]]: ...\n\n @algopy.arc4.abimethod\n def log(\n self,\n value: algopy.arc4.UIntN[typing.Literal[64]],\n ) -> None: ...\n\n @algopy.arc4.abimethod(name='log')\n def log2(\n self,\n value: algopy.arc4.BigUIntN[typing.Literal[512]],\n ) -> None: ...\n\n @algopy.arc4.abimethod(name='log')\n def log3(\n self,\n value: algopy.arc4.String,\n ) -> None: ...\n\n @algopy.arc4.abimethod(name='log')\n def log4(\n self,\n value: algopy.arc4.Bool,\n ) -> None: ...\n\n @algopy.arc4.abimethod(name='log')\n def log5(\n self,\n value: algopy.arc4.DynamicBytes,\n ) -> None: ...\n\n @algopy.arc4.abimethod(name='log')\n def log6(\n self,\n asset: algopy.Asset,\n account: algopy.Account,\n app: algopy.Application,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def echo_native_string(\n self,\n value: algopy.arc4.String,\n ) -> algopy.arc4.String: ...\n\n @algopy.arc4.abimethod\n def echo_native_bytes(\n self,\n value: algopy.arc4.DynamicBytes,\n ) -> algopy.arc4.DynamicBytes: ...\n\n @algopy.arc4.abimethod\n def echo_native_uint64(\n self,\n value: algopy.arc4.UIntN[typing.Literal[64]],\n ) -> algopy.arc4.UIntN[typing.Literal[64]]: ...\n\n @algopy.arc4.abimethod\n def echo_native_biguint(\n self,\n value: algopy.arc4.BigUIntN[typing.Literal[512]],\n ) -> algopy.arc4.BigUIntN[typing.Literal[512]]: ...\n\n @algopy.arc4.abimethod\n def echo_native_tuple(\n self,\n s: algopy.arc4.String,\n b: algopy.arc4.DynamicBytes,\n u: algopy.arc4.UIntN[typing.Literal[64]],\n bu: algopy.arc4.BigUIntN[typing.Literal[512]],\n ) -> algopy.arc4.Tuple[algopy.arc4.String, algopy.arc4.DynamicBytes, algopy.arc4.UIntN[typing.Literal[64]], algopy.arc4.BigUIntN[typing.Literal[512]]]: ...\n\n @algopy.arc4.abimethod\n def echo_nested_tuple(\n self,\n tuple_of_tuples: algopy.arc4.Tuple[algopy.arc4.Tuple[algopy.arc4.String, algopy.arc4.String], algopy.arc4.Tuple[algopy.arc4.UIntN[typing.Literal[64]], algopy.arc4.UIntN[typing.Literal[64]], algopy.arc4.DynamicBytes]],\n ) -> algopy.arc4.Tuple[algopy.arc4.Tuple[algopy.arc4.String, algopy.arc4.String], algopy.arc4.Tuple[algopy.arc4.UIntN[typing.Literal[64]], algopy.arc4.UIntN[typing.Literal[64]], algopy.arc4.DynamicBytes]]: ...\n\n @algopy.arc4.abimethod\n def return_args_after_14th(\n self,\n _a1: algopy.arc4.UIntN[typing.Literal[64]],\n _a2: algopy.arc4.UIntN[typing.Literal[64]],\n _a3: algopy.arc4.UIntN[typing.Literal[64]],\n _a4: algopy.arc4.UIntN[typing.Literal[64]],\n _a5: algopy.arc4.UIntN[typing.Literal[64]],\n _a6: algopy.arc4.UIntN[typing.Literal[64]],\n _a7: algopy.arc4.UIntN[typing.Literal[64]],\n _a8: algopy.arc4.UIntN[typing.Literal[64]],\n _a9: algopy.arc4.UIntN[typing.Literal[64]],\n _a10: algopy.arc4.UIntN[typing.Literal[64]],\n _a11: algopy.arc4.UIntN[typing.Literal[64]],\n _a12: algopy.arc4.UIntN[typing.Literal[64]],\n _a13: algopy.arc4.UIntN[typing.Literal[64]],\n _a14: algopy.arc4.UIntN[typing.Literal[64]],\n a15: algopy.arc4.UIntN[typing.Literal[8]],\n a16: algopy.arc4.UIntN[typing.Literal[8]],\n a17: algopy.arc4.UIntN[typing.Literal[8]],\n a18: algopy.arc4.UIntN[typing.Literal[8]],\n a19: algopy.arc4.Tuple[algopy.arc4.UIntN[typing.Literal[8]], algopy.arc4.UIntN[typing.Literal[8]], algopy.arc4.UIntN[typing.Literal[8]], algopy.arc4.UIntN[typing.Literal[8]]],\n a20: algopy.arc4.UIntN[typing.Literal[8]],\n ) -> algopy.arc4.DynamicBytes: ...\n\n @algopy.arc4.abimethod\n def logs_are_equal(\n self,\n log_1: LogMessage,\n log_2: LogMessage,\n ) -> algopy.arc4.Bool: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/typed_abi_call\/out\/client_Logger.py","language":"Python","license":"NOASSERTION","size":4481} {"code":"from algopy import (\n Application,\n ARC4Contract,\n Asset,\n BigUInt,\n Bytes,\n Global,\n String,\n UInt64,\n arc4,\n op,\n)\n\nfrom test_cases.typed_abi_call.logger import LOG_METHOD_NAME, Logger, LoggerClient, LogMessage\n\n\nclass Greeter(ARC4Contract):\n @arc4.abimethod\n def test_is_a_b(self, a: Bytes, b: Bytes, app: Application) -> None:\n arc4.abi_call(\n \"is_a_b(byte[],byte[])void\",\n a,\n b,\n app_id=app,\n )\n\n @arc4.abimethod()\n def test_method_selector_kinds(self, app: Application) -> None:\n result, _txn = arc4.abi_call(Logger.echo, arc4.String(\"test1\"), app_id=app)\n assert result == \"echo: test1\"\n result, _txn = arc4.abi_call(LoggerClient.echo, \"test2\", app_id=app)\n assert result == \"echo: test2\"\n result, _txn = arc4.abi_call[arc4.String](\"echo\", \"test3\", app_id=app)\n assert result == \"echo: test3\"\n result, _txn = arc4.abi_call[arc4.String](\"echo(string)\", \"test4\", app_id=app)\n assert result == \"echo: test4\"\n result, _txn = arc4.abi_call[arc4.String](\"echo(string)string\", \"test5\", app_id=app)\n assert result == \"echo: test5\"\n\n @arc4.abimethod()\n def test_method_overload(self, app: Application) -> None:\n arc4.abi_call[arc4.String](\"echo(string)string\", \"typed + ignore\", app_id=app)\n assert arc4.String.from_log(op.ITxn.last_log()) == \"echo: typed + ignore\"\n\n arc4.abi_call(\"echo(string)string\", \"untyped + ignore\", app_id=app)\n assert arc4.String.from_log(op.ITxn.last_log()) == \"echo: untyped + ignore\"\n\n result = arc4.abi_call[arc4.String](\"echo(string)string\", \"tuple\", app_id=app)\n assert result[0] == \"echo: tuple\"\n assert arc4.String.from_log(result[1].last_log) == \"echo: tuple\"\n\n txn_result = arc4.abi_call(\"echo(string)string\", \"untyped\", app_id=app)\n assert arc4.String.from_log(txn_result.last_log) == \"echo: untyped\"\n\n @arc4.abimethod()\n def test_arg_conversion(self, app: Application) -> None:\n txn = arc4.abi_call(Logger.log_string, \"converted1\", app_id=app)\n assert txn.last_log == b\"converted1\"\n\n txn = arc4.abi_call(Logger.log_uint64, 2, app_id=app)\n assert txn.last_log == op.itob(2)\n\n txn = arc4.abi_call(Logger.log_uint512, 3, app_id=app)\n assert txn.last_log == (op.bzero(56) + op.itob(3))\n\n txn = arc4.abi_call(Logger.log_bytes, b\"4\", app_id=app)\n assert txn.last_log == b\"4\"\n\n txn = arc4.abi_call(Logger.log_bool, True, app_id=app)\n assert txn.last_log == b\"True\"\n\n @arc4.abimethod()\n def test_15plus_args(self, app: Application) -> None:\n result, txn = arc4.abi_call(\n Logger.return_args_after_14th,\n 1,\n 2,\n 3,\n 4,\n 5,\n 6,\n 7,\n 8,\n 9,\n 10,\n 11,\n 12,\n 13,\n 14,\n 15,\n 16,\n 17,\n 18,\n arc4.Tuple((arc4.UInt8(0xDE), arc4.UInt8(0xAD), arc4.UInt8(0xBE), arc4.UInt8(0xEF))),\n 20,\n app_id=app,\n )\n assert result.native == Bytes.from_hex(\"0F101112DEADBEEF14\")\n\n @arc4.abimethod()\n def test_void(self, app: Application) -> None:\n txn = arc4.abi_call(LOG_METHOD_NAME + \"(string)void\", \"World1\", app_id=app)\n assert txn.last_log == b\"World1\"\n\n txn = arc4.abi_call(LOG_METHOD_NAME + \"(string)\", \"World2\", app_id=app)\n assert txn.last_log == b\"World2\"\n\n txn = arc4.abi_call(LOG_METHOD_NAME, arc4.String(\"World3\"), app_id=app)\n assert txn.last_log == b\"World3\"\n\n txn = arc4.abi_call(Logger.log_string, \"World4\", app_id=app)\n assert txn.last_log == b\"World4\"\n\n @arc4.abimethod()\n def test_ref_types(self, app: Application, asset: Asset) -> None:\n txn = arc4.abi_call(\n Logger.log_asset_account_app,\n asset,\n Global.current_application_address,\n app,\n app_id=app,\n )\n assert (\n txn.last_log\n == asset.name + Global.current_application_address.bytes + app.address.bytes\n )\n\n @arc4.abimethod()\n def test_native_string(self, app: Application) -> None:\n result1, _txn = arc4.abi_call(Logger.echo_native_string, \"s\", app_id=app)\n assert result1 == \"echo: s\"\n\n result2, _txn = arc4.abi_call(Logger.echo_native_string, String(\"s\"), app_id=app)\n assert result2 == result1\n\n result3, _txn = arc4.abi_call(Logger.echo_native_string, arc4.String(\"s\"), app_id=app)\n assert result3 == result1\n\n @arc4.abimethod()\n def test_native_bytes(self, app: Application) -> None:\n result1, _txn = arc4.abi_call(Logger.echo_native_bytes, b\"b\", app_id=app)\n assert result1 == b\"echo: b\"\n\n result2, _txn = arc4.abi_call(Logger.echo_native_bytes, Bytes(b\"b\"), app_id=app)\n assert result2 == result1\n\n result3, _txn = arc4.abi_call(\n Logger.echo_native_bytes, arc4.DynamicBytes(b\"b\"), app_id=app\n )\n assert result3 == result1\n\n @arc4.abimethod()\n def test_native_uint64(self, app: Application) -> None:\n result1, _txn = arc4.abi_call(Logger.echo_native_uint64, 1, app_id=app)\n assert result1 == 2\n\n result2, _txn = arc4.abi_call(Logger.echo_native_uint64, UInt64(1), app_id=app)\n assert result2 == result1\n\n result3, _txn = arc4.abi_call(Logger.echo_native_uint64, arc4.UInt64(1), app_id=app)\n assert result3 == result1\n\n @arc4.abimethod()\n def test_native_biguint(self, app: Application) -> None:\n result1, _txn = arc4.abi_call(Logger.echo_native_biguint, 2, app_id=app)\n assert result1 == 3\n\n result2, _txn = arc4.abi_call(Logger.echo_native_biguint, BigUInt(2), app_id=app)\n assert result2 == result1\n\n result3, _txn = arc4.abi_call(Logger.echo_native_biguint, arc4.UInt512(2), app_id=app)\n assert result3 == result1\n\n @arc4.abimethod()\n def test_native_tuple(self, app: Application) -> None:\n # python literals\n result1, txn = arc4.abi_call[\n arc4.Tuple[arc4.String, arc4.DynamicBytes, arc4.UInt64, arc4.UInt512]\n ](\n \"echo_native_tuple(string,byte[],uint64,uint512)(string,byte[],uint64,uint512)\",\n \"s1\",\n b\"b1\",\n 1,\n 2,\n app_id=app,\n )\n s, b, u, bu = result1.native\n assert s.native == \"echo: s1\"\n assert b.native == b\"echo: b1\"\n assert u.native == 2\n assert bu.native == 3\n\n # test again using native types in arguments\n result2, txn = arc4.abi_call[\n arc4.Tuple[arc4.String, arc4.DynamicBytes, arc4.UInt64, arc4.UInt512]\n ](\n \"echo_native_tuple(string,byte[],uint64,uint512)(string,byte[],uint64,uint512)\",\n String(\"s1\"),\n Bytes(b\"b1\"),\n UInt64(1),\n BigUInt(2),\n app_id=app,\n )\n assert result1 == result2\n\n # test again using arc4 types in arguments\n result3, txn = arc4.abi_call[\n arc4.Tuple[arc4.String, arc4.DynamicBytes, arc4.UInt64, arc4.UInt512]\n ](\n \"echo_native_tuple(string,byte[],uint64,uint512)(string,byte[],uint64,uint512)\",\n arc4.String(\"s1\"),\n arc4.DynamicBytes(b\"b1\"),\n arc4.UInt64(1),\n arc4.UInt512(2),\n app_id=app,\n )\n assert result1 == result3\n\n # test again using native result type\n result_native, txn = arc4.abi_call[tuple[String, Bytes, UInt64, BigUInt]](\n \"echo_native_tuple(string,byte[],uint64,uint512)(string,byte[],uint64,uint512)\",\n arc4.String(\"s1\"),\n arc4.DynamicBytes(b\"b1\"),\n arc4.UInt64(1),\n arc4.UInt512(2),\n app_id=app,\n )\n assert result1.native[0].native == result_native[0]\n assert result1.native[1].native == result_native[1]\n assert result1.native[2].native == result_native[2]\n assert result1.native[3].native == result_native[3]\n\n @arc4.abimethod()\n def test_native_tuple_method_ref(self, app: Application) -> None:\n # test with literal args\n result, txn = arc4.abi_call(\n Logger.echo_native_tuple,\n \"s1\",\n b\"b1\",\n 1,\n 2,\n app_id=app,\n )\n (s, b, u, bu) = result\n assert s == \"echo: s1\"\n assert b == b\"echo: b1\"\n assert u == 2\n assert bu == 3\n\n # test with native args\n result_2, txn = arc4.abi_call(\n Logger.echo_native_tuple,\n String(\"s1\"),\n Bytes(b\"b1\"),\n UInt64(1),\n BigUInt(2),\n app_id=app,\n )\n assert result_2 == result, \"expected native arguments to give the same result\"\n\n # test with arc4 args\n result_3, txn = arc4.abi_call(\n Logger.echo_native_tuple,\n arc4.String(\"s1\"),\n arc4.DynamicBytes(b\"b1\"),\n arc4.UInt64(1),\n arc4.UInt512(2),\n app_id=app,\n )\n assert result_3 == result, \"expected arc4 arguments to give the same result\"\n\n # test again using native result type\n result_native, txn = arc4.abi_call[tuple[String, Bytes, UInt64, BigUInt]](\n \"echo_native_tuple(string,byte[],uint64,uint512)(string,byte[],uint64,uint512)\",\n arc4.String(\"s1\"),\n arc4.DynamicBytes(b\"b1\"),\n arc4.UInt64(1),\n arc4.UInt512(2),\n app_id=app,\n )\n assert result_native == result\n\n @arc4.abimethod()\n def test_nested_tuples(self, app: Application) -> None:\n # literal args\n result, txn = arc4.abi_call(\n Logger.echo_nested_tuple,\n ((\"s1\", \"s2\"), (1, 2, b\"3\")),\n app_id=app,\n )\n ((s1, s2), (u64_1, u64_2, bytez)) = result\n assert s1 == \"echo: s1\"\n assert s2 == \"echo: s2\"\n assert u64_1 == 2\n assert u64_2 == 3\n assert bytez == b\"echo: 3\"\n\n # native args\n result, txn = arc4.abi_call(\n Logger.echo_nested_tuple,\n ((String(\"s1\"), arc4.String(\"s2\")), (UInt64(1), arc4.UInt64(2), Bytes(b\"3\"))),\n app_id=app,\n )\n ((s1, s2), (u64_1, u64_2, bytez)) = result\n assert s1 == \"echo: s1\"\n assert s2 == \"echo: s2\"\n assert u64_1 == 2\n assert u64_2 == 3\n assert bytez == b\"echo: 3\"\n\n # arc4 args\n result, txn = arc4.abi_call(\n Logger.echo_nested_tuple,\n arc4.Tuple(\n (\n arc4.Tuple((arc4.String(\"s1b\"), arc4.String(\"s2b\"))),\n arc4.Tuple((arc4.UInt64(11), arc4.UInt64(21), arc4.DynamicBytes(b\"3b\"))),\n )\n ),\n app_id=app,\n )\n ((s1, s2), (u64_1, u64_2, bytez)) = result\n assert s1 == \"echo: s1b\"\n assert s2 == \"echo: s2b\"\n assert u64_1 == 12\n assert u64_2 == 22\n assert bytez == b\"echo: 3b\"\n\n @arc4.abimethod()\n def test_no_args(self, app: Application) -> None:\n result, _txn = arc4.abi_call(Logger.no_args, app_id=app)\n assert result == 42\n arc4_result, _txn = arc4.abi_call[arc4.UInt64](\"no_args()uint64\", app_id=app)\n assert arc4_result == 42\n\n arc4.abi_call(Logger.no_args, app_id=app)\n assert arc4.UInt64.from_log(op.ITxn.last_log()) == 42\n\n @arc4.abimethod()\n def test_named_tuples(self, app: Application) -> None:\n result, _txn = arc4.abi_call(\n Logger.logs_are_equal,\n (UInt64(1), String(\"log 1\")),\n LogMessage(level=UInt64(1), message=String(\"log 1\")),\n app_id=app,\n )\n assert result\n result, _txn = arc4.abi_call(\n Logger.logs_are_equal,\n (UInt64(2), String(\"log 2\")),\n LogMessage(level=UInt64(1), message=String(\"log 1\")),\n app_id=app,\n )\n assert not result\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/typed_abi_call\/typed_c2c.py","language":"Python","license":"NOASSERTION","size":12189} {"code":"from algopy import (\n Application,\n ARC4Contract,\n Bytes,\n UInt64,\n arc4,\n itxn,\n op,\n)\n\nfrom test_cases.typed_abi_call_txn.txn_contract import TxnContract\n\n\nclass Caller(ARC4Contract):\n @arc4.abimethod\n def test_call_with_txn(self, a: Bytes, b: Bytes, app: Application) -> None:\n txn = itxn.AssetConfig(\n unit_name=\"TST\",\n asset_name=\"TEST\",\n total=1,\n )\n asset_id, _txn = arc4.abi_call(\n TxnContract.call_with_txn,\n a,\n txn,\n b,\n app_id=app,\n )\n assert asset_id, \"expected asset id\"\n\n @arc4.abimethod\n def test_call_with_acfg(self, a: Bytes, b: Bytes, app: Application) -> None:\n txn = itxn.AssetConfig(\n unit_name=\"TST\",\n asset_name=\"TEST\",\n total=1,\n )\n arc4.abi_call(\n TxnContract.call_with_acfg,\n a,\n txn,\n b,\n app_id=app,\n )\n\n @arc4.abimethod\n def test_call_with_infer(self, a: Bytes, b: Bytes, app: Application) -> None:\n txn = itxn.AssetConfig(\n unit_name=\"TST\",\n asset_name=\"TEST\",\n total=1,\n )\n arc4.abi_call[UInt64](\n \"call_with_acfg\",\n a,\n txn,\n b,\n app_id=app,\n )\n\n @arc4.abimethod\n def test_call_with_acfg_no_return(self, a: Bytes, b: Bytes, app: Application) -> None:\n acfg = itxn.AssetConfig(\n unit_name=\"TST\",\n asset_name=\"TEST\",\n total=1,\n )\n txn1 = arc4.abi_call(\n TxnContract.call_with_acfg_no_return, a, acfg, b, app_id=app, note=b\"1\"\n )\n assert txn1.note == b\"1\"\n txn1_copy1 = txn1\n assert txn1_copy1.note == txn1.note\n asset_id = op.GITxn.created_asset_id(0)\n assert asset_id, \"expected asset to be created\"\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/typed_abi_call_txn\/caller.py","language":"Python","license":"NOASSERTION","size":1939} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass Caller(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def test_call_with_txn(\n self,\n a: algopy.arc4.DynamicBytes,\n b: algopy.arc4.DynamicBytes,\n app: algopy.Application,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_call_with_acfg(\n self,\n a: algopy.arc4.DynamicBytes,\n b: algopy.arc4.DynamicBytes,\n app: algopy.Application,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_call_with_infer(\n self,\n a: algopy.arc4.DynamicBytes,\n b: algopy.arc4.DynamicBytes,\n app: algopy.Application,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def test_call_with_acfg_no_return(\n self,\n a: algopy.arc4.DynamicBytes,\n b: algopy.arc4.DynamicBytes,\n app: algopy.Application,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/typed_abi_call_txn\/out\/client_Caller.py","language":"Python","license":"NOASSERTION","size":954} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass TxnContract(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def call_with_txn(\n self,\n a: algopy.arc4.DynamicBytes,\n acfg: algopy.gtxn.Transaction,\n b: algopy.arc4.DynamicBytes,\n ) -> algopy.arc4.UIntN[typing.Literal[64]]: ...\n\n @algopy.arc4.abimethod\n def call_with_acfg(\n self,\n a: algopy.arc4.DynamicBytes,\n acfg: algopy.gtxn.AssetConfigTransaction,\n b: algopy.arc4.DynamicBytes,\n ) -> algopy.arc4.UIntN[typing.Literal[64]]: ...\n\n @algopy.arc4.abimethod\n def call_with_acfg_no_return(\n self,\n a: algopy.arc4.DynamicBytes,\n acfg: algopy.gtxn.AssetConfigTransaction,\n b: algopy.arc4.DynamicBytes,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/typed_abi_call_txn\/out\/client_TxnContract.py","language":"Python","license":"NOASSERTION","size":852} {"code":"from algopy import (\n ARC4Contract,\n Bytes,\n TransactionType,\n UInt64,\n arc4,\n gtxn,\n)\n\n\nclass TxnContract(ARC4Contract):\n @arc4.abimethod\n def call_with_txn(self, a: Bytes, acfg: gtxn.Transaction, b: Bytes) -> UInt64:\n assert a == b\"a\", \"a is not a\"\n assert b == b\"b\", \"b is not b\"\n assert acfg.type == TransactionType.AssetConfig, \"expected asset config\"\n assert acfg.created_asset.id, \"expected asset id\"\n return acfg.created_asset.id\n\n @arc4.abimethod\n def call_with_acfg(self, a: Bytes, acfg: gtxn.AssetConfigTransaction, b: Bytes) -> UInt64:\n assert a == b\"a\", \"a is not a\"\n assert b == b\"b\", \"b is not b\"\n assert acfg.created_asset.id, \"expected asset id\"\n return acfg.created_asset.id\n\n @arc4.abimethod\n def call_with_acfg_no_return(\n self, a: Bytes, acfg: gtxn.AssetConfigTransaction, b: Bytes\n ) -> None:\n assert a == b\"a\", \"a is not a\"\n assert b == b\"b\", \"b is not b\"\n assert acfg.created_asset.id, \"expected asset id\"\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/typed_abi_call_txn\/txn_contract.py","language":"Python","license":"NOASSERTION","size":1060} {"code":"from algopy import (\n BigUInt,\n Bytes,\n Contract,\n UInt64,\n subroutine,\n)\n\nMAX_UINT64 = 2**64 - 1\nMAX_BIGUINT = 2**512 - 1\n\n\nclass UnaryContract(Contract):\n def approval_program(self) -> bool:\n uint_unary()\n biguint_unary()\n bytes_unary()\n\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n\n@subroutine\ndef uint_unary() -> None:\n # test not\n assert not UInt64(0), \"not uint\"\n\n # test ~\n for i in (UInt64(1), UInt64(2), UInt64(150), UInt64(MAX_UINT64)):\n assert ~(MAX_UINT64 - i) == i, \"~ uint\"\n\n\n@subroutine\ndef biguint_unary() -> None:\n # test not\n assert not BigUInt(0), \"not biguint\"\n\n\n@subroutine\ndef bytes_unary() -> None:\n # test not\n assert not Bytes(b\"\"), \"not bytes\"\n\n # test ~\n assert ~Bytes.from_hex(\"FF\") == Bytes.from_hex(\"00\"), \"~ bytes\"\n assert ~Bytes.from_hex(\"0000\") == Bytes.from_hex(\"FFFF\"), \"~ bytes\"\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/unary\/contract.py","language":"Python","license":"NOASSERTION","size":935} {"code":"from algopy import ARC4Contract, Bytes, UInt64, arc4, op, subroutine\n\n\nclass Unassigned(ARC4Contract):\n @arc4.abimethod()\n def discard_op(self) -> None:\n op.bzero(10)\n\n @arc4.abimethod()\n def discard_subroutine(self) -> None:\n get_a_value()\n\n @arc4.abimethod()\n def discard_constants(self) -> None:\n Bytes()\n UInt64()\n True # noqa: B018\n\n\n@subroutine\ndef get_a_value() -> UInt64:\n return UInt64(42)\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/unassigned_expression\/contract.py","language":"Python","license":"NOASSERTION","size":456} {"code":"# This file is auto-generated, do not modify\n# flake8: noqa\n# fmt: off\nimport typing\n\nimport algopy\n\n\nclass Unassigned(algopy.arc4.ARC4Client, typing.Protocol):\n @algopy.arc4.abimethod\n def discard_op(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def discard_subroutine(\n self,\n ) -> None: ...\n\n @algopy.arc4.abimethod\n def discard_constants(\n self,\n ) -> None: ...\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/unassigned_expression\/out\/client_Unassigned.py","language":"Python","license":"NOASSERTION","size":418} {"code":"from algopy import BigUInt, Contract, UInt64, op, subroutine\n\n\nclass Baddie(Contract):\n def approval_program(self) -> bool:\n test_case = op.Txn.application_args(0)\n invert_second_condition = (\n op.Txn.num_app_args > 1 and op.btoi(op.Txn.application_args(1)) > 0\n )\n\n if invert_second_condition:\n if test_case == b\"uint\":\n assert test_uint_undefined(True, False) == 10\n assert test_uint_undefined(False, True) == 8 # should fail\n elif test_case == b\"bytes\":\n assert test_bytes_undefined(True, False) == 10\n assert test_bytes_undefined(False, True) == 8 # should fail\n else:\n assert test_mixed_undefined(True, False) == 10\n assert test_mixed_undefined(False, True) == 8 # should fail\n else: # noqa: PLR5501\n if test_case == b\"uint\":\n assert test_uint_undefined(True, True) == 8\n assert test_uint_undefined(False, False) == 10\n elif test_case == b\"bytes\":\n assert test_bytes_undefined(True, True) == 8\n assert test_bytes_undefined(False, False) == 10\n else:\n assert test_mixed_undefined(True, True) == 8\n assert test_mixed_undefined(False, False) == 10\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n\n@subroutine\ndef test_uint_undefined(x: bool, y: bool) -> UInt64:\n if x:\n a = UInt64(7)\n if x:\n b = UInt64(11)\n else:\n b = UInt64(11)\n if y:\n c = a + 1 # \ud83d\udca5\n else:\n c = b - 1\n return c\n\n\n@subroutine\ndef test_bytes_undefined(x: bool, y: bool) -> BigUInt:\n if x:\n a = BigUInt(7)\n if x:\n b = BigUInt(11)\n else:\n b = BigUInt(11)\n if y:\n c = a + 1 # \ud83d\udca5\n else:\n c = b - 1\n return c\n\n\n@subroutine\ndef test_mixed_undefined(x: bool, y: bool) -> BigUInt:\n if x:\n a = UInt64(7)\n if x:\n b = BigUInt(11)\n else:\n b = BigUInt(11)\n if y:\n c = BigUInt(a) + BigUInt(1) # \ud83d\udca5\n else:\n c = b - 1\n return c\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/undefined_phi_args\/baddie.py","language":"Python","license":"NOASSERTION","size":2186} {"code":"from algopy import Contract, UInt64, log, op, subroutine, urange\n\n\nclass UnSSAContract(Contract):\n def approval_program(self) -> bool:\n test_self_ref_phi()\n result1 = test_swap(UInt64(1))\n log(op.itob(result1))\n assert 1 <= result1 <= 2\n result2 = test_swap(UInt64(2))\n log(op.itob(result2))\n assert 1 <= result2 <= 2\n test_swap_loop(UInt64(7), UInt64(11))\n assert test_param_update_with_reentrant_entry_block(UInt64(0)) == 10\n test_param_update_with_reentrant_entry_block_v2(UInt64(0))\n test_param_update_with_reentrant_entry_block_v3()\n test_swap_args()\n\n (a, b) = test_tuple_swap(UInt64(100), UInt64(200), UInt64(0))\n assert a == UInt64(100)\n assert b == UInt64(200)\n (a, b) = test_tuple_swap(UInt64(100), UInt64(200), UInt64(1))\n assert a == UInt64(200)\n assert b == UInt64(100)\n\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n\n@subroutine\ndef test_self_ref_phi() -> UInt64:\n a = UInt64(1)\n while a < 100:\n if a % 105 == 0:\n continue\n if not a % 21:\n break\n a += 1\n return a\n\n\n@subroutine\ndef test_swap(i: UInt64) -> UInt64:\n x = UInt64(1)\n y = UInt64(2)\n while i > 0:\n tmp = x\n x = y\n y = tmp\n i = i - 1\n return x\n\n\n@subroutine\ndef test_swap_loop(i: UInt64, j: UInt64) -> UInt64:\n x = UInt64(1)\n y = UInt64(2)\n while i > 0:\n while j > 0:\n tmp = x\n x = y\n y = tmp\n j = j - 1\n i = i - 1\n return x\n\n\n@subroutine\ndef test_tuple_swap(a: UInt64, b: UInt64, i: UInt64) -> tuple[UInt64, UInt64]:\n for _item in urange(i):\n (a, b) = (b, a)\n return a, b\n\n\n@subroutine\ndef test_param_update_with_reentrant_entry_block(x: UInt64) -> UInt64:\n while True:\n x = x + 1\n if x >= 10:\n break\n return x\n\n\n@subroutine\ndef test_param_update_with_reentrant_entry_block_v2(x: UInt64) -> UInt64:\n x = x + 1\n while True:\n if x >= 1:\n break\n return x\n\n\n@subroutine\ndef test_param_update_with_reentrant_entry_block_v3() -> None:\n while True:\n if one():\n break\n\n\n@subroutine\ndef one() -> UInt64:\n return UInt64(1)\n\n\n@subroutine\ndef swap_args(a: UInt64, b: UInt64) -> tuple[UInt64, UInt64]:\n return b, a\n\n\n@subroutine\ndef test_swap_args() -> None:\n a = one() + 123\n b = one() + 234\n a, b = swap_args(a, b)\n assert a == 235, \"a == 235\"\n assert b == 124, \"b = 124\"\n\n\n# TODO: lost copy problem example\/test\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/unssa\/contract.py","language":"Python","license":"NOASSERTION","size":2620} {"code":"from algopy import Bytes, Contract, UInt64, log, op, subroutine\n\n\nclass WithReentrancy(Contract):\n \"\"\"My re-entrant contract\"\"\"\n\n def approval_program(self) -> bool:\n log(op.itob(fibonacci(UInt64(5))))\n silly(UInt64(2))\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n\n@subroutine\ndef itoa(i: UInt64) -> Bytes:\n digits = Bytes(b\"0123456789\")\n radix = digits.length\n if i < radix:\n return digits[i]\n return itoa(i \/\/ radix) + digits[i % radix]\n\n\n@subroutine\ndef fibonacci(n: UInt64) -> UInt64:\n if n <= 1:\n return n\n return fibonacci(n - 1) + fibonacci(n - 2)\n\n\n@subroutine\ndef silly(x: UInt64) -> UInt64:\n x = x + 1\n result = silly2(x)\n log(Bytes(b\"silly = \") + itoa(x))\n return result\n\n\n@subroutine\ndef silly2(x: UInt64) -> UInt64:\n x = x + 2\n result = silly3(x)\n log(Bytes(b\"silly2 = \") + itoa(x))\n return result\n\n\n@subroutine\ndef silly3(x: UInt64) -> UInt64:\n is_even = x % 2 == 0\n a = x + 2\n if is_even:\n result = a * 2\n a = result \/\/ 2 - 2\n else:\n result = silly(x)\n\n if is_even:\n result = a\n log(Bytes(b\"silly3 = \") + itoa(x))\n return result\n","repo_name":"algorandfoundation\/puya","path":"test_cases\/with_reentrancy\/contract.py","language":"Python","license":"NOASSERTION","size":1210} {"code":"from pathlib import Path\n\nVCS_ROOT = Path(__file__).parent.parent\nEXAMPLES_DIR = VCS_ROOT \/ \"examples\"\nTEST_CASES_DIR = VCS_ROOT \/ \"test_cases\"\n","repo_name":"algorandfoundation\/puya","path":"tests\/__init__.py","language":"Python","license":"NOASSERTION","size":144} {"code":"from random import randbytes\n\nimport pytest\nfrom _pytest.mark import ParameterSet\nfrom algokit_utils import (\n Account,\n get_algod_client,\n get_default_localnet_config,\n get_localnet_default_account,\n)\nfrom algosdk import transaction\nfrom algosdk.atomic_transaction_composer import AtomicTransactionComposer, TransactionWithSigner\nfrom algosdk.v2client.algod import AlgodClient\n\nfrom puya import log\nfrom tests import EXAMPLES_DIR, TEST_CASES_DIR\nfrom tests.utils import PuyaTestCase\n\n\ndef pytest_generate_tests(metafunc: pytest.Metafunc) -> None:\n # parametrize `test_case: PuyaTestCase` based on test cases in examples and test_cases dirs\n if \"test_case\" in metafunc.fixturenames:\n # only parametrize if not already parametrized\n mark = metafunc.definition.get_closest_marker(\"parametrize\")\n if not mark or \"test_case\" not in mark.args[0]:\n params = [\n ParameterSet.param(\n PuyaTestCase(item),\n marks=[pytest.mark.slow] if item.name == \"stress_tests\" else [],\n )\n for root in (EXAMPLES_DIR, TEST_CASES_DIR)\n for item in root.iterdir()\n if item.is_dir() and not item.name.startswith((\".\", \"_\"))\n ]\n metafunc.parametrize(\"test_case\", params, ids=lambda t: t.id)\n\n\n@pytest.fixture(autouse=True, scope=\"session\")\ndef _setup_logging() -> None:\n # configure logging for tests\n # note cache_logger should be False if calling configure_logging more than once\n log.configure_logging(min_log_level=log.LogLevel.info, cache_logger=False)\n\n\n@pytest.fixture(scope=\"session\")\ndef algod_client() -> AlgodClient:\n return get_algod_client(get_default_localnet_config(\"algod\"))\n\n\n@pytest.fixture(scope=\"session\")\ndef account(algod_client: AlgodClient) -> Account:\n return get_localnet_default_account(algod_client)\n\n\n@pytest.fixture(scope=\"session\")\ndef asset_a(algod_client: AlgodClient, account: Account) -> int:\n return _create_asset(algod_client, account, \"a\")\n\n\n@pytest.fixture(scope=\"session\")\ndef asset_b(algod_client: AlgodClient, account: Account) -> int:\n return _create_asset(algod_client, account, \"b\")\n\n\ndef _create_asset(algod_client: AlgodClient, account: Account, asset_unit: str) -> int:\n sp = algod_client.suggested_params()\n atc = AtomicTransactionComposer()\n atc.add_transaction(\n TransactionWithSigner(\n transaction.AssetCreateTxn(\n account.address,\n sp,\n 10_000_000,\n 0,\n default_frozen=False,\n asset_name=f\"asset {asset_unit}\",\n unit_name=asset_unit,\n note=randbytes(8),\n ),\n signer=account.signer,\n )\n )\n response = atc.execute(algod_client, 4)\n txn_id = response.tx_ids[0]\n result = algod_client.pending_transaction_info(txn_id)\n assert isinstance(result, dict)\n asset_index = result[\"asset-index\"]\n assert isinstance(asset_index, int)\n return asset_index\n","repo_name":"algorandfoundation\/puya","path":"tests\/conftest.py","language":"Python","license":"NOASSERTION","size":3071} {"code":"import math\nimport random\nfrom pathlib import Path\n\nimport algokit_utils\nimport algokit_utils.config\nimport algosdk\nimport pytest\nfrom algokit_utils import LogicError\nfrom algosdk import abi, constants, transaction\nfrom algosdk.atomic_transaction_composer import AtomicTransactionComposer, TransactionWithSigner\nfrom algosdk.transaction import OnComplete\nfrom algosdk.v2client.algod import AlgodClient\nfrom nacl.signing import SigningKey\n\nfrom puya.arc32 import create_arc32_json\nfrom puya.compilation_artifacts import CompiledContract\nfrom puyapy.options import PuyaPyOptions\nfrom tests import EXAMPLES_DIR, TEST_CASES_DIR\nfrom tests.test_execution import decode_logs\nfrom tests.utils import compile_src_from_options\nfrom tests.utils.merkle_tree import MerkleTree, sha_256_raw\n\npytestmark = pytest.mark.localnet\n\n\ndef compile_arc32(\n src_path: Path,\n *,\n optimization_level: int = 1,\n debug_level: int = 2,\n file_name: str | None = None,\n) -> str:\n result = compile_src_from_options(\n PuyaPyOptions(\n paths=(src_path,),\n optimization_level=optimization_level,\n debug_level=debug_level,\n )\n )\n if file_name is None:\n (contract,) = result.teal\n else:\n (contract,) = (\n t\n for t in result.teal\n if isinstance(t, CompiledContract)\n if (\n t.source_location\n and t.source_location.file\n and t.source_location.file.name == file_name\n )\n )\n\n assert isinstance(contract, CompiledContract), \"Compilation artifact must be a contract\"\n return create_arc32_json(\n contract.approval_program.teal_src, contract.clear_program.teal_src, contract.metadata\n )\n\n\ndef token_balances(\n app_client: algokit_utils.ApplicationClient,\n account: algokit_utils.Account,\n pool_token: int,\n asset_a: int,\n asset_b: int,\n) -> dict[str, dict[str, int] | int]:\n account_info = app_client.algod_client.account_info(account.address)\n assert isinstance(account_info, dict)\n\n account_balances = {}\n for asset in account_info[\"assets\"]:\n if asset[\"asset-id\"] == pool_token:\n account_balances[\"pool\"] = asset[\"amount\"]\n if asset[\"asset-id\"] == asset_a:\n account_balances[\"asset_a\"] = asset[\"amount\"]\n if asset[\"asset-id\"] == asset_b:\n account_balances[\"asset_b\"] = asset[\"amount\"]\n\n app_account_info = app_client.algod_client.account_info(app_client.app_address)\n assert isinstance(app_account_info, dict)\n\n app_balances = {}\n for asset in app_account_info[\"assets\"]:\n if asset[\"asset-id\"] == pool_token:\n app_balances[\"pool\"] = asset[\"amount\"]\n if asset[\"asset-id\"] == asset_a:\n app_balances[\"asset_a\"] = asset[\"amount\"]\n if asset[\"asset-id\"] == asset_b:\n app_balances[\"asset_b\"] = asset[\"amount\"]\n\n state = app_client.get_global_state()\n ratio = state[\"ratio\"]\n assert isinstance(ratio, int)\n return {\"account\": account_balances, \"app\": app_balances, \"ratio\": ratio}\n\n\ndef test_amm(\n algod_client: AlgodClient,\n account: algokit_utils.Account,\n asset_a: int,\n asset_b: int,\n) -> None:\n example = EXAMPLES_DIR \/ \"amm\"\n app_spec = algokit_utils.ApplicationSpecification.from_json(compile_arc32(example))\n app_client = algokit_utils.ApplicationClient(algod_client, app_spec, signer=account)\n\n # create\n create_response = app_client.create()\n assert create_response.confirmed_round\n\n pay_txn = TransactionWithSigner(\n transaction.PaymentTxn(\n sender=account.address,\n receiver=app_client.app_address,\n amt=int(1e7),\n sp=algod_client.suggested_params(),\n ),\n signer=account.signer,\n )\n sp = algod_client.suggested_params()\n sp.flat_fee = True\n sp.fee = 4_000\n\n # bootstrap\n bootstrap_response = app_client.call(\n \"bootstrap\",\n transaction_parameters=algokit_utils.OnCompleteCallParameters(suggested_params=sp),\n seed=pay_txn,\n a_asset=asset_a,\n b_asset=asset_b,\n )\n pool_token = bootstrap_response.return_value\n assert token_balances(app_client, account, pool_token, asset_a, asset_b) == {\n \"account\": {\n \"asset_a\": 10_000_000,\n \"asset_b\": 10_000_000,\n },\n \"app\": {\n \"asset_a\": 0,\n \"asset_b\": 0,\n \"pool\": 10_000_000_000,\n },\n \"ratio\": 0,\n }\n\n # pool_id should be newer than asset a + b\n assert pool_token > asset_a\n assert pool_token > asset_b\n\n # opt user into tokens\n # fund user account with assets a & b\n sp = algod_client.suggested_params()\n atc = AtomicTransactionComposer()\n atc.add_transaction(\n TransactionWithSigner(\n txn=transaction.AssetTransferTxn(account.address, sp, account.address, 0, asset_a),\n signer=account.signer,\n )\n )\n atc.add_transaction(\n TransactionWithSigner(\n txn=transaction.AssetTransferTxn(account.address, sp, account.address, 0, asset_b),\n signer=account.signer,\n )\n )\n atc.add_transaction(\n TransactionWithSigner(\n txn=transaction.AssetTransferTxn(account.address, sp, account.address, 0, pool_token),\n signer=account.signer,\n )\n )\n atc.execute(algod_client, wait_rounds=1)\n\n # mint\n sp = algod_client.suggested_params()\n sp.flat_fee = True\n sp.fee = 3_000\n\n app_client.call(\n \"mint\",\n a_xfer=TransactionWithSigner(\n txn=transaction.AssetTransferTxn(\n account.address, sp, app_client.app_address, 10_000, asset_a\n ),\n signer=account.signer,\n ),\n b_xfer=TransactionWithSigner(\n txn=transaction.AssetTransferTxn(\n account.address, sp, app_client.app_address, 3000, asset_b\n ),\n signer=account.signer,\n ),\n transaction_parameters=algokit_utils.OnCompleteCallParameters(suggested_params=sp),\n )\n assert token_balances(app_client, account, pool_token, asset_a, asset_b) == {\n \"account\": {\n \"asset_a\": 9_990_000,\n \"asset_b\": 9_997_000,\n \"pool\": 4_477,\n },\n \"app\": {\n \"asset_a\": 10_000,\n \"asset_b\": 3_000,\n \"pool\": 9_999_995_523,\n },\n \"ratio\": 3_333,\n }\n\n app_client.call(\n \"mint\",\n a_xfer=TransactionWithSigner(\n txn=transaction.AssetTransferTxn(\n account.address, sp, app_client.app_address, 100_000, asset_a\n ),\n signer=account.signer,\n ),\n b_xfer=TransactionWithSigner(\n txn=transaction.AssetTransferTxn(\n account.address, sp, app_client.app_address, 1_000, asset_b\n ),\n signer=account.signer,\n ),\n transaction_parameters=algokit_utils.OnCompleteCallParameters(suggested_params=sp),\n )\n assert token_balances(app_client, account, pool_token, asset_a, asset_b) == {\n \"account\": {\n \"asset_a\": 9_890_000,\n \"asset_b\": 9_996_000,\n \"pool\": 5_967,\n },\n \"app\": {\n \"asset_a\": 110_000,\n \"asset_b\": 4_000,\n \"pool\": 9_999_994_033,\n },\n \"ratio\": 27_500,\n }\n\n # swap\n app_client.call(\n \"swap\",\n swap_xfer=TransactionWithSigner(\n txn=transaction.AssetTransferTxn(\n account.address, sp, app_client.app_address, 500, asset_a\n ),\n signer=account.signer,\n ),\n )\n assert token_balances(app_client, account, pool_token, asset_a, asset_b) == {\n \"account\": {\n \"asset_a\": 9_903_252,\n \"asset_b\": 9_996_000,\n \"pool\": 5_967,\n },\n \"app\": {\n \"asset_a\": 96_748,\n \"asset_b\": 4_000,\n \"pool\": 9_999_994_033,\n },\n \"ratio\": 24_187,\n }\n\n app_client.call(\n \"swap\",\n swap_xfer=TransactionWithSigner(\n txn=transaction.AssetTransferTxn(\n account.address, sp, app_client.app_address, 500, asset_b\n ),\n signer=account.signer,\n ),\n )\n assert token_balances(app_client, account, pool_token, asset_a, asset_b) == {\n \"account\": {\n \"asset_a\": 9_903_252,\n \"asset_b\": 9_995_523,\n \"pool\": 5_967,\n },\n \"app\": {\n \"asset_a\": 96_748,\n \"asset_b\": 4_477,\n \"pool\": 9_999_994_033,\n },\n \"ratio\": 21_610,\n }\n\n # burn\n app_client.call(\n \"burn\",\n pool_xfer=TransactionWithSigner(\n txn=transaction.AssetTransferTxn(\n account.address, sp, app_client.app_address, 100, pool_token\n ),\n signer=account.signer,\n ),\n )\n assert token_balances(app_client, account, pool_token, asset_a, asset_b) == {\n \"account\": {\n \"asset_a\": 9_904_929,\n \"asset_b\": 9_995_600,\n \"pool\": 5_867,\n },\n \"app\": {\n \"asset_a\": 95_071,\n \"asset_b\": 4_400,\n \"pool\": 9_999_994_133,\n },\n \"ratio\": 21_607,\n }\n\n\n@pytest.fixture\ndef voter_account(algod_client: AlgodClient) -> algokit_utils.Account:\n v = algosdk.account.generate_account()\n voter_account = algokit_utils.Account(private_key=v[0], address=v[1])\n algokit_utils.transfer(\n client=algod_client,\n parameters=algokit_utils.TransferParameters(\n from_account=algokit_utils.get_localnet_default_account(algod_client),\n to_address=voter_account.address,\n micro_algos=10000000,\n ),\n )\n return voter_account\n\n\ndef suggested_params(\n *, algod_client: AlgodClient, fee: int | None = None, flat_fee: bool | None = None\n) -> algosdk.transaction.SuggestedParams:\n sp = algod_client.suggested_params()\n\n if fee is not None:\n sp.fee = fee\n if flat_fee is not None:\n sp.flat_fee = flat_fee\n\n return sp\n\n\ndef payment_transaction(\n *,\n algod_client: AlgodClient,\n amount: int,\n receiver: str,\n sender: algokit_utils.Account,\n note: bytes | None = None,\n) -> TransactionWithSigner:\n return TransactionWithSigner(\n txn=algosdk.transaction.PaymentTxn(\n sender=sender.address,\n receiver=receiver,\n amt=amount,\n note=note,\n sp=suggested_params(algod_client=algod_client),\n ),\n signer=sender.signer,\n )\n\n\ndef test_voting_app(\n algod_client: AlgodClient,\n account: algokit_utils.Account,\n voter_account: algokit_utils.Account,\n) -> None:\n creator_account = account\n\n private_key = SigningKey.generate()\n\n example = EXAMPLES_DIR \/ \"voting\"\n app_spec = algokit_utils.ApplicationSpecification.from_json(compile_arc32(example))\n app_client = algokit_utils.ApplicationClient(algod_client, app_spec, signer=creator_account)\n\n quorum = math.ceil(random.randint(1, 9) * 1000)\n question_counts = [1] * 10\n\n health = algod_client.status()\n assert isinstance(health, dict)\n response = algod_client.block_info(health[\"last-round\"])\n assert isinstance(response, dict)\n block = response[\"block\"]\n block_ts = block[\"ts\"]\n app_client.create(\n \"create\",\n vote_id=\"1\",\n metadata_ipfs_cid=\"cid\",\n start_time=int(block_ts),\n end_time=int(block_ts) + 1000,\n quorum=quorum,\n snapshot_public_key=private_key.verify_key.encode(),\n nft_image_url=\"ipfs:\/\/cid\",\n option_counts=question_counts,\n )\n\n app_client.call(\n call_abi_method=\"bootstrap\",\n transaction_parameters=algokit_utils.OnCompleteCallParameters(boxes=[(0, \"V\")]),\n fund_min_bal_req=payment_transaction(\n algod_client=algod_client,\n amount=(100000 * 2) + 1000 + 2500 + 400 * (1 + 8 * 10),\n sender=creator_account,\n note=b\"Bootstrap payment\",\n receiver=app_client.app_address,\n ),\n )\n\n def get_account_signature(voter_public_key: bytes) -> bytes:\n signed = private_key.sign(voter_public_key)\n return signed.signature\n\n pre_conditions = app_client.call(\n call_abi_method=\"get_preconditions\",\n transaction_parameters=algokit_utils.OnCompleteCallParameters(\n sender=voter_account.address,\n signer=voter_account.signer,\n boxes=[(0, voter_account.public_key)],\n suggested_params=suggested_params(algod_client=algod_client, fee=4000),\n ),\n signature=get_account_signature(voter_account.public_key),\n )\n (is_open, can_vote, has_voted, _time) = pre_conditions.return_value\n assert is_open\n assert can_vote\n assert not has_voted\n\n app_client.call(\n call_abi_method=\"vote\",\n transaction_parameters=algokit_utils.OnCompleteCallParameters(\n boxes=[(0, \"V\"), (0, voter_account.public_key)],\n sender=voter_account.address,\n signer=voter_account.signer,\n suggested_params=suggested_params(algod_client=algod_client, fee=12000, flat_fee=True),\n ),\n answer_ids=[0] * 10,\n fund_min_bal_req=payment_transaction(\n algod_client=algod_client,\n amount=400 * (32 + 2 + 10) + 2500,\n sender=voter_account,\n note=b\"Vote payment\",\n receiver=app_client.app_address,\n ),\n signature=get_account_signature(voter_account.public_key),\n )\n\n pre_conditions = app_client.call(\n call_abi_method=\"get_preconditions\",\n transaction_parameters=algokit_utils.OnCompleteCallParameters(\n sender=voter_account.address,\n signer=voter_account.signer,\n boxes=[(0, voter_account.public_key)],\n suggested_params=suggested_params(algod_client=algod_client, fee=4000),\n ),\n signature=get_account_signature(voter_account.public_key),\n )\n (is_open, can_vote, has_voted, _time) = pre_conditions.return_value\n assert is_open\n assert can_vote\n assert has_voted\n\n app_client.call(\n call_abi_method=\"close\",\n transaction_parameters=algokit_utils.OnCompleteCallParameters(\n boxes=[(0, \"V\")],\n sender=creator_account.address,\n signer=creator_account.signer,\n suggested_params=suggested_params(\n algod_client=algod_client, fee=1000000, flat_fee=True\n ),\n ),\n )\n\n pre_conditions = app_client.call(\n call_abi_method=\"get_preconditions\",\n transaction_parameters=algokit_utils.OnCompleteCallParameters(\n boxes=[(0, account.public_key)],\n suggested_params=suggested_params(algod_client=algod_client, fee=4000),\n ),\n signature=get_account_signature(voter_account.public_key),\n )\n (is_open, _can_vote, _has_voted, _time) = pre_conditions.return_value\n assert not is_open\n\n\ndef test_arc4_routing(\n algod_client: AlgodClient,\n account: algokit_utils.Account,\n) -> None:\n app_spec = algokit_utils.ApplicationSpecification.from_json(\n compile_arc32(TEST_CASES_DIR \/ \"abi_routing\" \/ \"contract.py\")\n )\n app_client = algokit_utils.ApplicationClient(algod_client, app_spec, signer=account)\n\n # create\n create_response = app_client.create()\n assert create_response.confirmed_round\n\n app_client.call(\"method_with_default_args\")\n\n hello_result = app_client.call(\"hello_with_algopy_string\", name=\"Algopy\")\n assert hello_result.return_value == \"Hello Algopy!\"\n\n\ndef test_arc4_routing_with_many_params(\n algod_client: AlgodClient,\n account: algokit_utils.Account,\n asset_a: int,\n asset_b: int,\n) -> None:\n app_spec = algokit_utils.ApplicationSpecification.from_json(\n compile_arc32(TEST_CASES_DIR \/ \"abi_routing\" \/ \"contract.py\")\n )\n app_client = algokit_utils.ApplicationClient(algod_client, app_spec, signer=account)\n\n # create\n create_response = app_client.create()\n assert create_response.confirmed_round\n\n result = app_client.call(\n \"method_with_more_than_15_args\",\n a=1,\n b=1,\n c=1,\n d=1,\n e=1,\n f=1,\n g=1,\n h=1,\n i=1,\n j=1,\n k=1,\n l=1,\n m=1,\n n=1,\n o=1,\n p=1,\n q=1,\n r=1,\n s=b\"a\",\n t=b\"b\",\n u=1,\n v=1,\n pay=payment_transaction(\n algod_client=algod_client,\n amount=100000,\n sender=account,\n note=b\"Test 1\",\n receiver=app_client.app_address,\n ),\n pay2=payment_transaction(\n algod_client=algod_client,\n amount=200000,\n sender=account,\n note=b\"Test 2\",\n receiver=app_client.app_address,\n ),\n asset=asset_a,\n asset2=asset_b,\n )\n assert result.return_value == 20\n\n (logged_string,) = decode_logs(result.tx_info[\"logs\"][:-1], \"u\")\n assert logged_string == \"ab\"\n\n result2 = app_client.call(\n \"method_with_15_args\",\n one=1,\n two=1,\n three=1,\n four=1,\n five=1,\n six=1,\n seven=1,\n eight=1,\n nine=1,\n ten=1,\n eleven=1,\n twelve=1,\n thirteen=1,\n fourteen=1,\n fifteen=b\"fifteen\",\n )\n assert result2.return_value == list(b\"fifteen\")\n\n\ndef test_transaction(algod_client: AlgodClient, account: algokit_utils.Account) -> None:\n app_spec = algokit_utils.ApplicationSpecification.from_json(\n compile_arc32(TEST_CASES_DIR \/ \"transaction\")\n )\n app_client = algokit_utils.ApplicationClient(algod_client, app_spec, signer=account)\n\n # create\n create_response = app_client.create()\n assert create_response.confirmed_round\n\n # ensure app meets minimum balance requirements\n algokit_utils.ensure_funded(\n algod_client,\n algokit_utils.EnsureBalanceParameters(\n account_to_fund=app_client.app_address,\n min_spending_balance_micro_algos=100_000,\n ),\n )\n\n app_client.call(\n \"pay\",\n txn=TransactionWithSigner(\n transaction.PaymentTxn(\n sender=account.address,\n receiver=app_client.app_address,\n amt=1001,\n sp=algod_client.suggested_params(),\n ),\n signer=account.signer,\n ),\n )\n\n # TODO: call remaining transaction methods\n\n\ndef test_dynamic_array_of_string(\n algod_client: AlgodClient,\n account: algokit_utils.Account,\n) -> None:\n app_spec = algokit_utils.ApplicationSpecification.from_json(\n compile_arc32(TEST_CASES_DIR \/ \"arc4_types\/dynamic_string_array.py\")\n )\n app_client = algokit_utils.ApplicationClient(algod_client, app_spec, signer=account)\n\n create_response = app_client.create()\n assert create_response.confirmed_round\n\n xyz_result = app_client.call(\"xyz\")\n assert xyz_result.return_value == list(\"XYZ\")\n\n xyz_raw_result = app_client.call(\"xyz_raw\")\n assert xyz_raw_result.return_value == list(\"XYZ\")\n\n\ndef test_array_rebinding(\n algod_client: AlgodClient,\n account: algokit_utils.Account,\n) -> None:\n app_spec = algokit_utils.ApplicationSpecification.from_json(\n compile_arc32(TEST_CASES_DIR \/ \"arc4_types\/mutable_params2.py\")\n )\n app_client = algokit_utils.ApplicationClient(algod_client, app_spec, signer=account)\n\n create_response = app_client.create()\n assert create_response.confirmed_round\n\n app_client.call(\"test_array_rebinding\")\n\n\ndef test_avm_types_in_abi(algod_client: AlgodClient, account: algokit_utils.Account) -> None:\n example = TEST_CASES_DIR \/ \"avm_types_in_abi\" \/ \"contract.py\"\n app_spec = algokit_utils.ApplicationSpecification.from_json(compile_arc32(example))\n app_client = algokit_utils.ApplicationClient(algod_client, app_spec, signer=account)\n max_biguint = 2**512 - 1\n result = app_client.create(\n \"create\",\n bool_param=True,\n uint64_param=45,\n bytes_param=b\"Hello world!\",\n biguint_param=max_biguint,\n string_param=\"Hi again\",\n tuple_param=(True, 45, b\"Hello world!\", max_biguint, \"Hi again\"),\n )\n\n mapped_return = (\n result.return_value[0],\n result.return_value[1],\n bytes(result.return_value[2]),\n result.return_value[3],\n result.return_value[4],\n )\n\n assert mapped_return == (True, 45, b\"Hello world!\", max_biguint, \"Hi again\")\n\n result2 = app_client.call(call_abi_method=\"tuple_of_arc4\", args=(255, account.address))\n\n assert result2.return_value[0] == 255\n assert result2.return_value[1] == account.address\n\n\ndef test_inner_transactions_c2c(algod_client: AlgodClient, account: algokit_utils.Account) -> None:\n example = TEST_CASES_DIR \/ \"inner_transactions\" \/ \"c2c.py\"\n app_spec = algokit_utils.ApplicationSpecification.from_json(compile_arc32(example))\n\n # deploy greeter\n increased_fee = algod_client.suggested_params()\n increased_fee.flat_fee = True\n increased_fee.fee = constants.min_txn_fee * 2\n app_client = algokit_utils.ApplicationClient(\n algod_client, app_spec, signer=account, suggested_params=increased_fee\n )\n app_client.create()\n\n algokit_utils.ensure_funded(\n algod_client,\n algokit_utils.EnsureBalanceParameters(\n account_to_fund=app_client.app_address,\n min_spending_balance_micro_algos=100_000,\n ),\n )\n inner_app_id = app_client.call(\"bootstrap\").return_value\n assert isinstance(inner_app_id, int)\n\n result = app_client.call(\n \"log_greetings\",\n name=\"There\",\n transaction_parameters={\"foreign_apps\": [inner_app_id]},\n )\n assert decode_logs(result.tx_info[\"logs\"], \"b\") == [b\"HelloWorld returned: Hello, There\"]\n\n\ndef test_inner_transactions_array_access(\n algod_client: AlgodClient, account: algokit_utils.Account\n) -> None:\n example = TEST_CASES_DIR \/ \"inner_transactions\" \/ \"array_access.py\"\n app_spec = algokit_utils.ApplicationSpecification.from_json(compile_arc32(example))\n\n # deploy greeter\n increased_fee = algod_client.suggested_params()\n increased_fee.flat_fee = True\n increased_fee.fee = constants.min_txn_fee * 2\n app_client = algokit_utils.ApplicationClient(\n algod_client, app_spec, signer=account, suggested_params=increased_fee\n )\n app_client.create()\n\n algokit_utils.ensure_funded(\n algod_client,\n algokit_utils.EnsureBalanceParameters(\n account_to_fund=app_client.app_address,\n min_spending_balance_micro_algos=200_000,\n ),\n )\n\n app_client.call(\"test_branching_array_call\", maybe=True)\n app_client.call(\"test_branching_array_call\", maybe=False)\n\n\ndef test_inner_transactions_tuple(\n algod_client: AlgodClient, account: algokit_utils.Account\n) -> None:\n example = TEST_CASES_DIR \/ \"inner_transactions\" \/ \"field_tuple_assignment.py\"\n app_spec = algokit_utils.ApplicationSpecification.from_json(compile_arc32(example))\n\n increased_fee = algod_client.suggested_params()\n increased_fee.flat_fee = True\n increased_fee.fee = constants.min_txn_fee * 7\n app_client = algokit_utils.ApplicationClient(\n algod_client, app_spec, signer=account, suggested_params=increased_fee\n )\n app_client.create()\n\n app_client.call(\"test_assign_tuple\")\n app_client.call(\"test_assign_tuple_mixed\")\n\n\ndef test_inner_transactions_asset_transfer(\n algod_client: AlgodClient, account: algokit_utils.Account\n) -> None:\n example = TEST_CASES_DIR \/ \"inner_transactions\" \/ \"asset_transfer.py\"\n app_spec = algokit_utils.ApplicationSpecification.from_json(compile_arc32(example))\n\n # deploy\n increased_fee = algod_client.suggested_params()\n increased_fee.flat_fee = True\n increased_fee.fee = constants.min_txn_fee * 3\n app_client = algokit_utils.ApplicationClient(\n algod_client, app_spec, signer=account, suggested_params=increased_fee\n )\n app_client.create()\n\n algokit_utils.ensure_funded(\n algod_client,\n algokit_utils.EnsureBalanceParameters(\n account_to_fund=app_client.app_address,\n min_spending_balance_micro_algos=200_000,\n ),\n )\n\n app_client.call(\"create_and_transfer\")\n\n\ndef test_inner_transactions_assignment(\n algod_client: AlgodClient, account: algokit_utils.Account\n) -> None:\n example = TEST_CASES_DIR \/ \"inner_transactions_assignment\"\n app_spec = algokit_utils.ApplicationSpecification.from_json(compile_arc32(example))\n\n increased_fee = algod_client.suggested_params()\n increased_fee.flat_fee = True\n increased_fee.fee = constants.min_txn_fee * 8\n app_client = algokit_utils.ApplicationClient(\n algod_client, app_spec, signer=account, suggested_params=increased_fee\n )\n app_client.create()\n\n algokit_utils.ensure_funded(\n algod_client,\n algokit_utils.EnsureBalanceParameters(\n account_to_fund=app_client.app_address,\n min_spending_balance_micro_algos=400_000,\n ),\n )\n\n app_client.call(\"test_itxn_slice\")\n app_client.call(\"test_itxn_nested\")\n\n\ndef test_state_proxies(algod_client: AlgodClient, account: algokit_utils.Account) -> None:\n example = TEST_CASES_DIR \/ \"state_proxies\" \/ \"contract.py\"\n\n app_spec = algokit_utils.ApplicationSpecification.from_json(compile_arc32(example))\n app_client = algokit_utils.ApplicationClient(algod_client, app_spec, signer=account)\n\n app_client.create(transaction_parameters={\"on_complete\": OnComplete.OptInOC})\n assert app_client.get_global_state() == {\"g1\": 1, \"g2\": 0, \"funky\": 123}\n assert app_client.get_local_state(account.address) == {\"l1\": 2, \"l2\": 3}\n\n\ndef test_template_variables(\n algod_client: AlgodClient,\n account: algokit_utils.Account,\n) -> None:\n example = TEST_CASES_DIR \/ \"template_variables\"\n app_spec = algokit_utils.ApplicationSpecification.from_json(compile_arc32(example))\n app_client = algokit_utils.ApplicationClient(\n algod_client,\n app_spec,\n signer=account,\n template_values={\n \"SOME_BYTES\": b\"Hello I'm a variable\",\n \"SOME_BIG_UINT\": (1337).to_bytes(length=2),\n \"UPDATABLE\": 1,\n \"DELETABLE\": 1,\n },\n )\n\n app_client.create()\n\n get_bytes = app_client.call(\n call_abi_method=\"get_bytes\",\n )\n assert bytes(get_bytes.return_value) == b\"Hello I'm a variable\"\n\n get_uint = app_client.call(\n call_abi_method=\"get_big_uint\",\n )\n\n assert get_uint.return_value == 1337\n\n app_client = algokit_utils.ApplicationClient(\n algod_client,\n app_spec,\n signer=account,\n app_id=app_client.app_id,\n template_values={\n \"SOME_BYTES\": b\"Updated variable\",\n \"SOME_BIG_UINT\": (0).to_bytes(length=2),\n \"UPDATABLE\": 0,\n \"DELETABLE\": 1,\n },\n )\n\n app_client.update()\n\n get_bytes = app_client.call(\n call_abi_method=\"get_bytes\",\n )\n assert bytes(get_bytes.return_value) == b\"Updated variable\"\n\n get_uint = app_client.call(\n call_abi_method=\"get_big_uint\",\n )\n\n assert get_uint.return_value == 0\n\n try:\n app_client.update()\n raise AssertionError(\"Update should fail\")\n except LogicError:\n pass\n\n app_client.delete()\n\n\ndef test_merkle(algod_client: AlgodClient, account: algokit_utils.Account) -> None:\n example = EXAMPLES_DIR \/ \"merkle\"\n app_spec = algokit_utils.ApplicationSpecification.from_json(compile_arc32(example))\n app_client = algokit_utils.ApplicationClient(\n algod_client,\n app_spec,\n signer=account,\n )\n\n test_tree = MerkleTree(\n [\n b\"a\",\n b\"b\",\n b\"c\",\n b\"d\",\n b\"e\",\n ]\n )\n app_client.create(call_abi_method=\"create\", root=test_tree.root)\n\n assert app_client.call(\n call_abi_method=\"verify\", leaf=sha_256_raw(b\"a\"), proof=test_tree.get_proof(b\"a\")\n ).return_value\n\n\ndef test_typed_abi_call(\n algod_client: AlgodClient, account: algokit_utils.Account, asset_a: int\n) -> None:\n logger = algokit_utils.ApplicationClient(\n algod_client,\n algokit_utils.ApplicationSpecification.from_json(\n compile_arc32(TEST_CASES_DIR \/ \"typed_abi_call\" \/ \"logger.py\")\n ),\n signer=account,\n )\n logger.create()\n\n example = TEST_CASES_DIR \/ \"typed_abi_call\" \/ \"typed_c2c.py\"\n app_spec = algokit_utils.ApplicationSpecification.from_json(compile_arc32(example))\n\n # deploy greeter\n app_client = algokit_utils.ApplicationClient(algod_client, app_spec, signer=account)\n app_client.create()\n\n increased_fee = algod_client.suggested_params()\n increased_fee.flat_fee = True\n increased_fee.fee = constants.min_txn_fee * 6\n txn_params = algokit_utils.OnCompleteCallParameters(suggested_params=increased_fee)\n\n app_client.call(\n \"test_method_selector_kinds\",\n transaction_parameters=txn_params,\n app=logger.app_id,\n )\n\n app_client.call(\n \"test_arg_conversion\",\n transaction_parameters=txn_params,\n app=logger.app_id,\n )\n\n app_client.call(\n \"test_method_overload\",\n transaction_parameters=txn_params,\n app=logger.app_id,\n )\n\n app_client.call(\n \"test_15plus_args\",\n transaction_parameters=txn_params,\n app=logger.app_id,\n )\n\n app_client.call(\n \"test_void\",\n transaction_parameters=txn_params,\n app=logger.app_id,\n )\n\n app_client.call(\n \"test_ref_types\",\n transaction_parameters=txn_params,\n app=logger.app_id,\n asset=asset_a,\n )\n\n app_client.call(\n \"test_native_tuple\",\n transaction_parameters=txn_params,\n app=logger.app_id,\n )\n\n app_client.call(\n \"test_native_tuple_method_ref\",\n transaction_parameters=txn_params,\n app=logger.app_id,\n )\n\n app_client.call(\n \"test_nested_tuples\",\n transaction_parameters=txn_params,\n app=logger.app_id,\n )\n\n app_client.call(\n \"test_native_string\",\n transaction_parameters=txn_params,\n app=logger.app_id,\n )\n\n app_client.call(\n \"test_native_bytes\",\n transaction_parameters=txn_params,\n app=logger.app_id,\n )\n\n app_client.call(\n \"test_native_uint64\",\n transaction_parameters=txn_params,\n app=logger.app_id,\n )\n\n app_client.call(\n \"test_native_biguint\",\n transaction_parameters=txn_params,\n app=logger.app_id,\n )\n\n app_client.call(\n \"test_no_args\",\n transaction_parameters=txn_params,\n app=logger.app_id,\n )\n\n app_client.call(\n \"test_is_a_b\",\n transaction_parameters=txn_params,\n a=b\"a\",\n b=b\"b\",\n app=logger.app_id,\n )\n\n app_client.call(\n \"test_named_tuples\",\n transaction_parameters=txn_params,\n app=logger.app_id,\n )\n\n\ndef test_arc28(algod_client: AlgodClient, account: algokit_utils.Account) -> None:\n app_client = algokit_utils.ApplicationClient(\n algod_client,\n algokit_utils.ApplicationSpecification.from_json(compile_arc32(EXAMPLES_DIR \/ \"arc_28\")),\n signer=account,\n )\n app_client.create()\n\n a = 42\n b = 12\n result = app_client.call(\n \"emit_swapped\",\n a=a,\n b=b,\n )\n logs = result.tx_info[\"logs\"]\n events = decode_logs(logs, \"bbb\")\n for event in events:\n assert isinstance(event, bytes)\n event_sig = event[:4]\n event_data = event[4:]\n assert event_sig == bytes.fromhex(\"1ccbd925\")\n assert event_data == b.to_bytes(length=8) + a.to_bytes(length=8)\n\n\n@pytest.fixture\ndef other_account(algod_client: AlgodClient) -> algokit_utils.Account:\n v = algosdk.account.generate_account()\n voter_account = algokit_utils.Account(private_key=v[0], address=v[1])\n algokit_utils.transfer(\n client=algod_client,\n parameters=algokit_utils.TransferParameters(\n from_account=algokit_utils.get_localnet_default_account(algod_client),\n to_address=voter_account.address,\n micro_algos=10000000,\n ),\n )\n return voter_account\n\n\ndef test_tictactoe(\n algod_client: AlgodClient, account: algokit_utils.Account, other_account: algokit_utils.Account\n) -> None:\n app_spec = algokit_utils.ApplicationSpecification.from_json(\n compile_arc32(EXAMPLES_DIR \/ \"tictactoe\" \/ \"tictactoe.py\")\n )\n client_host = algokit_utils.ApplicationClient(\n algod_client,\n app_spec,\n signer=account,\n )\n\n client_host.create(call_abi_method=\"new_game\", move=(0, 0))\n turn_result = client_host.call(\"whose_turn\")\n assert turn_result.return_value == 2\n # no one has joined, can start a new game\n client_host.call(call_abi_method=\"new_game\", move=(1, 1))\n\n with pytest.raises(algokit_utils.logic_error.LogicError) as exc_info:\n client_host.call(call_abi_method=\"play\", move=(0, 0))\n assert exc_info.value.line_no is not None\n assert \"It is the challenger's turn\" in exc_info.value.lines[exc_info.value.line_no]\n\n game, winner = _get_tic_tac_toe_game_status(client_host)\n assert game == [\n \"- - -\",\n \"- X -\",\n \"- - -\",\n ]\n assert winner is None\n\n client_challenger = algokit_utils.ApplicationClient(\n algod_client,\n app_spec,\n app_id=client_host.app_id,\n signer=other_account,\n )\n\n client_challenger.call(call_abi_method=\"join_game\", move=(0, 0))\n\n game, winner = _get_tic_tac_toe_game_status(client_host)\n assert game == [\n \"O - -\",\n \"- X -\",\n \"- - -\",\n ]\n assert winner is None\n\n turn_result = client_challenger.call(\"whose_turn\")\n assert turn_result.return_value == 1\n\n with pytest.raises(algokit_utils.logic_error.LogicError) as exc_info:\n client_host.call(call_abi_method=\"new_game\", move=(2, 2))\n assert exc_info.value.line_no is not None\n assert \"Game isn't over\" in exc_info.value.lines[exc_info.value.line_no]\n\n client_host.call(call_abi_method=\"play\", move=(0, 1))\n\n game, winner = _get_tic_tac_toe_game_status(client_host)\n assert game == [\n \"O - -\",\n \"X X -\",\n \"- - -\",\n ]\n assert winner is None\n\n client_challenger.call(call_abi_method=\"play\", move=(1, 0))\n\n game, winner = _get_tic_tac_toe_game_status(client_host)\n assert game == [\n \"O O -\",\n \"X X -\",\n \"- - -\",\n ]\n assert winner is None\n\n client_host.call(call_abi_method=\"play\", move=(2, 1))\n\n game, winner = _get_tic_tac_toe_game_status(client_host)\n assert game == [\n \"O O -\",\n \"X X X\",\n \"- - -\",\n ]\n assert winner == \"Host\"\n\n client_host.call(call_abi_method=\"new_game\", move=(1, 1))\n game, winner = _get_tic_tac_toe_game_status(client_host)\n assert game == [\n \"- - -\",\n \"- X -\",\n \"- - -\",\n ]\n assert winner is None\n\n\ndef _get_tic_tac_toe_game_status(\n client_host: algokit_utils.ApplicationClient,\n) -> tuple[list[str], str | None]:\n state = client_host.get_global_state(raw=True)\n game = state[b\"game\"]\n assert isinstance(game, bytes)\n chars = [\"X\" if b == 1 else \"O\" if b == 2 else \"-\" for b in game]\n board = [\" \".join(chars[:3]), \" \".join(chars[3:6]), \" \".join(chars[6:])]\n\n winner_index = state.get(b\"winner\")\n assert isinstance(winner_index, bytes | None)\n winner = {\n None: None,\n b\"\\01\": \"Host\",\n b\"\\02\": \"Challenger\",\n b\"\\03\": \"Draw\",\n }[winner_index]\n return board, winner\n\n\n@pytest.fixture(scope=\"module\")\ndef dynamic_app_client(\n algod_client: AlgodClient, account: algokit_utils.Account\n) -> algokit_utils.ApplicationClient:\n app_client = algokit_utils.ApplicationClient(\n algod_client,\n algokit_utils.ApplicationSpecification.from_json(\n compile_arc32(TEST_CASES_DIR \/ \"arc4_dynamic_arrays\")\n ),\n signer=account,\n )\n app_client.create()\n return app_client\n\n\ndef test_dynamic_arrays_static_element(\n dynamic_app_client: algokit_utils.ApplicationClient,\n) -> None:\n static_struct_t = abi.ABIType.from_string(\"(uint64,byte[2])\")\n static_arr_t = abi.ArrayDynamicType(static_struct_t)\n static_struct0 = (3, bytes((4, 5)))\n static_struct1 = (2**42, bytes((42, 255)))\n\n static_result = dynamic_app_client.call(\"test_static_elements\")\n (static_arr_bytes, static_0_bytes, static_1_bytes) = decode_logs(\n static_result.tx_info[\"logs\"], \"bbb\"\n )\n\n assert static_arr_bytes == static_arr_t.encode([static_struct0, static_struct1])\n assert static_0_bytes == static_struct_t.encode(static_struct0)\n assert static_1_bytes == static_struct_t.encode(static_struct1)\n\n\ndef test_dynamic_arrays_dynamic_element(\n dynamic_app_client: algokit_utils.ApplicationClient,\n) -> None:\n dynamic_struct_t = abi.ABIType.from_string(\"(string,string)\")\n dynamic_arr_t = abi.ABIType.from_string(\"(string,string)[]\")\n dynamic_struct0 = (\"a\", \"bee\")\n dynamic_struct1 = (\"Hello World\", \"a\")\n\n dynamic_result = dynamic_app_client.call(\"test_dynamic_elements\")\n (\n dynamic_arr_bytes,\n dynamic_0_bytes,\n dynamic_1_bytes,\n dynamic_2_bytes,\n dynamic_arr_bytes_01,\n dynamic_arr_bytes_0,\n empty_arr,\n ) = decode_logs(dynamic_result.tx_info[\"logs\"], \"b\" * 7)\n\n assert dynamic_arr_bytes == dynamic_arr_t.encode(\n [dynamic_struct0, dynamic_struct1, dynamic_struct0]\n )\n assert dynamic_0_bytes == dynamic_struct_t.encode(dynamic_struct0)\n assert dynamic_1_bytes == dynamic_struct_t.encode(dynamic_struct1)\n assert dynamic_2_bytes == dynamic_struct_t.encode(dynamic_struct0)\n assert dynamic_arr_bytes_01 == dynamic_arr_t.encode([dynamic_struct0, dynamic_struct1])\n assert dynamic_arr_bytes_0 == dynamic_arr_t.encode([dynamic_struct0])\n assert empty_arr == dynamic_arr_t.encode([])\n\n\ndef test_dynamic_arrays_mixed_single_dynamic(\n dynamic_app_client: algokit_utils.ApplicationClient,\n) -> None:\n mixed1_struct_t = abi.ABIType.from_string(\"(uint64,string,uint64)\")\n mixed1_arr_t = abi.ArrayDynamicType(mixed1_struct_t)\n mixed1_struct0 = (3, \"a\", 2**42)\n mixed1_struct1 = (2**42, \"bee\", 3)\n\n mixed_single_result = dynamic_app_client.call(\"test_mixed_single_dynamic_elements\")\n (mixed1_arr_bytes, mixed1_0_bytes, mixed1_1_bytes) = decode_logs(\n mixed_single_result.tx_info[\"logs\"], \"bbb\"\n )\n\n assert mixed1_arr_bytes == mixed1_arr_t.encode([mixed1_struct0, mixed1_struct1])\n assert mixed1_0_bytes == mixed1_struct_t.encode(mixed1_struct0)\n assert mixed1_1_bytes == mixed1_struct_t.encode(mixed1_struct1)\n\n\ndef test_dynamic_arrays_mixed_multiple_dynamic(\n dynamic_app_client: algokit_utils.ApplicationClient,\n) -> None:\n mixed2_struct_t = abi.ABIType.from_string(\"(uint64,string,uint64,uint16[],uint64)\")\n mixed2_arr_t = abi.ArrayDynamicType(mixed2_struct_t)\n mixed2_struct0 = (3, \"a\", 2**42, (2**16 - 1, 0, 42), 3)\n mixed2_struct1 = (2**42, \"bee\", 3, (1, 2, 3, 4), 2**42)\n\n mixed_multiple_result = dynamic_app_client.call(\"test_mixed_multiple_dynamic_elements\")\n (mixed2_arr_bytes, mixed2_0_bytes, mixed2_1_bytes) = decode_logs(\n mixed_multiple_result.tx_info[\"logs\"], \"bbb\"\n )\n\n assert mixed2_arr_bytes == mixed2_arr_t.encode([mixed2_struct0, mixed2_struct1])\n assert mixed2_0_bytes == mixed2_struct_t.encode(mixed2_struct0)\n assert mixed2_1_bytes == mixed2_struct_t.encode(mixed2_struct1)\n\n\ndef test_nested_struct(\n dynamic_app_client: algokit_utils.ApplicationClient,\n) -> None:\n dynamic_app_client.call(\"test_nested_struct_replacement\")\n\n\ndef test_nested_tuple(\n dynamic_app_client: algokit_utils.ApplicationClient,\n) -> None:\n dynamic_app_client.call(\"test_nested_tuple_modification\")\n\n\ndef test_struct_in_box(\n algod_client: AlgodClient, account: algokit_utils.Account, asset_a: int\n) -> None:\n app_spec = algokit_utils.ApplicationSpecification.from_json(\n compile_arc32(EXAMPLES_DIR \/ \"struct_in_box\" \/ \"contract.py\")\n )\n client = algokit_utils.ApplicationClient(\n algod_client,\n app_spec,\n signer=account,\n )\n\n # Create the application\n client.create()\n\n # Fund the application (so it can have boxes)\n algokit_utils.transfer(\n algod_client,\n algokit_utils.TransferParameters(\n to_address=client.app_address, from_account=account, micro_algos=10_000_000\n ),\n )\n\n user_1 = {\"id\": 1, \"name\": \"Bob\", \"asset\": 0}\n user_2 = {\"id\": 2, \"name\": \"Jane\", \"asset\": 0}\n\n client.call(\n \"add_user\",\n user=user_1,\n transaction_parameters=algokit_utils.OnCompleteCallParameters(\n boxes=[\n (0, (1).to_bytes(8)),\n ]\n ),\n )\n\n client.call(\n \"add_user\",\n user=user_2,\n transaction_parameters=algokit_utils.OnCompleteCallParameters(\n boxes=[\n (0, (2).to_bytes(8)),\n ]\n ),\n )\n\n client.call(\n \"attach_asset_to_user\",\n user_id=user_1[\"id\"],\n asset=asset_a,\n transaction_parameters=algokit_utils.OnCompleteCallParameters(\n boxes=[\n (0, (1).to_bytes(8)),\n ]\n ),\n )\n\n user_1_result = client.call(\n \"get_user\",\n user_id=1,\n transaction_parameters=algokit_utils.OnCompleteCallParameters(\n boxes=[\n (0, (1).to_bytes(8)),\n ]\n ),\n )\n assert user_1_result.return_value == [\"Bob\", 1, asset_a]\n user_2_result = client.call(\n \"get_user\",\n user_id=2,\n transaction_parameters=algokit_utils.OnCompleteCallParameters(\n boxes=[\n (0, (2).to_bytes(8)),\n ]\n ),\n )\n assert user_2_result.return_value == [\"Jane\", 2, 0]\n\n\n_ADDITIONAL_BOX_REF = (0, b\"\")\n\n\n@pytest.fixture\ndef box_client(\n algod_client: AlgodClient, account: algokit_utils.Account\n) -> algokit_utils.ApplicationClient:\n app_spec = algokit_utils.ApplicationSpecification.from_json(\n compile_arc32(EXAMPLES_DIR \/ \"box_storage\" \/ \"contract.py\")\n )\n algokit_utils.ensure_funded(\n algod_client,\n algokit_utils.EnsureBalanceParameters(\n account_to_fund=account, min_spending_balance_micro_algos=20_000_000\n ),\n )\n client = algokit_utils.ApplicationClient(\n algod_client,\n app_spec,\n signer=account,\n )\n\n client.create()\n\n algokit_utils.transfer(\n algod_client,\n algokit_utils.TransferParameters(\n to_address=client.app_address, from_account=account, micro_algos=10_000_000\n ),\n )\n return client\n\n\ndef _params_with_boxes(\n *keys: str | bytes | int, additional_refs: int = 0\n) -> algokit_utils.OnCompleteCallParameters:\n return algokit_utils.OnCompleteCallParameters(\n boxes=[(0, key.to_bytes(8) if isinstance(key, int) else key) for key in keys]\n + [_ADDITIONAL_BOX_REF] * additional_refs\n )\n\n\ndef test_box(box_client: algokit_utils.ApplicationClient) -> None:\n box_c = b\"BOX_C\"\n transaction_parameters = _params_with_boxes(\"box_a\", \"b\", box_c, \"box_d\")\n\n (a_exist, b_exist, c_exist) = box_client.call(\n call_abi_method=\"boxes_exist\",\n transaction_parameters=transaction_parameters,\n ).return_value\n assert not a_exist\n assert not b_exist\n assert not c_exist\n\n box_client.call(\n call_abi_method=\"set_boxes\",\n a=56,\n b=b\"Hello\",\n c=\"World\",\n transaction_parameters=transaction_parameters,\n )\n\n (a_exist, b_exist, c_exist) = box_client.call(\n call_abi_method=\"boxes_exist\",\n transaction_parameters=transaction_parameters,\n ).return_value\n assert a_exist\n assert b_exist\n assert c_exist\n\n box_client.call(\"check_keys\", transaction_parameters=transaction_parameters)\n\n (a, b, c) = box_client.call(\n call_abi_method=\"read_boxes\",\n transaction_parameters=transaction_parameters,\n ).return_value\n\n assert (a, bytes(b), c) == (59, b\"Hello\", \"World\")\n\n box_client.call(\"delete_boxes\", transaction_parameters=transaction_parameters)\n\n (a_exist, b_exist, c_exist) = box_client.call(\n call_abi_method=\"boxes_exist\",\n transaction_parameters=transaction_parameters,\n ).return_value\n assert not a_exist\n assert not b_exist\n assert not c_exist\n\n box_client.call(\n call_abi_method=\"slice_box\", transaction_parameters=_params_with_boxes(b\"0\", box_c)\n )\n\n box_client.call(call_abi_method=\"arc4_box\", transaction_parameters=_params_with_boxes(b\"d\"))\n\n\ndef test_box_ref(box_client: algokit_utils.ApplicationClient) -> None:\n box_client.call(\n call_abi_method=\"test_box_ref\",\n transaction_parameters=_params_with_boxes(\"box_ref\", b\"blob\", additional_refs=6),\n )\n\n\ndef test_box_map(box_client: algokit_utils.ApplicationClient) -> None:\n box_client.call(\n call_abi_method=\"box_map_test\",\n transaction_parameters=_params_with_boxes(0, 1),\n )\n\n key = 2\n transaction_parameters = _params_with_boxes(key)\n assert not box_client.call(\n call_abi_method=\"box_map_exists\",\n key=key,\n transaction_parameters=transaction_parameters,\n ).return_value, \"Box does not exist (yet)\"\n box_client.call(\n call_abi_method=\"box_map_set\",\n key=key,\n value=\"Hello 123\",\n transaction_parameters=transaction_parameters,\n )\n assert (\n box_client.call(\n call_abi_method=\"box_map_get\",\n key=key,\n transaction_parameters=transaction_parameters,\n ).return_value\n == \"Hello 123\"\n ), \"Box value is what was set\"\n\n assert box_client.call(\n call_abi_method=\"box_map_exists\",\n key=key,\n transaction_parameters=transaction_parameters,\n ).return_value, \"Box exists\"\n\n box_client.call(\n call_abi_method=\"box_map_del\",\n key=key,\n transaction_parameters=transaction_parameters,\n )\n\n assert not box_client.call(\n call_abi_method=\"box_map_exists\",\n key=key,\n transaction_parameters=transaction_parameters,\n ).return_value, \"Box does not exist after deletion\"\n\n\ndef test_compile(algod_client: AlgodClient, account: algokit_utils.Account) -> None:\n app_spec = algokit_utils.ApplicationSpecification.from_json(\n compile_arc32(TEST_CASES_DIR \/ \"compile\", file_name=\"factory.py\")\n )\n app_client = algokit_utils.ApplicationClient(algod_client, app_spec, signer=account)\n\n app_client.create()\n\n increased_fee = algod_client.suggested_params()\n increased_fee.flat_fee = True\n increased_fee.fee = constants.min_txn_fee * 6\n txn_params = algokit_utils.OnCompleteCallParameters(suggested_params=increased_fee)\n algokit_utils.config.config.configure(debug=True, trace_all=True)\n app_client.call(\"test_compile_contract\", transaction_parameters=txn_params)\n app_client.call(\"test_compile_contract_tmpl\", transaction_parameters=txn_params)\n app_client.call(\"test_compile_contract_prfx\", transaction_parameters=txn_params)\n app_client.call(\"test_compile_contract_large\", transaction_parameters=txn_params)\n\n app_client.call(\"test_arc4_create\", transaction_parameters=txn_params)\n app_client.call(\"test_arc4_create_tmpl\", transaction_parameters=txn_params)\n app_client.call(\"test_arc4_create_prfx\", transaction_parameters=txn_params)\n app_client.call(\"test_arc4_create_large\", transaction_parameters=txn_params)\n app_client.call(\"test_arc4_create_modified_compiled\", transaction_parameters=txn_params)\n app_client.call(\"test_arc4_update\", transaction_parameters=txn_params)\n app_client.call(\"test_other_constants\", transaction_parameters=txn_params)\n app_client.call(\"test_abi_call_create_params\", transaction_parameters=txn_params)\n\n\ndef test_nested_tuples(\n algod_client: AlgodClient,\n account: algokit_utils.Account,\n) -> None:\n example = TEST_CASES_DIR \/ \"tuple_support\" \/ \"nested_tuples.py\"\n app_spec = algokit_utils.ApplicationSpecification.from_json(compile_arc32(example))\n app_client = algokit_utils.ApplicationClient(algod_client, app_spec, signer=account)\n\n # create\n app_client.create()\n\n app_client.call(\"run_tests\")\n\n response = app_client.call(\"nested_tuple_params\", args=(\"Hello\", (b\"World\", (123,))))\n\n assert bytes(response.return_value[0]) == b\"World\"\n assert response.return_value[1][0] == \"Hello\"\n assert response.return_value[1][1] == 123\n\n response = app_client.call(\"named_tuple\", args=(1, b\"2\", \"3\"))\n assert response.return_value == [1, [50], \"3\"]\n\n response = app_client.call(\"nested_named_tuple_params\", args=(1, 2, (3, b\"4\", \"5\")))\n assert response.return_value == [1, 2, [3, [52], \"5\"]]\n\n\ndef test_named_tuples(\n algod_client: AlgodClient,\n account: algokit_utils.Account,\n) -> None:\n example = TEST_CASES_DIR \/ \"named_tuples\" \/ \"contract.py\"\n app_spec = algokit_utils.ApplicationSpecification.from_json(compile_arc32(example))\n app_client = algokit_utils.ApplicationClient(algod_client, app_spec, signer=account)\n\n # create\n app_client.create()\n\n result = app_client.call(\"build_tuple\", a=12, b=343459043, c=\"hello 123\", d=account.public_key)\n\n (a, b, c, d) = result.return_value\n\n app_client.call(\"test_tuple\", value=(a, b, c, d))\n\n app_client.call(\n \"test_tuple\", value={\"a\": 34, \"b\": 53934433, \"c\": \"hmmmm\", \"d\": account.public_key}\n )\n\n\ndef test_group_side_effects(\n algod_client: AlgodClient,\n account: algokit_utils.Account,\n) -> None:\n test_dir = TEST_CASES_DIR \/ \"group_side_effects\"\n other_app_spec = algokit_utils.ApplicationSpecification.from_json(\n compile_arc32(test_dir \/ \"other.py\")\n )\n app_spec = algokit_utils.ApplicationSpecification.from_json(\n compile_arc32(test_dir \/ \"contract.py\")\n )\n other_app_client = algokit_utils.ApplicationClient(\n algod_client, other_app_spec, signer=account\n )\n app_client = algokit_utils.ApplicationClient(algod_client, app_spec, signer=account)\n\n # create app\n app_client.create()\n sp = algod_client.suggested_params()\n\n # compose group with asset and app create txns\n asset_create_txn = TransactionWithSigner(\n transaction.AssetCreateTxn(\n account.address,\n sp,\n 10_000_000,\n 0,\n default_frozen=False,\n asset_name=\"asset group\",\n unit_name=\"AGRP\",\n ),\n signer=account.signer,\n )\n atc = AtomicTransactionComposer()\n other_app_client.compose_create(atc)\n app_create_txn = atc.txn_list[-1]\n\n # call app with create txns\n response = app_client.call(\n \"create_group\", asset_create=asset_create_txn, app_create=app_create_txn\n )\n asset_id, other_app_id = response.return_value\n\n # compose group with app call\n other_app_client.app_id = other_app_id\n atc = AtomicTransactionComposer()\n other_app_client.compose_call(atc, \"some_value\")\n app_call_txn = atc.txn_list[-1]\n app_client.call(\"log_group\", app_call=app_call_txn)\n\n\ndef test_state_mutations(\n algod_client: AlgodClient,\n account: algokit_utils.Account,\n) -> None:\n test_dir = TEST_CASES_DIR \/ \"state_mutations\"\n app_spec = algokit_utils.ApplicationSpecification.from_json(compile_arc32(test_dir))\n app_client = algokit_utils.ApplicationClient(algod_client, app_spec, signer=account)\n\n # create app\n app_client.create()\n algokit_utils.ensure_funded(\n algod_client,\n algokit_utils.EnsureBalanceParameters(\n account_to_fund=app_client.app_address,\n min_spending_balance_micro_algos=200_000,\n ),\n )\n box_key = b\"box\"\n map_key = b\"map\" + account.public_key\n txn_params: algokit_utils.OnCompleteCallParametersDict = {\n \"boxes\": [(0, box_key), (0, map_key)]\n }\n app_client.opt_in(transaction_parameters=txn_params)\n response = app_client.call(\"get\", transaction_parameters=txn_params)\n assert response.return_value == []\n\n # append\n app_client.call(\"append\", transaction_parameters=txn_params)\n response = app_client.call(\"get\", transaction_parameters=txn_params)\n assert response.return_value == [[1, \"baz\"]]\n\n # modify\n app_client.call(\"modify\", transaction_parameters=txn_params)\n response = app_client.call(\"get\", transaction_parameters=txn_params)\n assert response.return_value == [[1, \"modified\"]]\n\n # append\n app_client.call(\"append\", transaction_parameters=txn_params)\n response = app_client.call(\"get\", transaction_parameters=txn_params)\n assert response.return_value == [[1, \"modified\"], [1, \"baz\"]]\n\n\n@pytest.mark.parametrize(\n (\"file_name\", \"expected_init_log\", \"expected_method_log\"),\n [\n (\n \"base1\",\n [\"base1.__init__\", \"gp.__init__\"],\n [\"base1.method\", \"gp.method\"],\n ),\n (\n \"base2\",\n [\"base2.__init__\", \"gp.__init__\"],\n [\"base2.method\", \"gp.method\"],\n ),\n (\n \"derived\",\n [\"derived.__init__\", \"base1.__init__\", \"base2.__init__\", \"gp.__init__\"],\n [\"derived.method\", \"base1.method\", \"base2.method\", \"gp.method\"],\n ),\n ],\n)\ndef test_diamond_mro(\n algod_client: AlgodClient,\n account: algokit_utils.Account,\n file_name: str,\n expected_init_log: list[str],\n expected_method_log: list[str],\n) -> None:\n example = TEST_CASES_DIR \/ \"diamond_mro\" \/ f\"{file_name}.py\"\n\n app_spec = algokit_utils.ApplicationSpecification.from_json(compile_arc32(example))\n app_client = algokit_utils.ApplicationClient(algod_client, app_spec, signer=account)\n init_response = app_client.create(call_abi_method=True)\n init_logs_raw = init_response.tx_info[\"logs\"]\n init_logs = decode_logs(init_logs_raw, len(init_logs_raw) * \"u\")\n assert init_logs == expected_init_log\n\n method_response = app_client.call(call_abi_method=\"method\")\n method_logs_raw = method_response.tx_info[\"logs\"]\n method_logs = decode_logs(method_logs_raw, len(method_logs_raw) * \"u\")\n assert method_logs == expected_method_log\n","repo_name":"algorandfoundation\/puya","path":"tests\/test_arc32.py","language":"Python","license":"NOASSERTION","size":54547} {"code":"from collections.abc import Mapping\n\nimport algosdk.error\nimport pytest\nfrom algokit_utils import Program\nfrom algosdk.v2client.algod import AlgodClient\n\nfrom puya.compilation_artifacts import CompiledContract, CompiledLogicSig, CompiledProgram\nfrom puya.context import CompileContext\nfrom puya.mir.models import Signature\nfrom puya.options import PuyaOptions\nfrom puya.program_refs import LogicSigReference\nfrom puya.teal import models as teal\nfrom puya.ussemble.main import assemble_program\nfrom puyapy.options import PuyaPyOptions\nfrom tests.utils import (\n PuyaTestCase,\n compile_src_from_options,\n load_template_vars,\n)\n\n\n@pytest.mark.parametrize(\"optimization_level\", [0, 1, 2])\n@pytest.mark.localnet\ndef test_assemble_matches_algod(\n algod_client: AlgodClient, test_case: PuyaTestCase, optimization_level: int\n) -> None:\n prefix, template_vars = load_template_vars(test_case.template_vars_path)\n options = PuyaPyOptions(\n paths=(test_case.path,),\n optimization_level=optimization_level,\n debug_level=0,\n output_bytecode=True,\n template_vars_prefix=prefix,\n cli_template_definitions=template_vars,\n )\n compile_result = compile_src_from_options(options)\n for artifact in compile_result.teal:\n match artifact:\n case CompiledContract(approval_program=approval, clear_program=clear):\n assemble_and_compare_program(\n options, algod_client, approval, f\"{artifact.metadata.ref}-approval\"\n )\n assemble_and_compare_program(\n options, algod_client, clear, f\"{artifact.metadata.ref}-clear\"\n )\n case CompiledLogicSig(program=logic_sig):\n assemble_and_compare_program(\n options, algod_client, logic_sig, f\"{artifact.metadata.ref}-logicsig\"\n )\n\n\ndef assemble_and_compare_program(\n options: PuyaOptions,\n algod_client: AlgodClient,\n compiled_program: CompiledProgram,\n name: str,\n) -> None:\n puya_program = compiled_program.bytecode\n assert puya_program is not None\n template_values = {k: _template_value_as_str(v) for k, v in options.template_variables.items()}\n teal_src = \"\\n\".join(\n _replace_template_variables(line, template_values)\n for line in compiled_program.teal_src.splitlines()\n )\n algod_program_ = Program(teal_src, algod_client)\n algod_program = algod_program_.raw_binary\n\n expected = algod_program.hex()\n actual = puya_program.hex()\n if expected != actual:\n # attempt to decompile both to compare, but revert to byte code if puya can't\n # even be disassembled\n try:\n puya_dis = algod_client.disassemble(puya_program)[\"result\"]\n except algosdk.error.AlgodHTTPError:\n pass\n else:\n expected = algod_client.disassemble(algod_program)[\"result\"]\n actual = puya_dis\n assert actual == expected, f\"{name} bytecode does not match algod bytecode\"\n\n\ndef _template_value_as_str(value: int | bytes) -> str:\n if isinstance(value, int):\n return repr(value)\n return \"0x\" + value.hex()\n\n\ndef _replace_template_variables(line: str, template_values: Mapping[str, str]) -> str:\n for var, value in template_values.items():\n line = line.replace(var, value, 1)\n return line\n\n\ndef test_assemble_last_op_jump() -> None:\n \"\"\"Verifies edge case where final op of a program is a branch op\"\"\"\n\n # construct a block that is terminated with a branch, by jumping to the block's label\n looping_block = teal.TealBlock(\n label=\"start\",\n ops=[\n teal.Intrinsic(\n op_code=\"b\",\n immediates=[\"start\"],\n consumes=0,\n produces=0,\n source_location=None,\n )\n ],\n x_stack_in=(),\n entry_stack_height=0,\n exit_stack_height=0,\n )\n\n # verify program assembles correctly\n bytecode = assemble_program(\n CompileContext(\n options=PuyaOptions(),\n compilation_set={},\n sources_by_path={},\n ),\n LogicSigReference(),\n program=teal.TealProgram(\n avm_version=10,\n main=teal.TealSubroutine(\n is_main=True,\n signature=Signature(name=\"\", parameters=(), returns=()),\n blocks=[looping_block],\n source_location=None,\n ),\n subroutines=[],\n ),\n ).bytecode\n\n assert bytecode == b\"\".join(\n (\n b\"\\x0a\", # version 10\n b\"B\", # branch\n (-3).to_bytes(length=2, signed=True), # offset\n )\n )\n","repo_name":"algorandfoundation\/puya","path":"tests\/test_assemble.py","language":"Python","license":"NOASSERTION","size":4718} {"code":"from puya.awst import nodes, serialize\nfrom puya.awst.to_code_visitor import ToCodeVisitor\nfrom tests.utils import PuyaTestCase, get_awst_cache\n\n\ndef test_cattrs(test_case: PuyaTestCase) -> None:\n cache = get_awst_cache(test_case.root)\n awst = [a for a in cache.module_awst if _is_case_awst(test_case, a)]\n json = serialize.awst_to_json(awst)\n cloned = serialize.awst_from_json(json)\n assert len(cloned) == len(awst)\n\n assert ToCodeVisitor().visit_module(cloned) == ToCodeVisitor().visit_module(awst)\n for cloned_, awst_ in zip(cloned, awst, strict=True):\n assert cloned_ == awst_\n\n\ndef _is_case_awst(case: PuyaTestCase, awst: nodes.RootNode) -> bool:\n path = awst.source_location.file\n return bool(path and path.is_relative_to(case.path))\n","repo_name":"algorandfoundation\/puya","path":"tests\/test_cattrs.py","language":"Python","license":"NOASSERTION","size":774} {"code":"import os\nimport shutil\nimport subprocess\nfrom pathlib import Path\n\nfrom tests import EXAMPLES_DIR, TEST_CASES_DIR, VCS_ROOT\n\nENV_WITH_NO_COLOR = dict(os.environ) | {\n \"NO_COLOR\": \"1\", # disable colour output\n \"PYTHONUTF8\": \"1\", # force utf8 on windows\n}\n\n\ndef run_puyapy(\n args: list[str | Path], *, check: bool = True, text: bool = True\n) -> subprocess.CompletedProcess[str]:\n puyapy = shutil.which(\"puyapy\")\n assert puyapy is not None\n result = subprocess.run(\n [\n puyapy,\n # we don't want to overwrite outputs, just check the CLI works,\n \"--no-output-teal\",\n \"--no-output-bytecode\",\n \"--no-output-source-map\",\n \"--no-output-client\",\n \"--no-output-arc32\",\n *map(str, args),\n ],\n text=text,\n # capture stdout\n stdout=subprocess.PIPE,\n # redirect stderr to stdout, so they're interleaved in the correct ordering\n stderr=subprocess.STDOUT,\n cwd=VCS_ROOT,\n check=False,\n env=ENV_WITH_NO_COLOR,\n )\n if check:\n assert result.returncode == 0, result.stdout\n return result\n\n\ndef run_puyapy_clientgen(\n path: Path,\n *flags: str,\n) -> subprocess.CompletedProcess[str]:\n puyapy_clientgen = shutil.which(\"puyapy-clientgen\")\n assert puyapy_clientgen is not None\n result = subprocess.run(\n [\n puyapy_clientgen,\n str(path),\n *flags,\n ],\n text=True,\n # capture stdout\n stdout=subprocess.PIPE,\n # redirect stderr to stdout, so they're interleaved in the correct ordering\n stderr=subprocess.STDOUT,\n cwd=VCS_ROOT,\n check=False,\n env=ENV_WITH_NO_COLOR,\n )\n assert result.returncode == 0, result.stdout\n return result\n\n\ndef test_run_no_args() -> None:\n result = run_puyapy([], check=False)\n assert result.returncode == 2\n\n\ndef test_run_version() -> None:\n result = run_puyapy([\"--version\"], check=False)\n assert result.returncode == 0\n assert result.stdout.startswith(\"puyapy\")\n\n\ndef test_run_not_python() -> None:\n result = run_puyapy([\"pyproject.toml\"], check=False)\n assert result.returncode == 1\n assert \"error: invalid syntax\" in result.stdout\n\n\ndef test_run_single_file() -> None:\n run_puyapy([TEST_CASES_DIR \/ Path(\"simple\") \/ \"contract.py\"])\n\n\ndef test_run_single_file_with_other_references(tmpdir: Path) -> None:\n run_puyapy(\n [\n TEST_CASES_DIR \/ \"compile\" \/ \"factory.py\",\n \"--output-bytecode\",\n \"--out-dir\",\n str(tmpdir),\n ]\n )\n\n\ndef test_run_multiple_files() -> None:\n run_puyapy(\n [\n EXAMPLES_DIR \/ Path(\"calculator\") \/ \"contract.py\",\n TEST_CASES_DIR \/ Path(\"simple\") \/ \"contract.py\",\n ]\n )\n\n\ndef test_run_directory() -> None:\n run_puyapy([TEST_CASES_DIR \/ \"simple\"])\n\n\ndef test_puyapy_clientgen_arc32(tmpdir: Path) -> None:\n # ARC-32 output differs slightly from ARC-56, so we are just checking it doesn't error\n # and ignore the generated artifact\n path = TEST_CASES_DIR \/ \"arc_56\" \/ \"out\" \/ \"Contract.arc32.json\"\n run_puyapy_clientgen(path, \"--out-dir\", str(tmpdir))\n\n\ndef test_puyapy_clientgen_arc56() -> None:\n path = TEST_CASES_DIR \/ \"arc_56\" \/ \"out\" \/ \"Contract.arc56.json\"\n run_puyapy_clientgen(path)\n","repo_name":"algorandfoundation\/puya","path":"tests\/test_cli.py","language":"Python","license":"NOASSERTION","size":3379} {"code":"import json\nimport os\nimport shutil\nimport subprocess\nimport typing\nfrom pathlib import Path\n\nimport attrs\n\nfrom puya import log\nfrom puyapy.options import PuyaPyOptions\nfrom tests import VCS_ROOT\nfrom tests.utils import (\n APPROVAL_EXTENSIONS,\n PuyaTestCase,\n compile_src_from_options,\n get_relative_path,\n load_template_vars,\n)\n\nENV_WITH_NO_COLOR = dict(os.environ) | {\n \"NO_COLOR\": \"1\", # disable colour output\n \"PYTHONUTF8\": \"1\", # force utf8 on windows\n}\nSUFFIX_O0 = \"_unoptimized\"\nSUFFIX_O1 = \"\"\nSUFFIX_O2 = \"_O2\"\n\n\ndef test_compile(test_case: PuyaTestCase) -> None:\n _remove_output(test_case.path)\n _compile_no_optimization(test_case)\n _compile_with_level1_optimizations(test_case)\n _compile_with_level2_optimizations(test_case)\n diff = _check_for_diff(test_case.path)\n assert not diff, f\"Uncommitted changes were found:\\n{diff}\"\n\n\ndef _compile_test_case(\n test_case: PuyaTestCase, suffix: str, log_path: Path | None = None, **options: typing.Any\n) -> None:\n path = test_case.path\n assert path.is_dir()\n dst_out_dir = path \/ (\"out\" + suffix)\n\n prefix, template_vars = load_template_vars(test_case.template_vars_path)\n puya_options = PuyaPyOptions(\n paths=(test_case.path,),\n out_dir=dst_out_dir,\n log_level=log.LogLevel.debug,\n template_vars_prefix=prefix,\n cli_template_definitions=template_vars,\n **options,\n )\n compile_result = compile_src_from_options(puya_options)\n\n if log_path:\n root_dir = compile_result.root_dir\n log_options = attrs.evolve(puya_options, paths=(Path(test_case.name),))\n logs = [_log_to_str(log_, root_dir) for log_ in compile_result.logs]\n logs.insert(0, f\"debug: {log_options}\")\n log_path.write_text(\n \"\\n\".join(map(_normalize_log, logs)),\n encoding=\"utf8\",\n )\n\n # normalize ARC-56 output\n for arc56_file in dst_out_dir.rglob(\"*.arc56.json\"):\n _normalize_arc56(arc56_file)\n\n\ndef _normalize_path(path: Path | str) -> str:\n return str(path).replace(\"\\\\\", \"\/\")\n\n\n_NORMALIZED_VCS = _normalize_path(VCS_ROOT)\n\n\ndef _normalize_log(log: str) -> str:\n return log.replace(\"\\\\\", \"\/\").replace(_NORMALIZED_VCS, \"\")\n\n\ndef _log_to_str(log: log.Log, root_dir: Path) -> str:\n if log.location and log.location.file:\n relative_path = get_relative_path(log.location, root_dir)\n col = f\":{log.location.column + 1}\" if log.location.column else \"\"\n location = f\"{relative_path!s}:{log.location.line}{col} \"\n else:\n location = \"\"\n return f\"{location}{log.level}: {log.message}\"\n\n\ndef _compile_no_optimization(test_case: PuyaTestCase) -> None:\n _compile_test_case(\n test_case,\n SUFFIX_O0,\n optimization_level=0,\n output_teal=True,\n output_bytecode=True,\n output_destructured_ir=True,\n )\n\n\ndef _compile_with_level1_optimizations(test_case: PuyaTestCase) -> None:\n _compile_test_case(\n test_case,\n SUFFIX_O1,\n log_path=test_case.path \/ \"puya.log\",\n optimization_level=1,\n output_teal=True,\n output_bytecode=True,\n output_source_map=True,\n output_arc32=True,\n output_arc56=True,\n output_awst=True,\n output_ssa_ir=True,\n output_optimization_ir=True,\n output_destructured_ir=True,\n output_memory_ir=True,\n output_client=True,\n )\n\n\ndef _compile_with_level2_optimizations(test_case: PuyaTestCase) -> None:\n _compile_test_case(\n test_case,\n SUFFIX_O2,\n optimization_level=2,\n debug_level=0,\n output_teal=True,\n output_bytecode=True,\n output_destructured_ir=True,\n )\n\n\ndef _remove_output(path: Path) -> None:\n (path \/ \"puya.log\").unlink(missing_ok=True)\n for out_suffix in (SUFFIX_O0, SUFFIX_O1, SUFFIX_O2):\n out_dir = path \/ f\"out{out_suffix}\"\n if out_dir.exists():\n for file in out_dir.iterdir():\n if file.suffix in APPROVAL_EXTENSIONS:\n if file.is_dir():\n shutil.rmtree(file)\n else:\n file.unlink()\n\n\ndef _check_for_diff(path: Path) -> str | None:\n git = shutil.which(\"git\")\n assert git, \"could not find git\"\n assert path.is_dir()\n result = subprocess.run(\n [git, \"diff\", str(path)],\n check=True,\n capture_output=True,\n cwd=VCS_ROOT,\n )\n return result.stdout.decode(\"utf8\")\n\n\ndef _normalize_arc56(path: Path) -> None:\n arc56 = json.loads(path.read_text())\n compiler_version = arc56.get(\"compilerInfo\", {}).get(\"compilerVersion\", {})\n compiler_version[\"major\"] = 99\n compiler_version[\"minor\"] = 99\n compiler_version[\"patch\"] = 99\n path.write_text(json.dumps(arc56, indent=4), encoding=\"utf8\")\n","repo_name":"algorandfoundation\/puya","path":"tests\/test_compile.py","language":"Python","license":"NOASSERTION","size":4842} {"code":"import typing\n\nimport algokit_utils\nimport algokit_utils.config\nimport attrs\nimport pytest\nfrom algosdk.atomic_transaction_composer import (\n AtomicTransactionComposer,\n)\nfrom algosdk.source_map import SourceMap\nfrom algosdk.v2client.algod import AlgodClient\nfrom algosdk.v2client.models import SimulateRequest, SimulateTraceConfig\n\nfrom puya.arc32 import create_arc32_json\nfrom puya.compilation_artifacts import CompiledContract, DebugInfo\nfrom puyapy.options import PuyaPyOptions\nfrom tests import TEST_CASES_DIR\nfrom tests.utils import compile_src_from_options\n\npytestmark = pytest.mark.localnet\n\n\ndef test_debug(algod_client: AlgodClient, account: algokit_utils.Account) -> None:\n contract_src = TEST_CASES_DIR \/ \"debug\" \/ \"contract.py\"\n result = compile_src_from_options(\n PuyaPyOptions(\n paths=(contract_src,),\n optimization_level=1,\n debug_level=2,\n )\n )\n (contract,) = result.teal\n assert isinstance(contract, CompiledContract), \"Compilation artifact must be a contract\"\n approval_src = algokit_utils.replace_template_variables(\n contract.approval_program.teal_src, {\"A_MULT\": 1000}\n )\n clear_src = contract.clear_program.teal_src\n arc32 = create_arc32_json(approval_src, clear_src, contract.metadata)\n app_spec = algokit_utils.ApplicationSpecification.from_json(arc32)\n client = algokit_utils.ApplicationClient(\n algod_client,\n app_spec,\n signer=account,\n )\n client.create()\n\n atc = AtomicTransactionComposer()\n client.compose_call(atc, \"test\", x=1, y=2, z=3)\n simulate_request = SimulateRequest(\n txn_groups=[],\n allow_more_logs=True,\n allow_empty_signatures=True,\n exec_trace_config=SimulateTraceConfig(\n enable=True,\n stack_change=True,\n scratch_change=True,\n state_change=True,\n ),\n )\n response = atc.simulate(algod_client, simulate_request)\n approval_debug_map = contract.approval_program.debug_info\n assert approval_debug_map is not None\n clear_debug_map = contract.clear_program.debug_info\n assert clear_debug_map is not None\n assert client.approval\n _check_teal_map_with_puya_map(client.approval.source_map, approval_debug_map)\n _check_trace_with_puya_map(response.simulate_response, approval_debug_map)\n\n assert client.clear\n _check_teal_map_with_puya_map(client.clear.source_map, clear_debug_map)\n\n\nJson = dict[str, typing.Any]\n\n\ndef _check_teal_map_with_puya_map(teal_source_map: SourceMap, puya_map: DebugInfo) -> None:\n op_pc_offset = puya_map.op_pc_offset\n # if a non-zero offset is provided increment by 1 to account for version byte in line_to_pc map\n if op_pc_offset:\n op_pc_offset += 1\n line, pcs = sorted(teal_source_map.line_to_pc.items())[op_pc_offset]\n pc_offset = pcs[0]\n\n puya_source_map = SourceMap(attrs.asdict(puya_map))\n events = puya_map.pc_events\n max_puya_pc = max(puya_source_map.pc_to_line) + pc_offset\n assert max_puya_pc in teal_source_map.pc_to_line, \"expected max puya pc to be in teal src map\"\n assert (\n max_puya_pc + 1 not in teal_source_map.pc_to_line\n ), \"expected teal pc to not go beyond puya pc\"\n missing_event_pcs = [\n pc\n for pc in (int(pc_str) + pc_offset for pc_str in events)\n if pc not in teal_source_map.pc_to_line\n ]\n assert not missing_event_pcs, \"expected all event pcs to be in teal source map\"\n\n\ndef _check_trace_with_puya_map(simulate: Json, puya_map: DebugInfo) -> None:\n op_pc_offset = puya_map.op_pc_offset\n approval_trace = simulate[\"txn-groups\"][0][\"txn-results\"][0][\"exec-trace\"][\n \"approval-program-trace\"\n ]\n offset_trace = approval_trace[op_pc_offset]\n pc_offset = offset_trace[\"pc\"]\n pc_events = {int(pc): event for pc, event in puya_map.pc_events.items()}\n missing_pcs = [\n pc\n for pc in (int(pc_trace[\"pc\"]) for pc_trace in approval_trace)\n if pc >= pc_offset and (pc - pc_offset) not in pc_events\n ]\n assert not missing_pcs, \"expected relative pcs to be in pc_events\"\n","repo_name":"algorandfoundation\/puya","path":"tests\/test_debug.py","language":"Python","license":"NOASSERTION","size":4118} {"code":"import base64\nimport collections\nimport inspect\nimport os\nimport random\nimport re\nimport typing\nfrom collections.abc import Callable, Collection, Iterable\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\nfrom textwrap import dedent\n\nimport algokit_utils\nimport algosdk.constants\nimport attrs\nimport prettytable\nimport pytest\nfrom algokit_utils import (\n Account,\n LogicError,\n Program,\n execute_atc_with_logic_error,\n)\nfrom algosdk import constants, transaction\nfrom algosdk.atomic_transaction_composer import (\n AtomicTransactionComposer,\n SimulateAtomicTransactionResponse,\n TransactionWithSigner,\n)\nfrom algosdk.encoding import decode_address\nfrom algosdk.logic import get_application_address\nfrom algosdk.transaction import ApplicationCallTxn, ApplicationCreateTxn, OnComplete, StateSchema\nfrom algosdk.v2client.algod import AlgodClient\nfrom algosdk.v2client.models import SimulateRequest, SimulateTraceConfig\nfrom nacl.signing import SigningKey\n\nfrom puya.artifact_metadata import ContractState\nfrom puya.avm import AVMType\nfrom puya.compilation_artifacts import CompiledContract\nfrom puyapy.options import PuyaPyOptions\nfrom tests import EXAMPLES_DIR, TEST_CASES_DIR\nfrom tests.utils import compile_src_from_options\n\npytestmark = pytest.mark.localnet\n\nDEFAULT_MAX_OPTIMIZATION_LEVEL = int(os.getenv(\"MAX_TEST_OPTIMIZATION_LEVEL\", \"2\"))\nBYTES_ACTION = 1\nUINT_ACTION = 2\nNONE_ACTION = 3\nINTC_BLOCK = 0x20\nBYTEC_BLOCK = 0x26\n\n\ndef decode_int(result: str) -> int:\n return int.from_bytes(decode_bytes(result), byteorder=\"big\", signed=False)\n\n\ndef decode_bytes(result: str) -> bytes:\n return base64.b64decode(result)\n\n\ndef decode_utf8(result: str) -> str:\n return decode_bytes(result).decode(\"utf8\")\n\n\ndef encode_bytes(value: bytes) -> str:\n return base64.b64encode(value).decode()\n\n\ndef decode_logs(logs: list[str], log_format: str) -> list[str | bytes | int]:\n assert len(logs) == len(log_format)\n result = list[str | bytes | int]()\n\n for fmt, log in zip(log_format, logs, strict=True):\n match fmt:\n case \"i\":\n result.append(decode_int(log))\n case \"u\":\n result.append(decode_utf8(log))\n case \"b\":\n result.append(decode_bytes(log))\n case _:\n raise ValueError(f\"Unexpected format: {fmt}\")\n return result\n\n\ndef encode_utf8(value: str) -> str:\n return encode_bytes(value.encode(\"utf8\"))\n\n\n@attrs.define(kw_only=True)\nclass Compilation:\n approval: Program\n clear: Program\n local_schema: StateSchema | None\n global_schema: StateSchema | None\n\n\ndef assemble_src(contract: CompiledContract, client: AlgodClient) -> Compilation:\n def state_to_schema(state: Collection[ContractState]) -> StateSchema:\n return StateSchema(\n num_uints=sum(1 for x in state if x.storage_type is AVMType.uint64),\n num_byte_slices=sum(1 for x in state if x.storage_type is AVMType.bytes),\n )\n\n approval_program = Program(contract.approval_program.teal_src, client)\n clear_program = Program(contract.clear_program.teal_src, client)\n compilation = Compilation(\n approval=approval_program,\n clear=clear_program,\n local_schema=state_to_schema(contract.metadata.local_state.values()),\n global_schema=state_to_schema(contract.metadata.global_state.values()),\n )\n return compilation\n\n\nAppArgs: typing.TypeAlias = int | str | bytes\n\n\n@attrs.frozen\nclass AppTransactionParameters:\n args: list[AppArgs] = attrs.field(factory=list)\n accounts: list[str] | None = None\n assets: list[int] | None = None\n on_complete: OnComplete = OnComplete.NoOpOC\n sp: transaction.SuggestedParams | None = None\n extra_pages: int | None = None\n add_random_note: bool = False\n\n\nGroupTransactionsProvider: typing.TypeAlias = Callable[[int], Iterable[TransactionWithSigner]]\n\n\n@attrs.frozen\nclass AppCallRequest(AppTransactionParameters):\n increase_budget: int = 0\n debug_level: int = 1\n trace_output: Path | None = None\n group_transactions: GroupTransactionsProvider | None = None\n\n def get_trace_output_path_for_level(self, opt_level: int) -> Path | None:\n path = self.trace_output\n if path is None:\n return None\n return path.with_name(path.stem + \"\".join((f\".O{opt_level}\", *path.suffixes)))\n\n\n@attrs.frozen\nclass AppCallResult:\n logs: list[str]\n global_state_deltas: dict[str, typing.Any]\n local_state_deltas: dict[tuple[str, str], typing.Any]\n app_id: int = attrs.field(eq=False)\n\n @property\n def app_address(self) -> str:\n return get_application_address(self.app_id)\n\n def decode_logs(self, log_format: str) -> list[str | bytes | int]:\n \"\"\"\n log_format should contain a sequence of characters representing the desired types:\n b -> bytes, i -> int or u -> str\n \"\"\"\n return decode_logs(self.logs, log_format)\n\n\nclass ATCRunner:\n def __init__(\n self,\n client: AlgodClient,\n account: Account,\n compilation: Compilation,\n op_up_app_id: int | None = None,\n ) -> None:\n self.atc = AtomicTransactionComposer()\n self.compilation = compilation\n self.sender = account.address\n self.signer = account.signer\n self.client = client\n self.op_up_app_id = op_up_app_id\n self.sp = client.suggested_params()\n\n def add_deployment_transaction(\n self,\n request: AppTransactionParameters,\n ) -> typing.Self:\n self.atc.add_transaction(\n TransactionWithSigner(\n txn=ApplicationCreateTxn(\n approval_program=self.compilation.approval.raw_binary,\n clear_program=self.compilation.clear.raw_binary,\n local_schema=self.compilation.local_schema,\n global_schema=self.compilation.global_schema,\n **self._txn_args_from_request(request),\n ),\n signer=self.signer,\n )\n )\n return self\n\n def _txn_args_from_request(self, request: AppTransactionParameters) -> dict[str, object]:\n return {\n \"sender\": self.sender,\n \"sp\": request.sp or self.sp,\n \"on_complete\": request.on_complete,\n \"accounts\": request.accounts,\n \"foreign_assets\": request.assets,\n \"app_args\": request.args,\n \"extra_pages\": request.extra_pages,\n \"note\": random.randbytes(8) if request.add_random_note else None,\n }\n\n def add_transactions(\n self, *, app_id: int, get_group_transactions: GroupTransactionsProvider | None\n ) -> typing.Self:\n if get_group_transactions:\n for txn in get_group_transactions(app_id):\n self.atc.add_transaction(txn)\n return self\n\n def add_app_call_transaction(\n self,\n app_id: int,\n request: AppTransactionParameters,\n ) -> typing.Self:\n self.atc.add_transaction(\n TransactionWithSigner(\n txn=ApplicationCallTxn(\n index=app_id,\n **self._txn_args_from_request(request),\n ),\n signer=self.signer,\n )\n )\n return self\n\n def add_fund_transaction(self, app_id: int, micro_algos: int) -> typing.Self:\n self.atc.add_transaction(\n TransactionWithSigner(\n txn=transaction.PaymentTxn(\n sender=self.sender,\n receiver=get_application_address(app_id),\n amt=micro_algos,\n sp=self.sp,\n ),\n signer=self.signer,\n )\n )\n return self\n\n def add_op_ups(self, *, count: int) -> typing.Self:\n for idx in range(count):\n assert self.op_up_app_id is not None\n self.add_app_call_transaction(\n app_id=self.op_up_app_id,\n request=AppTransactionParameters(\n args=[idx],\n on_complete=OnComplete.NoOpOC,\n ),\n )\n return self\n\n def run(self, trace_path: Path | None = None) -> AppCallResult:\n if trace_path is not None:\n self._simulate_and_write_trace(trace_path)\n\n return self._execute_with_logic_error()\n\n def _simulate_and_write_trace(\n self,\n trace_path: Path,\n *,\n allow_more_logs: bool = True,\n allow_empty_signatures: bool = True,\n ) -> None:\n simulate_request = SimulateRequest(\n txn_groups=[],\n allow_more_logs=allow_more_logs,\n allow_empty_signatures=allow_empty_signatures,\n exec_trace_config=SimulateTraceConfig(\n enable=True, stack_change=True, scratch_change=True\n ),\n )\n simulate_response = self.atc.simulate(self.client, simulate_request)\n self._write_trace_to_file(simulate_response, trace_path)\n\n def _execute_with_logic_error(self) -> AppCallResult:\n response = execute_atc_with_logic_error(\n self.atc,\n self.client,\n self.compilation.approval.teal,\n approval_source_map=self.compilation.approval.source_map,\n )\n (txn_id, *_) = response.tx_ids\n assert response.confirmed_round, \"Transaction not confirmed\"\n txn_info = self.client.pending_transaction_info(txn_id)\n assert isinstance(txn_info, dict)\n app_id: int = txn_info.get(\"application-index\", -1)\n logs = txn_info.get(\"logs\", [])\n global_state_deltas = txn_info.get(\"global-state-delta\", [])\n global_state_deltas_by_key = {\n delta[\"key\"]: delta[\"value\"] for delta in global_state_deltas\n }\n assert len(global_state_deltas) == len(global_state_deltas_by_key)\n local_state_deltas = txn_info.get(\"local-state-delta\", [])\n local_state_deltas_by_address_and_key = {\n (account[\"address\"], delta[\"key\"]): delta[\"value\"]\n for account in local_state_deltas\n for delta in account[\"delta\"]\n }\n return AppCallResult(\n app_id=app_id,\n logs=logs,\n global_state_deltas=global_state_deltas_by_key,\n local_state_deltas=local_state_deltas_by_address_and_key,\n )\n\n def _write_trace_to_file(\n self,\n simulate_response: SimulateAtomicTransactionResponse,\n output_path: Path,\n ) -> None:\n def map_stack_addition(value: dict[str, typing.Any]) -> int | str:\n match value[\"type\"]:\n case 1:\n b64 = value.get(\"bytes\")\n if b64 is None:\n return \"0x\"\n try:\n utf8 = decode_utf8(b64)\n except UnicodeDecodeError:\n pass\n else:\n if utf8.isprintable():\n return f'\"{utf8}\"'\n return \"0x\" + decode_bytes(b64).hex().upper()\n case 2:\n return int(value.get(\"uint\", 0))\n case _:\n raise NotImplementedError(f\"Mapping not implemented: {value}\")\n\n approval_source_map = self.compilation.approval.source_map\n approval_src = self.compilation.approval.teal.splitlines()\n\n (txn_group,) = simulate_response.simulate_response[\"txn-groups\"]\n txn_result, *_ = txn_group[\"txn-results\"]\n approval_program_trace = txn_result[\"exec-trace\"][\"approval-program-trace\"]\n\n writer = prettytable.PrettyTable(\n field_names=[\"PC\", \"Teal\", \"Stack\"],\n header=True,\n border=False,\n padding_width=0,\n left_padding_width=0,\n right_padding_width=1,\n align=\"l\",\n )\n stack = list[int | str]()\n for t in approval_program_trace:\n pc = t[\"pc\"]\n teal_line = approval_source_map.get_line_for_pc(pc)\n op_code = self.compilation.approval.raw_binary[pc]\n if teal_line == 0 and op_code in (INTC_BLOCK, BYTEC_BLOCK):\n # algod collects constants and creates constant blocks for them,\n # however they do not have a corresponding teal line to map to\n # so handle that specifically\n teal = \"\" if op_code == INTC_BLOCK else \"\"\n else:\n teal = \"\" if teal_line is None else approval_src[teal_line]\n teal = teal.split(\"\/\/\", maxsplit=1)[0].strip()\n for _ in range(t.get(\"stack-pop-count\", 0)):\n assert stack, \"Oh noes, the stack is empty, we can't pop anything\"\n stack.pop()\n stack.extend(map(map_stack_addition, t.get(\"stack-additions\", [])))\n\n writer.add_row(\n [\n str(pc),\n teal,\n \", \".join(map(str, stack)),\n ]\n )\n output_path.write_text(writer.get_string())\n\n\n@attrs.define\nclass _TestHarness:\n client: AlgodClient = attrs.field(on_setattr=attrs.setters.frozen)\n account: Account = attrs.field(on_setattr=attrs.setters.frozen)\n op_up_app_id: int = attrs.field(on_setattr=attrs.setters.frozen)\n max_optimization_level: int = attrs.field(\n default=DEFAULT_MAX_OPTIMIZATION_LEVEL, on_setattr=attrs.setters.frozen\n )\n _app_ids_by_level: dict[int, int] = attrs.field(factory=dict, init=False)\n _compilations_by_level: dict[int, Compilation] = attrs.field(factory=dict, init=False)\n\n @property\n def sender(self) -> str:\n return self.account.address\n\n @property\n def _optimization_levels(self) -> range:\n return range(self.max_optimization_level + 1)\n\n def deploy_from_closure(\n self,\n closure: typing.Callable[[], None],\n request: AppCallRequest | None = None,\n ) -> AppCallResult:\n with TemporaryDirectory() as tmp_dir:\n src_path = Path(tmp_dir) \/ \"contract.py\"\n source = inspect.getsource(closure)\n closure_lines = source.splitlines()[1:]\n closure_text_block = dedent(\"\\n\".join(closure_lines))\n src_path.write_text(closure_text_block, encoding=\"utf8\")\n return self.deploy(src_path, request)\n\n def deploy(\n self,\n src_path: Path,\n request: AppCallRequest | None = None,\n ) -> AppCallResult:\n if request is None:\n request = AppCallRequest()\n\n self._compilations_by_level = {\n o_level: self._compile_and_assemble_src(\n src_path, optimization_level=o_level, debug_level=request.debug_level\n )\n for o_level in self._optimization_levels\n }\n\n o_level_deploy_results = {\n o_level: (\n self._new_runner(compilation)\n .add_transactions(app_id=0, get_group_transactions=request.group_transactions)\n .add_deployment_transaction(request)\n .add_op_ups(count=request.increase_budget)\n .run(trace_path=request.get_trace_output_path_for_level(o_level))\n )\n for o_level, compilation in self._compilations_by_level.items()\n }\n self._app_ids_by_level = {\n o_level: deploy_result.app_id\n for o_level, deploy_result in o_level_deploy_results.items()\n }\n return self._get_singularly_valid_result(o_level_deploy_results)\n\n def fund(self, micro_algos: int) -> None:\n for o_level, compilation in self._compilations_by_level.items():\n (\n self._new_runner(compilation)\n .add_fund_transaction(\n app_id=self._app_ids_by_level[o_level],\n micro_algos=micro_algos,\n )\n .run()\n )\n\n def call(self, request: AppCallRequest) -> AppCallResult:\n o_level_results = {\n o_level: (\n self._new_runner(compilation)\n .add_transactions(\n app_id=self._app_ids_by_level[o_level],\n get_group_transactions=request.group_transactions,\n )\n .add_app_call_transaction(\n app_id=self._app_ids_by_level[o_level],\n request=request,\n )\n .add_op_ups(count=request.increase_budget)\n .run(trace_path=request.get_trace_output_path_for_level(o_level))\n )\n for o_level, compilation in self._compilations_by_level.items()\n }\n return self._get_singularly_valid_result(o_level_results)\n\n def _get_singularly_valid_result(\n self, results_by_level: dict[int, AppCallResult]\n ) -> AppCallResult:\n # this might seem a bit weird, but it's to get the most comprehensive output possible\n first_result, *_ = results_by_level.values()\n assert results_by_level == {o: first_result for o in self._optimization_levels}\n return first_result\n\n def _new_runner(self, compilation: Compilation) -> ATCRunner:\n return ATCRunner(\n client=self.client,\n account=self.account,\n compilation=compilation,\n op_up_app_id=self.op_up_app_id,\n )\n\n def _compile_and_assemble_src(\n self, src_path: Path, optimization_level: int, debug_level: int\n ) -> Compilation:\n result = compile_src_from_options(\n PuyaPyOptions(\n paths=(src_path,),\n optimization_level=optimization_level,\n debug_level=debug_level,\n )\n )\n (contract,) = result.teal\n assert isinstance(contract, CompiledContract), \"Compilation artifact must be a contract\"\n\n return assemble_src(contract=contract, client=self.client)\n\n\n@pytest.fixture(scope=\"session\")\ndef no_op_app_id(algod_client: AlgodClient, account: Account, worker_id: str) -> int:\n program = Program(\"#pragma version 8\\npushint 1\", algod_client)\n compilation = Compilation(\n approval=program, clear=program, global_schema=None, local_schema=None\n )\n result = (\n ATCRunner(client=algod_client, account=account, compilation=compilation)\n .add_deployment_transaction(\n AppTransactionParameters(\n args=[worker_id], # this ensures a unique instance per parallel test run\n ),\n )\n .run()\n )\n return result.app_id\n\n\n@pytest.fixture\ndef harness(algod_client: AlgodClient, account: Account, no_op_app_id: int) -> _TestHarness:\n return _TestHarness(algod_client, account, op_up_app_id=no_op_app_id)\n\n\ndef test_ssa(harness: _TestHarness) -> None:\n result = harness.deploy(\n TEST_CASES_DIR \/ \"ssa\",\n AppCallRequest(trace_output=TEST_CASES_DIR \/ \"ssa\" \/ \"out\" \/ \"trace.log\"),\n )\n\n assert result.decode_logs(\"i\") == [102]\n\n\ndef test_tuple_support(harness: _TestHarness) -> None:\n result = harness.deploy(TEST_CASES_DIR \/ \"tuple_support\" \/ \"tuple_support.py\")\n assert result.decode_logs(\"iuiiiuuuuu\") == [\n 306,\n \"Hello, world!\",\n 0,\n 2,\n 1,\n \"nanananana\",\n \"non_empty_tuple called\",\n \"not empty\",\n \"get_uint_with_side_effect called\",\n \"not empty2\",\n ]\n\n\ndef test_tuple_comparisons(harness: _TestHarness) -> None:\n result = harness.deploy(TEST_CASES_DIR \/ \"tuple_support\" \/ \"tuple_comparisons.py\")\n expected_log_values = list(range(42, 48))\n assert len(result.logs) == len(expected_log_values)\n assert result.decode_logs(\"i\" * len(expected_log_values)) == expected_log_values\n\n\ndef test_chained_assignment(harness: _TestHarness) -> None:\n result = harness.deploy(TEST_CASES_DIR \/ \"chained_assignment\")\n assert result.decode_logs(\"u\") == [\"Hello, world! \ud83d\udc4b\"]\n\n\ndef test_callsub(harness: _TestHarness) -> None:\n result = harness.deploy(TEST_CASES_DIR \/ \"callsub\")\n assert result.decode_logs(\"iii\") == [42, 1, 2]\n\n\ndef test_calculator(harness: _TestHarness) -> None:\n src_path = EXAMPLES_DIR \/ \"calculator\"\n add, sub, mul, div = 1, 2, 3, 4\n\n result = harness.deploy(src_path, AppCallRequest(args=[add, 1, 2]))\n assert result.decode_logs(\"iiu\") == [1, 2, \"1 + 2 = 3\"]\n\n result = harness.deploy(src_path, AppCallRequest(args=[sub, 45, 2]))\n assert result.decode_logs(\"iiu\") == [45, 2, \"45 - 2 = 43\"]\n\n result = harness.deploy(src_path, AppCallRequest(args=[mul, 42, 42]))\n assert result.decode_logs(\"iiu\") == [42, 42, \"42 * 42 = 1764\"]\n\n result = harness.deploy(src_path, AppCallRequest(args=[div, 8, 2]))\n assert result.decode_logs(\"iiu\") == [8, 2, \"8 \/\/ 2 = 4\"]\n\n with pytest.raises(algokit_utils.LogicError):\n harness.deploy(src_path)\n\n with pytest.raises(algokit_utils.LogicError):\n harness.deploy(src_path, AppCallRequest(args=[9, 20, 8]))\n\n\ndef test_subroutine_parameter_overwrite(harness: _TestHarness) -> None:\n def test() -> None:\n from algopy import Bytes, Contract, log, op, subroutine\n\n class Exclaimer(Contract):\n def approval_program(self) -> bool:\n num_args = op.Txn.num_app_args\n assert num_args == 1, \"expected one arg\"\n msg = op.Txn.application_args(0)\n exclaimed = self.exclaim(msg)\n log(exclaimed)\n return True\n\n @subroutine\n def exclaim(self, value: Bytes) -> Bytes:\n value = value + b\"!\"\n return value\n\n def clear_state_program(self) -> bool:\n return True\n\n result = harness.deploy_from_closure(test, AppCallRequest(args=[b\"whoop\"]))\n assert result.decode_logs(\"u\") == [\"whoop!\"]\n\n\ndef test_nested_loops(harness: _TestHarness) -> None:\n result = harness.deploy(TEST_CASES_DIR \/ \"nested_loops\", AppCallRequest(increase_budget=15))\n x, y = result.decode_logs(\"ii\")\n assert x == 192\n assert y == 285\n\n\ndef test_with_reentrancy(harness: _TestHarness) -> None:\n result = harness.deploy(TEST_CASES_DIR \/ \"with_reentrancy\")\n logs = result.decode_logs(\"iuuuuuu\")\n assert logs == [\n 5,\n \"silly3 = 8\",\n \"silly2 = 8\",\n \"silly = 6\",\n \"silly3 = 5\",\n \"silly2 = 5\",\n \"silly = 3\",\n ]\n\n\ndef test_conditional_expressions(harness: _TestHarness) -> None:\n result = harness.deploy(TEST_CASES_DIR \/ \"conditional_expressions\" \/ \"contract.py\")\n logs = result.decode_logs((\"u\" * 6) + \"i\")\n counts = collections.Counter(logs[:-1])\n assert counts == {\n \"expensive_op\": 3,\n \"side_effecting_op\": 3,\n }\n assert logs[-1] == 19\n\n\ndef test_literal_conditional_expressions(harness: _TestHarness) -> None:\n harness.deploy(TEST_CASES_DIR \/ \"conditional_expressions\" \/ \"literals.py\")\n\n\ndef test_contains_operator(harness: _TestHarness) -> None:\n harness.deploy(TEST_CASES_DIR \/ \"contains\", request=AppCallRequest(increase_budget=1))\n\n\ndef test_boolean_binary_ops(harness: _TestHarness) -> None:\n result = harness.deploy(\n TEST_CASES_DIR \/ \"boolean_binary_ops\", request=AppCallRequest(increase_budget=1)\n )\n logs = set(result.decode_logs(\"u\" * 12))\n assert logs == {\n # AND\n \"lhs_true_and_true\",\n \"rhs_true_and_true\",\n \"lhs_true_and_false\",\n \"rhs_true_and_false\",\n \"lhs_false_and_true\",\n # \"rhs_false_and_true\",\n \"lhs_false_and_false\",\n # \"rhs_false_and_false\",\n # OR\n \"lhs_true_or_true\",\n # \"rhs_true_or_true\",\n \"lhs_true_or_false\",\n # \"rhs_true_or_false\",\n \"lhs_false_or_true\",\n \"rhs_false_or_true\",\n \"lhs_false_or_false\",\n \"rhs_false_or_false\",\n }\n\n\ndef test_biguint_binary_ops(harness: _TestHarness) -> None:\n harness.deploy(TEST_CASES_DIR \/ \"biguint_binary_ops\")\n\n\ndef test_unssa(harness: _TestHarness) -> None:\n result = harness.deploy(\n TEST_CASES_DIR \/ \"unssa\",\n AppCallRequest(\n increase_budget=1,\n trace_output=TEST_CASES_DIR \/ \"unssa\" \/ \"out\" \/ \"execution_trace.log\",\n ),\n )\n result1, result2 = result.decode_logs(\"ii\")\n assert result1 == 2\n assert result2 == 1\n\n\ndef test_byte_constants(harness: _TestHarness) -> None:\n result = harness.deploy(TEST_CASES_DIR \/ \"constants\" \/ \"byte_constants.py\")\n the_str, the_length = result.decode_logs(\"bi\")\n expected = b\"Base 16 encoded|Base 64 encoded|Base 32 encoded|UTF-8 Encoded\"\n assert the_str == expected\n assert the_length == len(expected)\n\n\ndef test_bytes_ops(harness: _TestHarness) -> None:\n harness.deploy(TEST_CASES_DIR \/ \"bytes_ops\")\n\n\ndef test_simplish(harness: _TestHarness) -> None:\n nickname = \"My Nicky Nick\"\n harness.deploy(TEST_CASES_DIR \/ \"simplish\")\n\n opt_in_result = harness.call(AppCallRequest(args=[nickname], on_complete=OnComplete.OptInOC))\n assert not opt_in_result.logs\n assert opt_in_result.local_state_deltas == {\n (harness.sender, encode_utf8(\"name\")): {\n \"action\": 1,\n \"bytes\": encode_utf8(nickname),\n },\n }\n assert not opt_in_result.global_state_deltas\n\n circle_report_result = harness.call(AppCallRequest(args=[\"circle_report\", 123]))\n assert circle_report_result.decode_logs(\"uu\") == [\n \"Approximate area and circumference of circle with radius 123 = 47529, 772\",\n \"Incrementing counter!\",\n ]\n assert not circle_report_result.local_state_deltas\n assert circle_report_result.global_state_deltas == {\n encode_utf8(\"counter\"): {\n \"action\": 2,\n \"uint\": 1,\n }\n }\n\n delete_result = harness.call(AppCallRequest(on_complete=OnComplete.DeleteApplicationOC))\n assert delete_result.decode_logs(\"u\") == [\"I was used 1 time(s) before I died\"]\n assert not delete_result.global_state_deltas\n assert not delete_result.local_state_deltas\n\n\ndef test_address(harness: _TestHarness) -> None:\n result = harness.deploy(TEST_CASES_DIR \/ \"constants\" \/ \"address_constant.py\")\n sender_bytes = decode_address(harness.sender)\n assert result.decode_logs(\"b\") == [sender_bytes]\n\n\ndef test_string_ops(harness: _TestHarness) -> None:\n harness.deploy(TEST_CASES_DIR \/ \"string_ops\", AppCallRequest(increase_budget=4))\n\n\ndef test_global_storage(harness: _TestHarness) -> None:\n harness.deploy(EXAMPLES_DIR \/ \"global_state\", AppCallRequest(increase_budget=1))\n\n\ndef test_local_storage(harness: _TestHarness) -> None:\n default_value = \"this is a default\"\n stored_value = \"testing 123\"\n harness.deploy(\n EXAMPLES_DIR \/ \"local_state\/local_state_contract.py\",\n AppCallRequest(on_complete=OnComplete.OptInOC),\n )\n\n get_data_with_default_result_1 = harness.call(\n AppCallRequest(args=[\"get_data_with_default\", default_value])\n )\n assert get_data_with_default_result_1.decode_logs(\"u\") == [default_value]\n\n set_data_result = harness.call(AppCallRequest(args=[\"set_data\", stored_value]))\n assert set_data_result.local_state_deltas == {\n (harness.sender, encode_utf8(\"local\")): {\n \"action\": 1,\n \"bytes\": encode_utf8(stored_value),\n }\n }\n\n get_data_with_default_result_2 = harness.call(\n AppCallRequest(args=[\"get_data_with_default\", default_value])\n )\n assert get_data_with_default_result_2.decode_logs(\"u\") == [stored_value]\n\n get_guaranteed_data_result = harness.call(AppCallRequest(args=[\"get_guaranteed_data\"]))\n assert get_guaranteed_data_result.decode_logs(\"u\") == [stored_value]\n\n get_data_or_assert_result = harness.call(AppCallRequest(args=[\"get_data_or_assert\"]))\n assert get_data_or_assert_result.decode_logs(\"u\") == [stored_value]\n\n delete_data_result = harness.call(AppCallRequest(args=[\"delete_data\"]))\n assert delete_data_result.local_state_deltas == {\n (harness.sender, encode_utf8(\"local\")): {\"action\": 3}\n }\n\n\ndef test_local_storage_with_offsets(harness: _TestHarness) -> None:\n default_value = \"this is a default\"\n stored_value = \"testing 123\"\n harness.deploy(\n EXAMPLES_DIR \/ \"local_state\/local_state_with_offsets.py\",\n AppCallRequest(on_complete=OnComplete.OptInOC),\n )\n\n def make_request(*args: AppArgs) -> AppCallRequest:\n return AppCallRequest(\n # yes this is redundant, sender is [0] anyway\n args=[1, *args],\n accounts=[harness.sender],\n )\n\n get_data_with_default_result_1 = harness.call(\n make_request(\"get_data_with_default\", default_value)\n )\n assert get_data_with_default_result_1.decode_logs(\"u\") == [default_value]\n\n set_data_result = harness.call(make_request(\"set_data\", stored_value))\n assert set_data_result.local_state_deltas == {\n (harness.sender, encode_utf8(\"local\")): {\n \"action\": 1,\n \"bytes\": encode_utf8(stored_value),\n }\n }\n\n get_data_with_default_result_2 = harness.call(\n make_request(\"get_data_with_default\", default_value)\n )\n assert get_data_with_default_result_2.decode_logs(\"u\") == [stored_value]\n\n get_guaranteed_data_result = harness.call(make_request(\"get_guaranteed_data\"))\n assert get_guaranteed_data_result.decode_logs(\"u\") == [stored_value]\n\n get_data_or_assert_result = harness.call(make_request(\"get_data_or_assert\"))\n assert get_data_or_assert_result.decode_logs(\"u\") == [stored_value]\n\n delete_data_result = harness.call(make_request(\"delete_data\"))\n assert delete_data_result.local_state_deltas == {\n (harness.sender, encode_utf8(\"local\")): {\"action\": 3}\n }\n\n\ndef test_unary(harness: _TestHarness) -> None:\n unary_path = TEST_CASES_DIR \/ \"unary\"\n harness.deploy(\n unary_path,\n AppCallRequest(trace_output=unary_path \/ \"out\" \/ \"execution_trace.log\"),\n )\n\n\ndef test_enumeration(harness: _TestHarness) -> None:\n harness.deploy(TEST_CASES_DIR \/ \"enumeration\", AppCallRequest(increase_budget=1))\n\n\ndef test_scratch_slots(harness: _TestHarness) -> None:\n harness.deploy(TEST_CASES_DIR \/ \"scratch_slots\" \/ \"contract.py\", AppCallRequest())\n\n\ndef test_scratch_slots_inheritance(harness: _TestHarness) -> None:\n harness.deploy(TEST_CASES_DIR \/ \"scratch_slots\" \/ \"contract2.py\", AppCallRequest())\n\n\ndef test_bytes_stubs(harness: _TestHarness) -> None:\n result = harness.deploy(\n TEST_CASES_DIR \/ \"stubs\" \/ \"bytes.py\",\n AppCallRequest(\n increase_budget=1, trace_output=TEST_CASES_DIR \/ \"stubs\" \/ \"out\" \/ \"bytes.log\"\n ),\n )\n assert result.decode_logs(\"u\") == [\"one_to_seven called\"]\n\n\ndef test_uint64_stubs(harness: _TestHarness) -> None:\n harness.deploy(TEST_CASES_DIR \/ \"stubs\" \/ \"uint64.py\", AppCallRequest(increase_budget=1))\n\n\ndef test_string_stubs(harness: _TestHarness) -> None:\n harness.deploy(TEST_CASES_DIR \/ \"stubs\" \/ \"string.py\", AppCallRequest(increase_budget=2))\n\n\ndef test_biguint_stubs(harness: _TestHarness) -> None:\n harness.deploy(TEST_CASES_DIR \/ \"stubs\" \/ \"biguint.py\", AppCallRequest(increase_budget=1))\n\n\ndef test_biguint_from_to_bytes(harness: _TestHarness) -> None:\n def test() -> None:\n from algopy import BigUInt, Contract, log, op\n\n class BigUIntByteTests(Contract):\n def approval_program(self) -> bool:\n arg = op.Txn.application_args(0)\n big_uint = BigUInt.from_bytes(arg)\n big_uint += 1\n log(big_uint.bytes)\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n result = harness.deploy_from_closure(test, AppCallRequest(args=[122]))\n assert result.decode_logs(\"i\") == [123]\n\n\ndef test_abi_string(harness: _TestHarness) -> None:\n harness.deploy(\n TEST_CASES_DIR \/ \"arc4_types\" \/ \"string.py\",\n AppCallRequest(trace_output=TEST_CASES_DIR \/ \"arc4_types\" \/ \"out\" \/ \"string.log\"),\n )\n\n\ndef test_abi_reference_types(harness: _TestHarness) -> None:\n harness.deploy(TEST_CASES_DIR \/ \"arc4_types\" \/ \"reference_types.py\")\n\n\ndef test_abi_numeric(harness: _TestHarness) -> None:\n harness.deploy(\n TEST_CASES_DIR \/ \"arc4_types\" \/ \"numeric.py\",\n AppCallRequest(trace_output=TEST_CASES_DIR \/ \"arc4_types\" \/ \"out\" \/ \"numeric.log\"),\n )\n\n\ndef test_abi_array(harness: _TestHarness) -> None:\n harness.deploy(\n TEST_CASES_DIR \/ \"arc4_types\" \/ \"array.py\",\n AppCallRequest(trace_output=TEST_CASES_DIR \/ \"arc4_types\" \/ \"out\" \/ \"array.log\"),\n )\n\n\ndef test_dynamic_bytes(harness: _TestHarness) -> None:\n harness.deploy(TEST_CASES_DIR \/ \"arc4_types\" \/ \"dynamic_bytes.py\")\n\n\ndef test_abi_bool(harness: _TestHarness) -> None:\n harness.deploy(\n TEST_CASES_DIR \/ \"arc4_types\" \/ \"bool.py\",\n AppCallRequest(trace_output=TEST_CASES_DIR \/ \"arc4_types\" \/ \"out\" \/ \"bool.log\"),\n )\n\n\ndef test_abi_tuple(harness: _TestHarness) -> None:\n harness.deploy(\n TEST_CASES_DIR \/ \"arc4_types\" \/ \"tuples.py\",\n AppCallRequest(trace_output=TEST_CASES_DIR \/ \"arc4_types\" \/ \"out\" \/ \"tuples.log\"),\n )\n\n\ndef test_abi_struct(harness: _TestHarness) -> None:\n result = harness.deploy(\n TEST_CASES_DIR \/ \"arc4_types\" \/ \"structs.py\",\n AppCallRequest(trace_output=TEST_CASES_DIR \/ \"arc4_types\" \/ \"out\" \/ \"structs.log\"),\n )\n x, y, z = result.decode_logs(\"bbb\")\n\n assert x == 0x1079F7E42E.to_bytes(8, \"big\")\n assert y == 0x4607097084.to_bytes(8, \"big\")\n assert z == 0b10100000.to_bytes()\n\n\ndef test_abi_mutations(harness: _TestHarness) -> None:\n harness.deploy(\n TEST_CASES_DIR \/ \"arc4_types\" \/ \"mutation.py\",\n AppCallRequest(\n extra_pages=1,\n trace_output=TEST_CASES_DIR \/ \"arc4_types\" \/ \"out\" \/ \"mutation.log\",\n increase_budget=15,\n ),\n )\n\n\ndef test_abi_mutable_params(harness: _TestHarness) -> None:\n harness.deploy(\n TEST_CASES_DIR \/ \"arc4_types\" \/ \"mutable_params.py\",\n AppCallRequest(\n extra_pages=1,\n trace_output=TEST_CASES_DIR \/ \"arc4_types\" \/ \"out\" \/ \"mutable_params.log\",\n increase_budget=1,\n ),\n )\n\n\ndef test_abi_bool_eval(harness: _TestHarness) -> None:\n harness.deploy(\n TEST_CASES_DIR \/ \"arc4_types\" \/ \"bool_eval.py\",\n AppCallRequest(extra_pages=1),\n )\n\n\ndef test_arc4_uintn_comparisons(harness: _TestHarness) -> None:\n harness.deploy(\n TEST_CASES_DIR \/ \"arc4_numeric_comparisons\" \/ \"uint_n.py\",\n AppCallRequest(increase_budget=1),\n )\n\n\n@pytest.mark.parametrize(\n (\"test_case\", \"expected_logic_error\"),\n [\n (b\"uint\", \"+ arg 0 wanted uint64 but got []byte\"),\n (b\"bytes\", \"b+ arg 0 wanted bigint but got uint64\"),\n (b\"mixed\", \"itob arg 0 wanted uint64 but got []byte\"),\n ],\n)\ndef test_undefined_phi_args(\n harness: _TestHarness, test_case: bytes, expected_logic_error: str\n) -> None:\n example = TEST_CASES_DIR \/ \"undefined_phi_args\"\n harness.deploy(example, AppCallRequest(args=[test_case]))\n\n with pytest.raises(LogicError) as ex_info:\n harness.deploy(example, AppCallRequest(args=[test_case, True], debug_level=2))\n ex = ex_info.value\n assert ex.message == expected_logic_error\n assert ex.line_no is not None\n assert \"\ud83d\udca5\" in \"\".join(ex.lines[ex.line_no - 5 : ex.line_no])\n\n\ndef test_augmented_assignment(harness: _TestHarness) -> None:\n result = harness.deploy(\n TEST_CASES_DIR \/ \"augmented_assignment\" \/ \"contract.py\",\n AppCallRequest(args=[0], on_complete=OnComplete.OptInOC),\n )\n\n assert result.global_state_deltas == {\n encode_utf8(\"counter\"): {\n \"action\": UINT_ACTION,\n },\n encode_utf8(\"global_uint\"): {\n \"action\": UINT_ACTION,\n },\n encode_utf8(\"global_bytes\"): {\n \"action\": BYTES_ACTION,\n },\n }\n assert result.local_state_deltas == {\n (harness.account.address, encode_utf8(\"my_uint\")): {\n \"action\": UINT_ACTION,\n },\n (harness.account.address, encode_utf8(\"my_bytes\")): {\n \"action\": BYTES_ACTION,\n },\n }\n\n args: list[int | str | bytes] = [0]\n result = harness.call(AppCallRequest(args=args))\n increment_uint = len(args)\n expected_uint = increment_uint\n expected_bytes = increment_uint.to_bytes(byteorder=\"big\", length=8)\n assert result.global_state_deltas == {\n encode_utf8(\"counter\"): {\n \"action\": UINT_ACTION,\n \"uint\": 2,\n },\n encode_utf8(\"global_uint\"): {\n \"action\": UINT_ACTION,\n \"uint\": expected_uint,\n },\n encode_utf8(\"global_bytes\"): {\n \"action\": BYTES_ACTION,\n \"bytes\": encode_bytes(expected_bytes),\n },\n }\n\n assert result.local_state_deltas == {\n (harness.account.address, encode_utf8(\"my_uint\")): {\n \"action\": UINT_ACTION,\n \"uint\": expected_uint,\n },\n (harness.account.address, encode_utf8(\"my_bytes\")): {\n \"action\": BYTES_ACTION,\n \"bytes\": encode_bytes(expected_bytes),\n },\n }\n\n args = [0, 1]\n result = harness.call(AppCallRequest(args=args))\n increment_uint = len(args)\n expected_uint += increment_uint\n expected_bytes += increment_uint.to_bytes(byteorder=\"big\", length=8)\n assert result.global_state_deltas == {\n encode_utf8(\"counter\"): {\n \"action\": UINT_ACTION,\n \"uint\": 2,\n },\n encode_utf8(\"global_uint\"): {\n \"action\": UINT_ACTION,\n \"uint\": expected_uint,\n },\n encode_utf8(\"global_bytes\"): {\n \"action\": BYTES_ACTION,\n \"bytes\": encode_bytes(expected_bytes),\n },\n }\n\n assert result.local_state_deltas == {\n (harness.account.address, encode_utf8(\"my_uint\")): {\n \"action\": UINT_ACTION,\n \"uint\": expected_uint,\n },\n (harness.account.address, encode_utf8(\"my_bytes\")): {\n \"action\": BYTES_ACTION,\n \"bytes\": encode_bytes(expected_bytes),\n },\n }\n\n\ndef test_asset(harness: _TestHarness, asset_a: int, asset_b: int) -> None:\n harness.deploy(TEST_CASES_DIR \/ \"asset\")\n\n # ensure app meets minimum balance requirements\n harness.fund(200_000)\n\n # increase fee to cover opt_in inner txn\n increased_fee = harness.client.suggested_params()\n increased_fee.flat_fee = True\n increased_fee.fee = constants.min_txn_fee * 2\n\n # call functions to assert asset behaviour\n harness.call(AppCallRequest(args=[b\"opt_in\"], assets=[asset_a], sp=increased_fee))\n harness.call(AppCallRequest(args=[b\"is_opted_in\"], assets=[asset_a]))\n with pytest.raises(LogicError, match=re.escape(\"asset self.asa == asset\")):\n harness.call(AppCallRequest(args=[b\"is_opted_in\"], assets=[asset_b]))\n\n\ndef test_verify(harness: _TestHarness) -> None:\n key = SigningKey.generate()\n data = b\"random bytes\"\n sig = key.sign(data).signature\n public_key = key.verify_key.encode()\n\n result = harness.deploy(\n TEST_CASES_DIR \/ \"edverify\",\n AppCallRequest(\n args=[data, sig, public_key],\n increase_budget=4,\n ),\n )\n (verify_outcome,) = result.decode_logs(\"i\")\n\n assert verify_outcome == 1\n\n\ndef test_application(harness: _TestHarness) -> None:\n harness.deploy(TEST_CASES_DIR \/ \"application\")\n\n harness.call(AppCallRequest(args=[b\"validate\"]))\n\n\ndef test_conditional_execution(harness: _TestHarness) -> None:\n harness.deploy(\n TEST_CASES_DIR \/ \"conditional_execution\",\n request=AppCallRequest(\n trace_output=TEST_CASES_DIR \/ \"conditional_execution\" \/ \"out\" \/ \"trace.log\",\n ),\n )\n\n\ndef iteration_idfn(value: object) -> str:\n if isinstance(value, str):\n return value\n else:\n return \"\"\n\n\n_test_iteration_params = [(\"tuple\", 0), (\"indexable\", 0), (\"urange\", 1)]\n\n\n@pytest.mark.parametrize(\n (\"name\", \"increase_budget\"), _test_iteration_params, ids=[p[0] for p in _test_iteration_params]\n)\ndef test_iteration(harness: _TestHarness, name: str, increase_budget: int) -> None:\n result = harness.deploy(\n TEST_CASES_DIR \/ \"iteration\" \/ f\"iterate_{name}.py\",\n AppCallRequest(increase_budget=increase_budget),\n )\n expected_logs = [\n \"test_forwards\",\n \"a\",\n \"b\",\n \"c\",\n \"test_reversed\",\n \"c\",\n \"b\",\n \"a\",\n \"test_forwards_with_forwards_index\",\n \"0=a\",\n \"1=b\",\n \"2=c\",\n \"test_forwards_with_reverse_index\",\n \"2=a\",\n \"1=b\",\n \"0=c\",\n \"test_reverse_with_forwards_index\",\n \"0=c\",\n \"1=b\",\n \"2=a\",\n \"test_reverse_with_reverse_index\",\n \"2=c\",\n \"1=b\",\n \"0=a\",\n \"test_empty\",\n \"test_break\",\n \"a\",\n \"test_tuple_target\",\n \"0=t\",\n ]\n assert len(result.logs) == len(expected_logs)\n logs_decoded = result.decode_logs(len(expected_logs) * \"u\")\n assert logs_decoded == expected_logs\n\n\ndef test_ignored_value(harness: _TestHarness) -> None:\n def test() -> None:\n from algopy import Contract, subroutine\n\n class Silly(Contract):\n def approval_program(self) -> bool:\n True # noqa: B018\n self.silly()\n return True\n\n @subroutine\n def silly(self) -> bool:\n True # noqa: B018\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n harness.deploy_from_closure(test)\n\n\ndef test_intrinsics_immediate_variants(harness: _TestHarness) -> None:\n sp = harness.client.suggested_params()\n sp.fee = 10\n harness.deploy(\n TEST_CASES_DIR \/ \"intrinsics\" \/ \"immediate_variants.py\",\n AppCallRequest(args=[b\"\"], sp=sp, add_random_note=True),\n )\n\n\ndef test_intrinsics_overloaded(harness: _TestHarness) -> None:\n harness.deploy(TEST_CASES_DIR \/ \"intrinsics\" \/ \"overloaded.py\")\n\n\ndef test_too_many_permutations(harness: _TestHarness) -> None:\n harness.deploy(\n TEST_CASES_DIR \/ \"too_many_permutations\",\n request=AppCallRequest(args=[1, 2, 3, 4]),\n )\n\n\n@pytest.mark.parametrize(\n (\"args\", \"expected_logs\"),\n [\n ([], []),\n ([1], [1]),\n ([1, 2], []),\n ([1, 2, 3], [3]),\n ],\n)\ndef test_control_op_simplification(\n harness: _TestHarness, args: list[int], expected_logs: list[int]\n) -> None:\n result = harness.deploy(\n TEST_CASES_DIR \/ \"control_op_simplification\", request=AppCallRequest(args=[*args])\n )\n assert result.decode_logs(\"i\" * len(expected_logs)) == expected_logs\n\n\ndef test_log(harness: _TestHarness) -> None:\n result = harness.deploy(TEST_CASES_DIR \/ \"log\")\n u64_bytes = [x.to_bytes(length=8) for x in range(8)]\n bytes_8 = b\"\\x08\"\n assert result.decode_logs(\"b\" * 8) == [\n u64_bytes[0],\n b\"1\",\n b\"2\",\n u64_bytes[3],\n b\"\",\n b\"5\" + u64_bytes[6] + u64_bytes[7] + bytes_8 + b\"\",\n b\"_\".join((b\"5\", u64_bytes[6], u64_bytes[7], bytes_8, b\"\")),\n b\"_\".join((b\"5\", u64_bytes[6], u64_bytes[7], bytes_8, b\"\")),\n ]\n\n\ndef test_inner_transactions(harness: _TestHarness) -> None:\n harness.deploy(TEST_CASES_DIR \/ \"inner_transactions\" \/ \"contract.py\")\n # ensure app meets minimum balance requirements\n harness.fund(9 * 100_000)\n\n increased_fee = harness.client.suggested_params()\n increased_fee.flat_fee = True\n increased_fee.fee = constants.min_txn_fee * (1 + 16)\n\n harness.call(AppCallRequest(sp=increased_fee, args=[b\"test1\"]))\n\n harness.call(AppCallRequest(sp=increased_fee, args=[b\"test2\"]))\n\n harness.call(AppCallRequest(sp=increased_fee, args=[b\"test2\", b\"do 2nd submit\"]))\n\n harness.call(AppCallRequest(sp=increased_fee, args=[b\"test3\"]))\n\n harness.call(AppCallRequest(sp=increased_fee, args=[b\"test4\"]))\n\n\ndef test_inner_transactions_loop(harness: _TestHarness) -> None:\n increased_fee = harness.client.suggested_params()\n increased_fee.flat_fee = True\n increased_fee.fee = constants.min_txn_fee * (1 + 4)\n\n result = harness.deploy(\n TEST_CASES_DIR \/ \"inner_transactions\" \/ \"itxn_loop.py\",\n AppCallRequest(\n sp=increased_fee,\n add_random_note=True,\n ),\n )\n\n assert result.decode_logs(\"bibibibi\") == [b\"\", 0, b\"A\", 1, b\"AB\", 2, b\"ABC\", 3]\n\n\ndef test_inheritance_direct_method_invocation(harness: _TestHarness) -> None:\n result = harness.deploy(TEST_CASES_DIR \/ \"inheritance\" \/ \"child.py\")\n assert result.decode_logs(\"uu\") == [\n \"ChildContract.method called\",\n \"GrandParentContract.method called\",\n ]\n\n\ndef test_account_from_bytes_validation(harness: _TestHarness) -> None:\n def test() -> None:\n from algopy import Account, Contract, Txn\n\n class Baddie(Contract):\n def approval_program(self) -> bool:\n b = Txn.sender.bytes + b\"!\"\n x = Account(b)\n assert x.bytes.length > 0, \"shouldn't get here\"\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n with pytest.raises(algokit_utils.logic_error.LogicError) as exc_info:\n harness.deploy_from_closure(test)\n assert exc_info.value.line_no is not None\n assert \"\/\/ Address length is 32 bytes\" in exc_info.value.lines[exc_info.value.line_no]\n\n\ndef test_arc4_address_from_bytes_validation(harness: _TestHarness) -> None:\n def test() -> None:\n from algopy import Contract, Txn, arc4\n\n class Baddie(Contract):\n def approval_program(self) -> bool:\n b = Txn.sender.bytes + b\"!\"\n x = arc4.Address(b)\n assert x.bytes.length > 0, \"shouldn't get here\"\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n with pytest.raises(algokit_utils.logic_error.LogicError) as exc_info:\n harness.deploy_from_closure(test)\n assert exc_info.value.line_no is not None\n assert \"\/\/ Address length is 32 bytes\" in exc_info.value.lines[exc_info.value.line_no]\n\n\ndef test_tuple_element_mutation(harness: _TestHarness) -> None:\n def test() -> None:\n from algopy import Contract, arc4\n\n class MyContract(Contract):\n def approval_program(self) -> bool:\n t = (arc4.UInt64(1), arc4.DynamicBytes(b\"abc\"))\n assert t[1].bytes[2:] == b\"abc\", \"initial value\"\n t[1].extend(arc4.DynamicBytes(b\"def\"))\n assert t[1].bytes[2:] == b\"abcdef\", \"updated value\"\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n harness.deploy_from_closure(test)\n\n\ndef test_arc4_tuple_element_mutation(harness: _TestHarness) -> None:\n def test() -> None:\n from algopy import Contract, arc4\n\n class MyContract(Contract):\n def approval_program(self) -> bool:\n t = arc4.Tuple((arc4.UInt64(1), arc4.DynamicBytes(b\"abc\")))\n assert t[1].bytes[2:] == b\"abc\", \"initial value\"\n t[1].extend(arc4.DynamicBytes(b\"def\"))\n assert t[1].bytes[2:] == b\"abcdef\", \"updated value\"\n return True\n\n def clear_state_program(self) -> bool:\n return True\n\n harness.deploy_from_closure(test)\n\n\ndef test_arc4_copy_in_state(harness: _TestHarness) -> None:\n def test() -> None:\n from algopy import GlobalState, arc4\n\n class MyContract(arc4.ARC4Contract):\n def __init__(self) -> None:\n self.g = GlobalState(arc4.Address())\n\n @arc4.abimethod\n def okay(self) -> None:\n pass\n\n harness.deploy_from_closure(test)\n\n\n@pytest.mark.slow\ndef test_brute_force_rotation_search(harness: _TestHarness) -> None:\n harness.deploy(TEST_CASES_DIR \/ \"stress_tests\" \/ \"brute_force_rotation_search.py\")\n\n\ndef test_match(harness: _TestHarness) -> None:\n result = harness.deploy(TEST_CASES_DIR \/ \"match\" \/ \"contract.py\", AppCallRequest(args=[b\"\"]))\n assert result.decode_logs(4 * \"u\") == [\n \"Hello There biguint\",\n \"Hello bytes\",\n \"Hello one\",\n \"Hello True\",\n ]\n\n\ndef test_loop_else(harness: _TestHarness) -> None:\n contract_path = TEST_CASES_DIR \/ \"loop_else\" \/ \"loop_else.py\"\n with pytest.raises(algokit_utils.logic_error.LogicError) as exc_info:\n harness.deploy(contract_path, AppCallRequest(args=[0, 1]))\n assert exc_info.value.message == \"err opcode executed\"\n assert exc_info.value.line_no is not None\n assert (\n \"\/\/ access denied, missing secret argument\" in exc_info.value.lines[exc_info.value.line_no]\n )\n\n with pytest.raises(algokit_utils.logic_error.LogicError) as exc_info:\n harness.deploy(contract_path, AppCallRequest(args=[2, b\"while_secret\", 3]))\n assert exc_info.value.message == \"err opcode executed\"\n assert exc_info.value.line_no is not None\n assert (\n \"\/\/ access denied, missing secret account\" in exc_info.value.lines[exc_info.value.line_no]\n )\n\n with_all_secrets_result = harness.deploy(\n contract_path,\n AppCallRequest(\n args=[4, b\"while_secret\", 5],\n accounts=[algosdk.constants.ZERO_ADDRESS, harness.account.address],\n ),\n )\n assert with_all_secrets_result.decode_logs(\"u\") == [\n \"found secret argument at idx=1 and secret account at idx=1\"\n ]\n\n\ndef test_regression_194(harness: _TestHarness) -> None:\n harness.deploy(TEST_CASES_DIR \/ \"regression_tests\" \/ \"issue_194.py\")\n","repo_name":"algorandfoundation\/puya","path":"tests\/test_execution.py","language":"Python","license":"NOASSERTION","size":49711} {"code":"","repo_name":"algorandfoundation\/puya","path":"tests\/test_expected_output\/__init__.py","language":"Python","license":"NOASSERTION","size":0} {"code":"from pathlib import Path\n\nimport pytest\n\nfrom tests.test_expected_output.data import TestFile\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_collect_file(parent: pytest.Collector, file_path: Path) -> pytest.Collector | None:\n if file_path.suffix == \".test\":\n return TestFile.from_parent(parent, path=file_path) # type: ignore[no-any-return]\n return None\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: pytest.Parser) -> None:\n parser.addoption(\n \"--test-auto-update\",\n action=\"store_true\",\n default=False,\n help=\"Update .test files with expected error outputs, requires --dist no if using xdist\",\n )\n\n parser.addoption(\n \"--test-approval-suffix\",\n action=\"store\",\n default=None,\n help=\"File suffix to use when outputting expected outputs, \"\n \"defaults to None which overwrites the input file\",\n )\n","repo_name":"algorandfoundation\/puya","path":"tests\/test_expected_output\/conftest.py","language":"Python","license":"NOASSERTION","size":1126} {"code":"import contextlib\nimport difflib\nimport tempfile\nimport typing as t\nfrom collections.abc import Iterator, Sequence\nfrom pathlib import Path\n\nimport _pytest._code.code\nimport attrs\nimport pytest\n\nfrom puya.awst.nodes import AWST\nfrom puya.awst.to_code_visitor import ToCodeVisitor\nfrom puya.compile import awst_to_teal\nfrom puya.errors import PuyaError, log_exceptions\nfrom puya.log import Log, LogLevel, logging_context\nfrom puya.utils import coalesce\nfrom puyapy.awst_build.main import transform_ast\nfrom puyapy.compile import parse_with_mypy\nfrom puyapy.options import PuyaPyOptions\nfrom puyapy.template import parse_template_key_value\nfrom tests.utils import narrowed_parse_result\n\nTHIS_DIR = Path(__file__).parent\nREPO_DIR = THIS_DIR.parent.parent\nCASE_COMMENT = \"##\"\nCASE_PREFIX = f\"{CASE_COMMENT} case:\"\nPATH_PREFIX = f\"{CASE_COMMENT} path:\"\nTEMPLATE_PREFIX = f\"{CASE_COMMENT} template:\"\nEXPECTED_PREFIX = f\"{CASE_COMMENT} expected:\"\nEXPECTED_OUTPUTS = {\"awst\"}\nLINE_CONTINUATION = \"\\\\\"\nLineNum: t.TypeAlias = int\n\nPREFIX_TO_LEVEL = {\n \"E:\": LogLevel.error,\n \"W:\": LogLevel.warning,\n \"N:\": LogLevel.info,\n}\nLEVEL_TO_PREFIX = {v: k for k, v in PREFIX_TO_LEVEL.items()}\nMIN_LEVEL_TO_REPORT = min(LEVEL_TO_PREFIX)\nOUTPUT_TYPE_PREFIX_LENGTH = len(next(iter(PREFIX_TO_LEVEL)))\nassert all(len(k) == OUTPUT_TYPE_PREFIX_LENGTH for k in PREFIX_TO_LEVEL)\n\n\n@attrs.define(frozen=True)\nclass TestCaseOutput:\n level: LogLevel\n output: str\n\n def as_comment(self) -> str:\n try:\n prefix = LEVEL_TO_PREFIX[self.level]\n except KeyError:\n # display missing keys as error, this is so critical errors are displayed nicely\n # while still causing the test case to fail.\n # Critical errors should never be \"expected\", but can be useful to trigger\n # during development\n prefix = LEVEL_TO_PREFIX[LogLevel.error] + \" !!!\"\n return f\"{prefix} {self.output}\"\n\n\nOutputMapping: t.TypeAlias = dict[LineNum, list[TestCaseOutput]]\n\n\nclass TestCaseOutputDifferenceError(Exception):\n def __init__(\n self,\n *,\n missing_output: dict[Path, OutputMapping] | None = None,\n unexpected_output: dict[Path, OutputMapping] | None = None,\n unexpected_awst: dict[Path, list[str]] | None = None,\n ):\n self.missing_output: dict[Path, OutputMapping] = coalesce(missing_output, {})\n self.unexpected_output: dict[Path, OutputMapping] = coalesce(unexpected_output, {})\n self.unexpected_awst: dict[Path, list[str]] = coalesce(unexpected_awst, {})\n\n\n@attrs.define\nclass TestCaseFile:\n path: Path | None = None\n \"\"\"Path as defined in test data\"\"\"\n body: list[str] = attrs.field(factory=list)\n \"\"\"Contents of file\"\"\"\n expected_output: OutputMapping = attrs.field(factory=dict)\n \"\"\"Expected log output\"\"\"\n expected_awst: list[str] | None = None\n \"\"\"Expected awst output (after being transformed to a text representation)\"\"\"\n\n src_path: Path | None = None\n \"\"\"Temporary location of where test file is written during compilation,\n used to correlate log items and awst output\"\"\"\n\n\n@attrs.define\nclass TestCase:\n name: str\n src_line: int\n files: list[TestCaseFile] = attrs.field(factory=list)\n template_vars: dict[str, int | bytes] = attrs.field(factory=dict)\n approved_case_source: list[str] = attrs.field(factory=list)\n \"\"\"An adjusted test case source that has all the expected output as comments.\n Defaults to original input if test case is not executed\"\"\"\n failure: TestCaseOutputDifferenceError | None = None\n\n def __hash__(self) -> int:\n return hash(self.name)\n\n def __attrs_post_init__(self) -> None:\n if not self.files:\n self.add_new_file()\n\n @property\n def current_file(self) -> TestCaseFile:\n return self.files[-1]\n\n def add_new_file(self) -> None:\n self.files.append(TestCaseFile())\n\n\ndef get_python_expected_output(line: str) -> tuple[str, list[TestCaseOutput]]:\n [python, *comments] = line.split(f\" {CASE_COMMENT} \", maxsplit=1)\n outputs = list[TestCaseOutput]()\n for comment in comments:\n prefix = comment[:OUTPUT_TYPE_PREFIX_LENGTH]\n level = PREFIX_TO_LEVEL.get(prefix)\n if level is not None:\n output = comment[len(prefix) :].rstrip(LINE_CONTINUATION).strip()\n outputs.append(TestCaseOutput(level=level, output=output))\n else:\n python += f\" {CASE_COMMENT} {comment}\"\n return python.rstrip(), outputs\n\n\ndef line_matches_prefix(line: str, prefix: str) -> str | None:\n if line.startswith(prefix):\n return line[len(prefix) :].strip()\n return None\n\n\ndef get_unique_name(name: str, names: set[str]) -> str:\n check_name = name\n occurrence = 2\n while check_name in names:\n check_name = f\"{name}_{occurrence}\"\n occurrence += 1\n names.add(check_name)\n return check_name\n\n\ndef parse_file(path: Path) -> tuple[list[str], list[TestCase]]:\n preamble = list[str]()\n cases = list[TestCase]()\n seen_case_names = set[str]()\n with path.open() as file:\n current_case: TestCase | None = None\n lines = file.read().splitlines()\n src_line = 0 # original line number in .test file ignoring continuations\n line_num = 0 # logical line number (does not increment when continuations are present)\n current_line_collector: list[str] = preamble\n while lines:\n src_line += 1\n line_num += 1\n line = lines.pop(0)\n if case_name := line_matches_prefix(line, CASE_PREFIX):\n # new case\n case_name = get_unique_name(case_name, seen_case_names)\n current_case = TestCase(name=case_name, src_line=src_line)\n cases.append(current_case)\n current_line_collector = current_case.current_file.body\n elif case_path := line_matches_prefix(line, PATH_PREFIX):\n if not current_case:\n raise ValueError(\n f\"Path encountered before a case is defined {path}:{line_num}\"\n )\n # create a new file if current_file already has content or path is already defined\n if current_case.current_file.body or current_case.current_file.path:\n current_case.add_new_file()\n assert current_case.current_file.path is None\n current_case.current_file.path = Path(case_path)\n current_line_collector = current_case.current_file.body\n elif template := line_matches_prefix(line, TEMPLATE_PREFIX):\n if not current_case:\n raise ValueError(\n f\"Template encountered before a case is defined {path}:{line_num}\"\n )\n template_var_name, template_var_value = parse_template_key_value(template)\n current_case.template_vars[template_var_name] = template_var_value\n elif maybe_collecting_output_for := line_matches_prefix(line, EXPECTED_PREFIX):\n if not current_case:\n raise ValueError(\n f\"Expected encountered before a case is defined {path}:{line_num}\"\n )\n match maybe_collecting_output_for:\n case \"awst\":\n current_line_collector = []\n current_case.current_file.expected_awst = current_line_collector\n case _:\n raise ValueError(f\"Unrecognized expected type {path}:{line_num}\")\n else:\n current_line_collector.append(line)\n if current_case:\n current_file = current_case.current_file\n python, output = get_python_expected_output(line)\n file_line_num = len(current_file.body)\n current_file.expected_output.setdefault(file_line_num, []).extend(output)\n\n while line.endswith(LINE_CONTINUATION):\n current_case.approved_case_source.append(line)\n line = lines.pop(0)\n python, output = get_python_expected_output(line)\n\n if python.strip():\n raise ValueError(\n f\"Unexpected python `{python}`, continuations only supported \"\n f\"for case comment assertions\"\n )\n current_file.expected_output.setdefault(file_line_num, []).extend(output)\n\n if current_case:\n current_case.approved_case_source.append(line)\n return preamble, cases\n\n\ndef get_test_lines_to_match_output(\n test_case: TestCase, test_case_error: TestCaseOutputDifferenceError\n) -> list[str]:\n expected = list[str]()\n expected.append(f\"{CASE_PREFIX} {test_case.name}\")\n for template in test_case.template_vars:\n expected.append(f\"{TEMPLATE_PREFIX} {template}\")\n for test_file in test_case.files:\n if test_file.path:\n expected.append(f\"{PATH_PREFIX} {test_file.path}\")\n for line_num, line in enumerate(test_file.body, start=1):\n python, _ = get_python_expected_output(line)\n correct_errors = test_file.expected_output.get(line_num, [])[:]\n\n if test_file.src_path:\n for missing in test_case_error.missing_output.get(test_file.src_path, {}).get(\n line_num, []\n ):\n correct_errors.remove(missing)\n for unexpected in test_case_error.unexpected_output.get(\n test_file.src_path, {}\n ).get(line_num, []):\n correct_errors.append(unexpected)\n\n if correct_errors:\n line_width = len(python) * \" \"\n line_join = f\" {LINE_CONTINUATION}\\n{line_width}\"\n\n commented_lines = line_join.join(\n [f\" {CASE_COMMENT} {error.as_comment()}\" for error in correct_errors]\n ).splitlines()\n commented_lines[0] = f\"{python}{commented_lines[0]}\"\n expected.extend(commented_lines)\n else:\n expected.append(python)\n if test_file.expected_awst is not None:\n expected.append(f\"{EXPECTED_PREFIX} awst\")\n awst = test_file.expected_awst\n if test_case.failure and test_file.src_path:\n received_awst = test_case.failure.unexpected_awst.get(test_file.src_path)\n if received_awst is not None:\n awst = received_awst\n expected.extend(awst)\n return expected\n\n\ndef compile_and_update_cases(cases: list[TestCase]) -> None:\n with tempfile.TemporaryDirectory() as root_dir_str, logging_context() as awst_log_ctx:\n root_dir = Path(root_dir_str).resolve()\n srcs = list[Path]()\n case_path = dict[TestCase, Path]()\n # prepare temp directory for each case\n for case in cases:\n case_dir = root_dir\n file, *other_files = case.files\n if other_files:\n case_path[case] = case_dir = case_dir \/ get_python_file_name(case.name)\n else:\n case_path[case] = case_dir \/ (file.path or f\"{get_python_file_name(case.name)}.py\")\n case_dir.mkdir(parents=True, exist_ok=True)\n for file in case.files:\n file_name = file.path or f\"{get_python_file_name(case.name)}.py\"\n tmp_src = (case_dir \/ file_name).resolve()\n tmp_src.parent.mkdir(parents=True, exist_ok=True)\n tmp_src.write_text(\"\\n\".join(file.body))\n srcs.append(tmp_src)\n file.src_path = tmp_src\n puyapy_options = PuyaPyOptions(\n paths=srcs,\n output_bytecode=True,\n )\n parse_result = parse_with_mypy(puyapy_options.paths)\n # lower each case further if possible and process\n for case in cases:\n # lower awst for each case individually to order to get any output\n # from lower layers\n # this needs a new logging context so AWST errors from other cases\n # are not seen\n case_options = attrs.evolve(\n puyapy_options, cli_template_definitions=case.template_vars\n )\n case_parse_result = narrowed_parse_result(parse_result, case_path[case])\n with (\n contextlib.suppress(SystemExit),\n logging_context() as case_log_ctx,\n log_exceptions(),\n ):\n case_awst, case_compilation_set = transform_ast(case_parse_result)\n case_log_ctx.logs.extend(filter_logs(awst_log_ctx.logs, case))\n awst_to_teal(\n case_log_ctx,\n case_options,\n {k: Path() for k in case_compilation_set},\n case_parse_result.sources_by_path,\n case_awst,\n write=False,\n )\n process_test_case(case, case_log_ctx.logs, case_awst)\n\n\ndef filter_logs(captured_logs: list[Log], case: TestCase) -> Iterator[Log]:\n for file in case.files:\n path = file.src_path\n assert path is not None\n abs_path = path.resolve()\n yield from (record for record in captured_logs if record.file == abs_path)\n\n\ndef get_python_file_name(name: str) -> str:\n def is_valid(char: str) -> bool:\n return char.isalnum() or char == \"_\"\n\n python_name = \"\".join(filter(is_valid, name.replace(\" \", \"_\")))\n return python_name\n\n\ndef map_error_tuple_to_dict(errors: set[tuple[int, TestCaseOutput]]) -> OutputMapping:\n result: OutputMapping = OutputMapping()\n for line, error in errors:\n result.setdefault(line, []).append(error)\n return result\n\n\ndef process_test_case(case: TestCase, captured_logs: Sequence[Log], awst: AWST) -> None:\n if case.failure:\n return\n missing_output = dict[Path, OutputMapping]()\n unexpected_output = dict[Path, OutputMapping]()\n unexpected_awst = dict[Path, list[str]]()\n for file in case.files:\n path = file.src_path\n assert path is not None\n expected_output = {\n (line, message)\n for line, messages in file.expected_output.items()\n for message in messages\n }\n seen_output = {\n (\n record.line,\n TestCaseOutput(\n level=record.level,\n output=record.message.strip(),\n ),\n )\n for record in captured_logs\n if record.line is not None and record.level >= MIN_LEVEL_TO_REPORT\n }\n file_missing_output = expected_output - seen_output\n file_unexpected_output = seen_output - expected_output\n if file_missing_output:\n missing_output[path] = map_error_tuple_to_dict(file_missing_output)\n if file_unexpected_output:\n unexpected_output[path] = map_error_tuple_to_dict(file_unexpected_output)\n\n if file.expected_awst:\n assert file.src_path is not None\n observed_awst = trim_empty_lines(module_to_awst_repr(awst, file.src_path))\n expected_awst = trim_empty_lines(file.expected_awst)\n if observed_awst != expected_awst:\n unexpected_awst[path] = observed_awst\n\n if missing_output or unexpected_output or unexpected_awst:\n case.failure = TestCaseOutputDifferenceError(\n missing_output=missing_output,\n unexpected_output=unexpected_output,\n unexpected_awst=unexpected_awst,\n )\n\n\ndef report_test_case_error(\n test_case_src_path: Path, test_case: TestCase, test_case_error: TestCaseOutputDifferenceError\n) -> str:\n errors = list[str]()\n max_width = max(len(b) for case_file in test_case.files for b in case_file.body)\n for test_file in test_case.files:\n if test_file.path:\n errors.append(f\"## path: {test_file.path}\")\n\n if test_file.src_path:\n file_missing_output = test_case_error.missing_output.get(test_file.src_path, {})\n file_unexpected_output = test_case_error.unexpected_output.get(test_file.src_path, {})\n if file_missing_output or file_unexpected_output:\n for line_num, line in enumerate(test_file.body, start=1):\n annotated_line: str = line\n\n if test_file.src_path:\n missing_output = file_missing_output.get(line_num, [])\n unexpected_output = file_unexpected_output.get(line_num, [])\n\n if missing_output or unexpected_output:\n annotated_line = annotated_line.ljust(max_width)\n if missing_output and unexpected_output:\n annotated_line += \" <----wrong----- \" + \" \/ \".join(\n e.as_comment() for e in unexpected_output\n )\n elif missing_output:\n annotated_line += \" <---missing---- \"\n elif unexpected_output:\n annotated_line += \" <--unexpected-- \" + \" \/ \".join(\n e.as_comment() for e in unexpected_output\n )\n annotated_line += (\n f\" (file:\/\/{test_case_src_path}:{test_case.src_line + line_num})\"\n )\n errors.append(annotated_line)\n if unexpected_awst := test_case_error.unexpected_awst.get(test_file.src_path):\n assert test_file.expected_awst is not None\n errors.extend(\n [\n f\"test_source: file:\/\/{test_case_src_path}:{test_case.src_line}\",\n \"AWST Difference:\",\n *difflib.ndiff(test_file.expected_awst, unexpected_awst),\n ]\n )\n return \"\\n\".join(errors)\n\n\nclass TestItem(pytest.Item):\n def __init__(self, *, test_case: TestCase, **kwargs: t.Any):\n super().__init__(**kwargs)\n self.test_case = test_case\n\n def runtest(self) -> None:\n # test case has already been processed, but indicate failure if it failed\n if self.test_case.failure:\n raise self.test_case.failure\n\n def repr_failure(\n self,\n excinfo: pytest.ExceptionInfo[BaseException],\n _style: str | None = None,\n ) -> str | _pytest._code.code.TerminalRepr:\n match excinfo.value:\n case TestCaseOutputDifferenceError() as test_case_error:\n assert self.parent is not None\n return report_test_case_error(self.parent.path, self.test_case, test_case_error)\n case _:\n return super().repr_failure(excinfo)\n\n def reportinfo(self) -> tuple[Path, int | None, str]:\n assert self.parent\n return self.parent.path, self.test_case.src_line, self.name\n\n\nclass TestFile(pytest.File):\n def __init__(self, *args: t.Any, **kwargs: t.Any):\n super().__init__(*args, **kwargs)\n self.cases = list[TestCase]()\n self.preamble = list[str]()\n self.compile_error: PuyaError | None = None\n self.auto_update_output = bool(self.config.getoption(\"test_auto_update\"))\n dist_option = self.config.getoption(\"dist\")\n if self.auto_update_output and dist_option and dist_option != \"no\":\n # don't allow updating output if tests are being executed in parallel\n self.auto_update_output = False\n # TODO: work out how to inform the user of this\n print( # noqa: T201\n \"`--test-auto-update` ignored due to --dist option. Use `--dist no` to enable\"\n )\n\n def collect(self) -> t.Iterable[pytest.Item | pytest.Collector]:\n self.preamble, self.cases = parse_file(self.path)\n test_items = [\n TestItem.from_parent(self, name=case.name, test_case=case) for case in self.cases\n ]\n return test_items\n\n def get_expected_output(self) -> list[str]:\n lines = self.preamble[:]\n for case in self.cases:\n expected_output = (\n get_test_lines_to_match_output(case, case.failure)\n if case.failure is not None\n else case.approved_case_source\n )\n lines.extend(expected_output)\n lines.append(\"\")\n return lines\n\n def setup(self) -> None:\n # TODO: find a better way to improve performance\n # running multiple cases at once is a lot faster due to less mypy overhead\n # however a ParseError in a single case will effect all cases which is not ideal\n try:\n compile_and_update_cases(self.cases)\n except (PuyaError, SystemExit) as ex:\n pytest.fail(f\"Unhandled compiler error: {ex}\", pytrace=False)\n except BaseException as ex:\n # unexpected error, fail immediately\n pytest.fail(f\"Unexpected error: {ex!r}\", pytrace=False)\n\n def teardown(self) -> None:\n if self.auto_update_output:\n approval = self.path\n approval_suffix: str | None = self.config.getoption(\"test_approval_suffix\")\n if approval_suffix is not None:\n if not approval_suffix.startswith(\".\"):\n approval_suffix = f\".{approval_suffix}\"\n approval = approval.with_suffix(approval_suffix)\n approval.write_text(\"\\n\".join(self.get_expected_output()), encoding=\"utf8\")\n\n\ndef trim_empty_lines(lines: list[str]) -> list[str]:\n start = len(lines)\n end = 0\n for idx, line in enumerate(lines):\n if line:\n start = min(idx, start)\n end = max(idx, end)\n return lines[start : end + 1]\n\n\ndef module_to_awst_repr(awst: AWST, src_path: Path) -> list[str]:\n visitor = ToCodeVisitor()\n filtered_awst = [n for n in awst if n.source_location.file == src_path]\n return visitor.visit_module(filtered_awst).splitlines()\n","repo_name":"algorandfoundation\/puya","path":"tests\/test_expected_output\/data.py","language":"Python","license":"NOASSERTION","size":22322} {"code":"from decimal import Decimal\nfrom pathlib import Path\n\nimport pytest\n\nfrom puya.awst import (\n nodes as awst,\n wtypes,\n)\nfrom puya.awst.nodes import BytesEncoding\nfrom puya.ir import models as ir\nfrom puya.ir.builder.main import FunctionIRBuilder\nfrom puya.ir.context import IRBuildContext\nfrom puya.log import LogLevel, logging_context\nfrom puya.options import PuyaOptions\nfrom puya.parse import SourceLocation\n\n_location = SourceLocation(\n file=Path(\"\/test_ir.ts\"),\n line=1,\n)\n\n\n@pytest.mark.parametrize(\"value\", [-1, 2**64])\ndef test_uint64_validation(value: int) -> None:\n expr = awst.UInt64Constant(value=value, source_location=_location)\n assert _build_ir_and_return_errors(expr) == [\"invalid uint64 value\"]\n\n\n@pytest.mark.parametrize(\"value\", [-1, 2**512])\ndef test_biguint_validation(value: int) -> None:\n expr = awst.BigUIntConstant(value=value, source_location=_location)\n assert _build_ir_and_return_errors(expr) == [\"invalid biguint value\"]\n\n\n@pytest.mark.parametrize(\"value\", [-1, 2**8])\ndef test_arc4_uintn_validation(value: int) -> None:\n expr = awst.IntegerConstant(\n value=value, wtype=wtypes.arc4_byte_alias, source_location=_location\n )\n assert _build_ir_and_return_errors(expr) == [\"invalid arc4.uint8 value\"]\n\n\n@pytest.mark.parametrize(\n \"value\",\n [\n Decimal(\"-1.00\"),\n Decimal(\"2.56\"),\n Decimal(\"0.111\"),\n Decimal(\"inf\"),\n ],\n)\ndef test_decimal_validation(value: Decimal) -> None:\n expr = awst.DecimalConstant(\n value=value,\n wtype=wtypes.ARC4UFixedNxM(n=8, m=2, source_location=None),\n source_location=_location,\n )\n assert _build_ir_and_return_errors(expr) == [\"invalid arc4.ufixed8x2 value\"]\n\n\ndef test_bytes_validation() -> None:\n expr = awst.BytesConstant(\n value=b\"0\" * 4097, encoding=BytesEncoding.base16, source_location=_location\n )\n assert _build_ir_and_return_errors(expr) == [\"invalid bytes value\"]\n\n\ndef test_string_validation() -> None:\n expr = awst.StringConstant(value=\"0\" * 4097, source_location=_location)\n assert _build_ir_and_return_errors(expr) == [\"invalid string value\"]\n\n\ndef test_address_validation() -> None:\n expr = awst.AddressConstant(value=\"bad_address\", source_location=_location)\n assert _build_ir_and_return_errors(expr) == [\"invalid Algorand address\"]\n\n\ndef _build_ir_and_return_errors(expr: awst.Expression) -> list[str]:\n module_name = \"test_ir\"\n func_name = \"test_ir\"\n function = awst.Subroutine(\n id=f\"{module_name}.{func_name}\",\n name=func_name,\n body=awst.Block(body=[awst.ExpressionStatement(expr)], source_location=_location),\n source_location=_location,\n args=(),\n return_type=wtypes.void_wtype,\n documentation=awst.MethodDocumentation(),\n )\n ctx = IRBuildContext(\n options=PuyaOptions(),\n compilation_set={},\n sources_by_path={},\n awst=[],\n subroutines={},\n embedded_funcs_lookup={},\n )\n subroutine = ir.Subroutine(\n source_location=_location,\n id=function.id,\n short_name=function.short_name,\n parameters=(),\n returns=(),\n body=[],\n inline=function.inline,\n )\n with logging_context() as log_ctx:\n FunctionIRBuilder.build_body(ctx, function, subroutine)\n return [log.message for log in log_ctx.logs if log.level == LogLevel.error]\n","repo_name":"algorandfoundation\/puya","path":"tests\/test_ir_validation.py","language":"Python","license":"NOASSERTION","size":3408} {"code":"from collections.abc import Mapping\nfrom pathlib import Path\n\nimport algokit_utils\nimport algosdk\nimport pytest\nfrom algokit_utils import TransferAssetParameters\nfrom algosdk.atomic_transaction_composer import (\n AtomicTransactionComposer,\n LogicSigTransactionSigner,\n TransactionWithSigner,\n)\nfrom algosdk.transaction import AssetTransferTxn, LogicSigAccount, LogicSigTransaction, PaymentTxn\nfrom algosdk.v2client.algod import AlgodClient\n\nfrom puya.compilation_artifacts import CompiledLogicSig\nfrom puyapy.options import PuyaPyOptions\nfrom tests import TEST_CASES_DIR\nfrom tests.utils import compile_src_from_options\n\npytestmark = pytest.mark.localnet\n\n\ndef compile_logic_sig(\n src_path: Path,\n *,\n optimization_level: int = 1,\n debug_level: int = 2,\n template_variables: Mapping[str, int | bytes] | None = None,\n) -> bytes:\n result = compile_src_from_options(\n PuyaPyOptions(\n paths=(src_path,),\n optimization_level=optimization_level,\n debug_level=debug_level,\n output_bytecode=True,\n cli_template_definitions=template_variables or {},\n )\n )\n (logic_sig,) = result.teal\n assert isinstance(\n logic_sig, CompiledLogicSig\n ), \"Compilation artifact must be a logic signature\"\n bytecode = logic_sig.program.bytecode\n assert bytecode is not None\n return bytecode\n\n\ndef test_logic_sig(algod_client: AlgodClient, account: algokit_utils.Account) -> None:\n logic_sig_prog = compile_logic_sig(\n TEST_CASES_DIR \/ \"logic_signature\" \/ \"always_allow.py\",\n )\n logic_sig = LogicSigAccount(\n program=logic_sig_prog,\n )\n algokit_utils.transfer(\n client=algod_client,\n parameters=algokit_utils.TransferParameters(\n from_account=account,\n to_address=logic_sig.address(),\n micro_algos=2_000_000,\n ),\n )\n\n paytxn = PaymentTxn(\n sender=logic_sig.address(),\n sp=algod_client.suggested_params(),\n receiver=account.address,\n amt=1_000_000,\n )\n signed_paytxn = LogicSigTransaction(\n transaction=paytxn,\n lsig=logic_sig.lsig,\n )\n algod_client.send_transaction(txn=signed_paytxn)\n\n delegated_logic_sig = LogicSigAccount(program=logic_sig_prog)\n delegated_logic_sig.sign(account.private_key)\n\n paytxn = PaymentTxn(\n sender=account.address,\n sp=algod_client.suggested_params(),\n receiver=logic_sig.address(),\n amt=500_000,\n )\n signed_paytxn = algosdk.transaction.LogicSigTransaction(\n transaction=paytxn,\n lsig=delegated_logic_sig.lsig,\n )\n algod_client.send_transaction(txn=signed_paytxn)\n\n\n@pytest.fixture\ndef account_2(algod_client: AlgodClient) -> algokit_utils.Account:\n v = algosdk.account.generate_account()\n account = algokit_utils.Account(private_key=v[0], address=v[1])\n algokit_utils.transfer(\n client=algod_client,\n parameters=algokit_utils.TransferParameters(\n from_account=algokit_utils.get_localnet_default_account(algod_client),\n to_address=account.address,\n micro_algos=500_000_000,\n ),\n )\n return account\n\n\ndef test_pre_approved_sale(\n algod_client: AlgodClient,\n account: algokit_utils.Account,\n account_2: algokit_utils.Account,\n asset_a: int,\n) -> None:\n algokit_utils.transfer_asset(\n client=algod_client,\n parameters=TransferAssetParameters(\n from_account=account_2,\n to_address=account_2.address,\n asset_id=asset_a,\n amount=0, # Opt in\n ),\n )\n logic_sig_prog = compile_logic_sig(\n TEST_CASES_DIR \/ \"logic_signature\" \/ \"signature.py\",\n template_variables={\n \"SELLER\": algosdk.encoding.decode_address(account.address),\n \"PRICE\": 10_000_000,\n \"ASSET_ID\": asset_a,\n },\n )\n logic_sig = LogicSigAccount(program=logic_sig_prog)\n logic_sig.sign(account.private_key)\n\n # Payment for the asset\n paytxn = PaymentTxn(\n sender=account_2.address,\n sp=algod_client.suggested_params(),\n receiver=account.address,\n amt=10_000_000,\n )\n\n # Transfer the asset\n axfertxn = AssetTransferTxn(\n sender=account.address,\n sp=algod_client.suggested_params(),\n receiver=account_2.address,\n amt=1,\n index=asset_a,\n )\n\n atc = AtomicTransactionComposer()\n\n atc.add_transaction(TransactionWithSigner(txn=paytxn, signer=account_2.signer))\n atc.add_transaction(\n TransactionWithSigner(txn=axfertxn, signer=LogicSigTransactionSigner(logic_sig))\n )\n\n atc.execute(algod_client, wait_rounds=5)\n","repo_name":"algorandfoundation\/puya","path":"tests\/test_logic_sig.py","language":"Python","license":"NOASSERTION","size":4705} {"code":"# type: ignore\n# ruff: noqa\nimport inspect\nimport typing\nfrom textwrap import dedent\n\nimport mypy.build\nimport mypy.find_sources\nimport mypy.fscache\nimport mypy.nodes\nimport mypy.options\nimport mypy.types\nimport pytest\nfrom mypy.nodes import RevealExpr\n\nfrom puyapy.compile import get_mypy_options\n\n\ndef get_assignment_var_named(mypy_file: mypy.nodes.MypyFile, name: str) -> mypy.nodes.Var:\n for assignment in [\n stmt for stmt in mypy_file.defs if isinstance(stmt, mypy.nodes.AssignmentStmt)\n ]:\n for lvalue in assignment.lvalues:\n if isinstance(lvalue, mypy.nodes.NameExpr) and lvalue.name == name:\n assert isinstance(lvalue.node, mypy.nodes.Var)\n return lvalue.node\n raise Exception(f\"Assignment to '{name}' not found\")\n\n\ndef get_class_by_name(mypy_file: mypy.nodes.MypyFile, name: str) -> mypy.nodes.ClassDef:\n for cls_def in (stmt for stmt in mypy_file.defs if isinstance(stmt, mypy.nodes.ClassDef)):\n if cls_def.name == name:\n return cls_def\n raise Exception(f\"Assignment to '{name}' not found\")\n\n\ndef decompile(function: typing.Callable) -> str:\n source = inspect.getsource(function)\n return dedent(\"\\n\".join(source.splitlines()[1:]))\n\n\nTEST_MODULE = \"__test__\"\n\n\ndef mypy_parse_and_type_check(source: str | typing.Callable) -> mypy.build.BuildResult:\n code = source if isinstance(source, str) else decompile(source)\n options = get_mypy_options()\n options.export_types = True\n\n sources = [mypy.build.BuildSource(None, TEST_MODULE, text=dedent(code))]\n\n return mypy.build.build(sources=sources, options=options)\n\n\ndef strip_error_prefixes(br: mypy.build.BuildResult) -> list[str]:\n return [e.split(\":\", maxsplit=2)[-1].strip() for e in br.errors]\n\n\ndef get_revealed_types(\n br: mypy.build.BuildResult, tree: mypy.nodes.MypyFile\n) -> list[mypy.types.Type | None]:\n import mypy.traverser\n\n types = []\n\n class MyVisitor(mypy.traverser.TraverserVisitor):\n def visit_reveal_expr(self, o: RevealExpr) -> None:\n types.append(br.types.get(o.expr, mypy.types.UninhabitedType()))\n\n visitor = MyVisitor()\n visitor.visit_mypy_file(tree)\n return types\n\n\ndef test_ignore_assignment() -> None:\n def test():\n a_lie: int = \"bar\" # type: ignore[assignment]\n\n result = mypy_parse_and_type_check(test)\n assert not result.errors\n module = result.graph[TEST_MODULE]\n assert module.tree\n assert module.tree.ignored_lines == {1: [\"assignment\"]}\n\n\ndef test_incorrect_assignment() -> None:\n def test():\n wrong: int = \"bar\"\n\n result = mypy_parse_and_type_check(test)\n assert result.errors\n assert result.errors[0].endswith(\"[assignment]\")\n\n\ndef test_cast() -> None:\n def test():\n import typing\n\n wrong: int = typing.cast(int, \"bar\")\n\n result = mypy_parse_and_type_check(test)\n tree = result.graph[TEST_MODULE].tree\n assert tree\n var = get_assignment_var_named(tree, \"wrong\")\n assert str(var.type) == \"builtins.int\"\n\n\ndef test_implicit_cast() -> None:\n def test():\n import typing\n\n wrong_implicit = typing.cast(int, \"bar\")\n\n result = mypy_parse_and_type_check(test)\n tree = result.graph[TEST_MODULE].tree\n assert tree\n var = get_assignment_var_named(tree, \"wrong_implicit\")\n assert str(var.type) == \"builtins.int\"\n\n\n@pytest.mark.xfail(reason=\"The observed behaviour here changed after updating mypy to 1.5.0\")\ndef test_assert_isinstance_does_not_cast() -> None:\n def test():\n an_int: int = 123\n assert isinstance(an_int, str)\n\n another_int = an_int # despite earlier assert, an_int is still seen as a int\n\n result = mypy_parse_and_type_check(test)\n tree = result.graph[TEST_MODULE].tree\n assert tree\n var = get_assignment_var_named(tree, \"another_int\")\n assert str(var.type) == \"builtins.int\"\n\n\ndef test_assert_isinstance_does_narrow() -> None:\n def test():\n import typing\n\n an_int: typing.Any = 123\n assert isinstance(an_int, str)\n\n another_int = an_int # earlier assert narrows from Any to str\n\n result = mypy_parse_and_type_check(test)\n tree = result.graph[TEST_MODULE].tree\n assert tree\n var = get_assignment_var_named(tree, \"another_int\")\n assert str(var.type) == \"builtins.str\"\n\n\ndef test_name_defined():\n def test():\n error = missing + 2 # type: ignore[name-defined]\n\n result = mypy_parse_and_type_check(test)\n tree = result.graph[TEST_MODULE].tree\n match tree:\n case mypy.nodes.MypyFile(\n defs=[\n mypy.nodes.AssignmentStmt(\n rvalue=mypy.nodes.OpExpr(left=mypy.nodes.NameExpr(name=\"missing\") as missing),\n )\n ]\n ):\n assert missing.node is None\n case _:\n raise AssertionError\n\n\n# TODO: override, what does the type information look like when call these?\n\n\ndef test_ignore_override() -> None:\n def test():\n class ABase:\n def method(self, x: int) -> int:\n return x\n\n class ADerived(ABase):\n def method(self, x: int) -> str: # type: ignore[override]\n return str(x)\n\n class BBase:\n def call(self, o: ABase) -> int:\n result = o.method(42)\n return result\n\n class BDerived(BBase):\n def call(self, o: ADerived) -> str: # type: ignore[override]\n result = o.method(42)\n return result\n\n base_base_result = BBase().call(ABase())\n base_derived_result = BBase().call(ADerived())\n derived_base_result = BDerived().call(ABase())\n derived_derived_result = BDerived().call(ADerived())\n\n result = mypy_parse_and_type_check(test)\n tree = result.graph[TEST_MODULE].tree\n assert tree\n\n test()\n\n\ndef test_super_no_args_outside_method() -> None:\n def test():\n def function() -> None:\n super().__init__()\n\n class Obj:\n pass\n\n print(super(Obj, Obj()).__str__())\n\n result = mypy_parse_and_type_check(test)\n assert result.errors == [':2: error: \"super\" used outside class [misc]']\n\n\ndef test_aliased_import() -> None:\n def test():\n from collections import abc as xyz\n\n hmm = xyz\n\n result = mypy_parse_and_type_check(test)\n tree = result.graph[TEST_MODULE].tree\n assert tree.defs[-1].rvalue.fullname == \"collections.abc\"\n assert tree.names[\"xyz\"].fullname == \"collections.abc\"\n\n\ndef test_function_redefinition() -> None:\n def test():\n def foo(x: int) -> int:\n return 2 * x\n\n def foo(x: str) -> str:\n return 2 * x\n\n bar = foo(\"1\")\n\n result = mypy_parse_and_type_check(test)\n tree = result.graph[TEST_MODULE].tree\n assert result.errors == [\n ':4: error: Name \"foo\" already defined on line 1 [no-redef]',\n ':7: error: Argument 1 to \"foo\" has incompatible type \"str\"; expected \"int\" [arg-type]',\n ]\n assert tree.defs[-1].rvalue.callee.node is tree.defs[0]\n\n\ndef test_class_members() -> None:\n def test():\n from typing import ClassVar, Final\n\n class Class:\n class_var: ClassVar = 1\n class_var_implicit = 2\n class_var_implicit_final: Final = 3\n\n decl_only: int\n decl_and_set_in_init: int\n decl_and_set_in_method: int\n decl_only_final: Final[int]\n\n def __init__(self) -> None:\n self.decl_and_set_in_init = 100\n self.new_var_in_init = 101\n self.new_final_var_in_init: Final = 102\n self.decl_only_final = 103\n\n def method(self) -> None:\n self.decl_and_set_in_method = 200\n self.new_var_in_method = 201\n self.new_final_far_in_method: Final = 202\n\n obj = Class()\n assert not hasattr(Class, \"decl_only\")\n assert not hasattr(Class, \"decl_and_set_in_init\")\n assert not hasattr(obj, \"decl_only\")\n assert hasattr(obj, \"decl_and_set_in_init\")\n\n test()\n result = mypy_parse_and_type_check(test)\n assert len(result.errors) == 1\n assert result.errors[0].endswith(\n \"error: Can only declare a final attribute in class body or __init__ [misc]\"\n )\n tree = result.graph[TEST_MODULE].tree\n assert tree\n cls_def = tree.defs[1]\n assert isinstance(cls_def, mypy.nodes.ClassDef)\n symtable = cls_def.info.names.copy()\n del symtable[\"__init__\"]\n del symtable[\"method\"]\n assert symtable.keys() == {\n \"class_var\",\n \"class_var_implicit\",\n \"class_var_implicit_final\",\n \"decl_and_set_in_init\",\n \"decl_and_set_in_method\",\n \"decl_only\",\n \"decl_only_final\",\n \"new_final_far_in_method\",\n \"new_final_var_in_init\",\n \"new_var_in_init\",\n \"new_var_in_method\",\n }\n vars_ = {}\n for name, sym in symtable.items():\n assert sym.kind == mypy.nodes.MDEF # THE M STANDS FOR MEMBER.. REMEMBER... REMEMMMMBEERRR\n if name.startswith(\"new_\"):\n assert sym.implicit\n else:\n assert not sym.implicit\n assert isinstance(sym.node, mypy.nodes.Var)\n # unfortunate that implicit class vars and not detected as such :(\n assert sym.node.is_classvar == (name == \"class_var\")\n # can't use is_initialized_in_class either, it is True even when it's just declared\n assert sym.node.is_initialized_in_class == (\n name.startswith(\"class_var\") or name.startswith(\"decl_\")\n )\n vars_[name] = sym.node\n # note this does nothing v\n typing.assert_type(vars_, dict[str, mypy.nodes.Var])\n\n\ndef test_abc() -> None:\n # TODO: FINISH THIS\n def test():\n from abc import ABC, abstractmethod\n import typing\n\n class Base(ABC):\n def concrete(self) -> int:\n return id(self)\n\n @abstractmethod\n def explicit_abstract_ellipsis(self) -> int: ...\n\n @abstractmethod\n def explicit_abstract_raise_not_implemented(self) -> int:\n raise NotImplementedError\n\n @abstractmethod\n def explicit_abstract_pass(self) -> int:\n pass\n\n @abstractmethod\n def explicit_abstract_docstring_only(self) -> int:\n \"\"\"This is a docstring\"\"\"\n\n @abstractmethod\n def explicit_abstract_with_impl(self, x: int) -> int:\n return x + 1\n\n def implicit_abstract_returning_int(self) -> int:\n raise NotImplementedError\n\n class DerivedPass(Base):\n pass\n\n class DerivedABCPass(Base, ABC):\n pass\n\n class DerivedPartial(Base):\n def explicit_abstract_ellipsis(self) -> int:\n return 42\n\n if not typing.TYPE_CHECKING:\n import pytest\n\n with pytest.raises(TypeError, match=\"Can't instantiate abstract class\"):\n base = Base()\n with pytest.raises(TypeError, match=\"Can't instantiate abstract class\"):\n derived_pass = DerivedPass()\n with pytest.raises(TypeError, match=\"Can't instantiate abstract class\"):\n derived_abc_pass = DerivedABCPass()\n with pytest.raises(TypeError, match=\"Can't instantiate abstract class\"):\n derived_partial = DerivedPartial()\n\n test()\n result = mypy_parse_and_type_check(test)\n # assert not result.errors\n tree = result.graph[TEST_MODULE].tree\n assert tree\n\n\n# TODO: various member\/class var decls, protocol handling, special decorators,\n# metaclass, generics, etc\n#\n\n\n# TODO: Protocol tests\n\n\ndef test_nested_class() -> None:\n def test() -> None:\n class Outer:\n outer_mem: int = 1\n\n class Inner:\n inner_mem: int = 2\n\n inner_inst = Inner()\n\n outer_inst = Outer()\n assert outer_inst\n\n test()\n result = mypy_parse_and_type_check(test)\n tree = result.graph[TEST_MODULE].tree\n assert tree\n\n\ndef test_final_method() -> None:\n def test() -> None:\n import typing\n\n class Class:\n @typing.final\n def meaning_of_life(self) -> int:\n return 42\n\n result = mypy_parse_and_type_check(test)\n tree = result.graph[TEST_MODULE].tree\n assert tree\n class_def = tree.defs[-1]\n assert isinstance(class_def, mypy.nodes.ClassDef)\n deco = class_def.defs.body[0]\n assert isinstance(deco, mypy.nodes.Decorator)\n assert deco.decorators == []\n assert deco.is_final\n assert deco.func.is_final\n\n\ndef test_notypecheck_func() -> None:\n def test() -> None:\n import typing\n\n @typing.no_type_check\n def my_func(x: dict):\n return x + \"lol\"\n\n result = mypy_parse_and_type_check(test)\n tree = result.graph[TEST_MODULE].tree\n assert tree\n deco = tree.defs[-1]\n assert isinstance(deco, mypy.nodes.Decorator)\n assert deco.decorators, \"please don't strip the no_type_check decorator mypy...\"\n\n\ndef test_chained_assignment_lvalue_order() -> None:\n def test():\n outer = inner = 0\n\n result = mypy_parse_and_type_check(test)\n assert not result.errors\n tree = result.graph[TEST_MODULE].tree\n assert tree\n assert len(tree.defs) == 1\n assignment_stmt = tree.defs[0]\n assert isinstance(assignment_stmt, mypy.nodes.AssignmentStmt)\n lvalues = assignment_stmt.lvalues\n assert len(lvalues) == 2\n first, second = lvalues\n assert isinstance(first, mypy.nodes.NameExpr) and first.name == \"outer\"\n assert isinstance(second, mypy.nodes.NameExpr) and second.name == \"inner\"\n\n\ndef test_list_expr_assignment_target() -> None:\n \"\"\"MyPy translates assignment targets with list to tuple\"\"\"\n\n def test():\n [a, b] = 1, 2\n [head, *tail] = [1, 2, 3]\n\n result = mypy_parse_and_type_check(test)\n assert not result.errors\n tree = result.graph[TEST_MODULE].tree\n assert tree and len(tree.defs) == 2\n for stmt in tree.defs:\n assert isinstance(stmt, mypy.nodes.AssignmentStmt)\n lvalues = stmt.lvalues\n assert len(lvalues) == 1\n assert isinstance(lvalues[0], mypy.nodes.TupleExpr)\n\n\ndef test_assignment_statements() -> None:\n def test():\n class Base:\n var: str\n\n class Obj(Base):\n def __init__(self) -> None:\n self._tmp = \"tmp\"\n Obj._tmp = \"WHY\"\n self._tmp2: int\n self._tmp2 = 123\n self._tmp3: int = len(self._tmp)\n\n def method(self) -> None:\n self.x: int\n self.x = 2\n self.y = 3\n self.z: int\n\n lst = [1, 2]\n tup0, tup1 = lst\n star0, *star_rest = lst\n foo, (bar, *baz) = (tup0, (tup1, star0, *star_rest))\n x: int\n x = 0\n lst[2:] = [3, 4]\n o = Obj()\n o.var = \"a\"\n Obj().var = \"b\"\n super(Obj, o).var = \"c\" # type: ignore[misc]\n d = dict[str, int]()\n d[\"key\"] = x\n o.method()\n ox = o.x\n\n result = mypy_parse_and_type_check(test)\n assert not result.errors\n tree = result.graph[TEST_MODULE].tree\n assert tree\n\n import mypy.traverser\n\n class MyVisitor(mypy.traverser.TraverserVisitor):\n def visit_assignment_stmt(self, stmt: mypy.nodes.AssignmentStmt) -> None:\n (lval,) = stmt.lvalues\n assert isinstance(\n lval,\n mypy.nodes.MemberExpr\n | mypy.nodes.NameExpr\n | mypy.nodes.TupleExpr\n | mypy.nodes.SuperExpr\n | mypy.nodes.IndexExpr,\n )\n if isinstance(lval, mypy.nodes.MemberExpr) and lval.def_var is not None:\n assert lval.def_var is lval.node\n if isinstance(stmt.rvalue, mypy.nodes.TempNode) and stmt.rvalue.no_rhs:\n assert stmt.type is not None\n assert lval.is_new_def\n super().visit_assignment_stmt(stmt)\n\n vis = MyVisitor()\n tree.accept(vis)\n\n\ndef test_super_exprs() -> None:\n def test():\n class Base:\n def __init__(self, x: int) -> None:\n self.x = x\n self.var: int = 0\n\n def method(self) -> int:\n return self.x\n\n class Derived(Base):\n def __init__(self, x: int, y: int) -> None:\n super().__init__(x=x)\n super(Base, self).var = 123 # type: ignore[misc]\n self.y = y\n\n def method(self) -> int:\n return super().method() + self.y\n\n result = mypy_parse_and_type_check(test)\n tree = result.graph[TEST_MODULE].tree\n assert tree\n assert not result.errors\n\n\ndef test_special_decorators() -> None:\n def test() -> None:\n import abc\n import typing\n\n class Class(abc.ABC):\n @property\n def prop_get_set_del(self) -> int:\n return self._x\n\n @prop_get_set_del.setter\n def prop_get_set_del(self, value: int) -> None:\n self._x = value\n\n @prop_get_set_del.deleter\n def prop_get_set_del(self) -> None:\n del self._x\n\n @property\n def prop_get_set(self) -> str:\n return self._y\n\n @prop_get_set.setter\n def prop_get_set(self, value: str) -> None:\n self._y = value\n\n @property\n def prop_get(self) -> bytes:\n return b\"\"\n\n @abc.abstractmethod\n def abstract_method(self, x: str) -> str: ...\n\n @staticmethod\n def static() -> int:\n return 42\n\n @classmethod\n def klass(cls) -> int:\n return cls().static()\n\n @typing.overload\n def overloaded(self, x: int) -> None: ...\n\n @typing.overload\n def overloaded(self, x: str) -> None: ...\n\n def overloaded(self, x: int | str) -> None:\n if isinstance(x, int):\n self.prop_get_set_del = x\n else:\n self.prop_get_set = x\n\n test()\n result = mypy_parse_and_type_check(test)\n assert not result.errors\n tree = result.graph[TEST_MODULE].tree\n assert tree\n class_def = tree.defs[-1]\n assert isinstance(class_def, mypy.nodes.ClassDef)\n\n\ndef test_variadic_tuple_type() -> None:\n def test():\n from collections.abc import Sequence\n\n def func(items: Sequence[int]) -> tuple[int, ...]:\n return tuple(items)\n\n def func2(items: Sequence[int]) -> tuple[int, int]:\n return items[0], len(items)\n\n x = func([1, 2, 3])\n y = func2([1, 2, 3])\n\n test()\n result = mypy_parse_and_type_check(test)\n assert not result.errors\n tree = result.graph[TEST_MODULE].tree\n assert tree\n func = tree.defs[1]\n assert isinstance(func, mypy.nodes.FuncDef)\n assert isinstance(func.type, mypy.types.CallableType)\n assert type(func.type.ret_type) == mypy.types.Instance\n func2 = tree.defs[2]\n assert isinstance(func2, mypy.nodes.FuncDef)\n assert isinstance(func2.type, mypy.types.CallableType)\n assert type(func2.type.ret_type) == mypy.types.TupleType\n\n\ndef test_tuple_covariance() -> None:\n def test():\n class Base:\n pass\n\n class Derived(Base):\n pass\n\n def func_out() -> tuple[Base, object]:\n return Derived(), 1\n\n def func_in(a: tuple[Base, object]) -> None:\n print(a)\n\n func_in((Derived(), 2))\n\n test()\n result = mypy_parse_and_type_check(test)\n assert not result.errors\n tree = result.graph[TEST_MODULE].tree\n assert tree\n\n\ndef test_if_else_expr_combined_type() -> None:\n def test():\n import typing\n\n def random() -> float:\n return 0.1\n\n class Base:\n pass\n\n class Derived(Base):\n pass\n\n typing.reveal_type(Base() if random() > 0.5 else Derived())\n\n typing.reveal_type(\"str\" if random() < 0.5 else 1)\n okay: str | int = \"str\" if random() < 0.5 else 1\n typing.reveal_type(okay)\n bad: str = \"str\" if random() == 1 else 1\n\n result = mypy_parse_and_type_check(test)\n assert strip_error_prefixes(result) == [\n 'note: Revealed type is \"__test__.Base\"',\n \"note: Revealed type is \\\"Union[Literal['str']?, Literal[1]?]\\\"\",\n 'note: Revealed type is \"Union[builtins.str, builtins.int]\"',\n 'error: Incompatible types in assignment (expression has type \"str | int\",'\n ' variable has type \"str\") [assignment]',\n ]\n tree = result.graph[TEST_MODULE].tree\n assert tree\n assert list(map(repr, get_revealed_types(result, tree))) == [\n \"__test__.Base\",\n \"Union[Literal['str']?, Literal[1]?]\",\n \"Union[builtins.str, builtins.int]\",\n ]\n\n\ndef test_or_expr_combined_type() -> None:\n def test():\n import typing\n\n def random() -> float:\n return 0.1\n\n class Base:\n def __bool__(self) -> bool:\n return random() < 0.5\n\n class Derived(Base):\n pass\n\n typing.reveal_type(Base() or Derived())\n typing.reveal_type(Derived() or Base())\n true = True\n typing.reveal_type(true or Base())\n one = 1\n typing.reveal_type(Base() or one)\n bad: Derived = Base() or Derived()\n okay: Base = Base() or Derived()\n\n result = mypy_parse_and_type_check(test)\n assert strip_error_prefixes(result) == [\n 'note: Revealed type is \"__test__.Base\"',\n 'note: Revealed type is \"__test__.Base\"',\n 'note: Revealed type is \"Union[Literal[True], __test__.Base]\"',\n 'note: Revealed type is \"Union[__test__.Base, builtins.int]\"',\n 'error: Incompatible types in assignment (expression has type \"Base\",'\n ' variable has type \"Derived\") [assignment]',\n ]\n tree = result.graph[TEST_MODULE].tree\n assert tree\n assert list(map(repr, get_revealed_types(result, tree))) == [\n \"__test__.Base\",\n \"__test__.Base\",\n \"Union[Literal[True], __test__.Base]\",\n \"Union[__test__.Base, builtins.int]\",\n ]\n\n\ndef test_global_types() -> None:\n def test():\n import typing\n\n a = \"a\"\n b: typing.Final = \"b\"\n c = a + b\n d: typing.Final = a + b\n one = 1\n two: typing.Final = 2\n three = one + two\n four: typing.Final = three + one\n true = True\n false: typing.Final = False\n true_and_false = true and false\n true_or_false: typing.Final = true or false\n b_a = b\"a\"\n b_b: typing.Final = b\"b\"\n b_c = b_a + b_b\n b_d: typing.Final = 2 * b_b\n\n def silly_function() -> None:\n print(\n a,\n b,\n c,\n d,\n one,\n two,\n three,\n four,\n true,\n false,\n true_and_false,\n true_or_false,\n b_a,\n b_b,\n b_c,\n b_d,\n )\n\n result = mypy_parse_and_type_check(test)\n tree = result.graph[TEST_MODULE].tree\n assert tree\n silly_func_def = tree.defs[-1]\n assert isinstance(silly_func_def, mypy.nodes.FuncDef)\n assert len(silly_func_def.body.body) == 1\n print_stmt = silly_func_def.body.body[0]\n assert isinstance(print_stmt, mypy.nodes.ExpressionStmt)\n print_call = print_stmt.expr\n assert isinstance(print_call, mypy.nodes.CallExpr)\n for arg_name_expr in print_call.args:\n assert isinstance(arg_name_expr, mypy.nodes.NameExpr)\n assert arg_name_expr.kind == mypy.nodes.GDEF\n assert not (\n arg_name_expr.is_alias_rvalue\n or arg_name_expr.is_inferred_def\n or arg_name_expr.is_new_def\n or arg_name_expr.is_special_form\n )\n assert isinstance(arg_name_expr.node, mypy.nodes.Var)\n if isinstance(arg_name_expr.node.type, mypy.types.LiteralType):\n inst_type = arg_name_expr.node.type.fallback\n else:\n assert isinstance(arg_name_expr.node.type, mypy.types.Instance)\n inst_type = arg_name_expr.node.type\n assert inst_type.type.fullname in (\n \"builtins.str\",\n \"builtins.int\",\n \"builtins.bool\",\n \"builtins.bytes\",\n )\n\n\ndef test_annotated_metadata() -> None:\n \"\"\"Negative test - this would be a good way to add key overrides to global state storage,\n but unfortunately MyPy strips it entirely from the AST, even the unanalyzed_type\"\"\"\n\n def test() -> None:\n import typing\n import dataclasses\n\n @dataclasses.dataclass\n class StateKey:\n key: bytes\n\n counter: typing.Annotated[int, StateKey(b\"c\")] = 1\n\n result = mypy_parse_and_type_check(test)\n tree = result.graph[TEST_MODULE].tree\n assert tree\n ass = tree.defs[-1]\n assert isinstance(ass, mypy.nodes.AssignmentStmt)\n assert isinstance(ass.unanalyzed_type, mypy.types.UnboundType)\n assert len(ass.unanalyzed_type.args) == 2\n _, ann_arg = ass.unanalyzed_type.args\n assert isinstance(ann_arg, mypy.types.RawExpressionType) and ann_arg.literal_value is None\n\n\ndef test_dataclass_transform_frozen() -> None:\n def test() -> None:\n import typing\n\n @typing.dataclass_transform(\n eq_default=False, order_default=False, kw_only_default=False, field_specifiers=()\n )\n class _StructMeta(type):\n def __new__(\n cls,\n name: str,\n bases: tuple[type, ...],\n namespace: dict[str, object],\n *,\n kw_only: bool = False,\n ) -> \"_StructMeta\":\n raise NotImplementedError\n\n class StructBase(metaclass=_StructMeta):\n pass\n\n class Struct(StructBase):\n field: int\n\n class FrozenStruct(StructBase, frozen=True):\n field: int\n\n class UnfrozenStruct(StructBase, frozen=False):\n field: int\n\n f1 = Struct(1)\n f2 = FrozenStruct(1)\n f3 = UnfrozenStruct(1)\n f1.field = 1\n f2.field = 2\n f3.field = 3\n\n result = mypy_parse_and_type_check(test)\n assert strip_error_prefixes(result) == [\n 'error: Property \"field\" defined in \"FrozenStruct\" is read-only [misc]',\n ]\n tree = result.graph[TEST_MODULE].tree\n assert isinstance(tree, mypy.nodes.MypyFile)\n struct_cls_def = get_class_by_name(tree, \"Struct\")\n assert struct_cls_def.info.metadata[\"dataclass\"][\"frozen\"] is False\n frozen_struct_cls_def = get_class_by_name(tree, \"FrozenStruct\")\n assert frozen_struct_cls_def.info.metadata[\"dataclass\"][\"frozen\"] is True\n unfrozen_struct_cls_def = get_class_by_name(tree, \"UnfrozenStruct\")\n assert unfrozen_struct_cls_def.info.metadata[\"dataclass\"][\"frozen\"] is False\n\n\ndef test_bound_method_types() -> None:\n def test():\n import typing\n\n def func(\n a: bool,\n \/,\n b: int,\n b2: None = None,\n *args: str,\n c: bytes,\n d: float | None = None,\n **kwargs: complex,\n ) -> bool:\n return a\n\n class Class:\n def __init__(self) -> None:\n pass\n\n @staticmethod\n def static_method(b: int) -> int:\n return b\n\n @classmethod\n def class_method(cls, c: str) -> str:\n return c\n\n def instance_method(self, d: bytes) -> bytes:\n return d\n\n typing.reveal_type(func)\n typing.reveal_type(Class)\n typing.reveal_type(Class.__init__)\n typing.reveal_type(Class.static_method)\n typing.reveal_type(Class.class_method)\n typing.reveal_type(Class.instance_method)\n inst = Class()\n typing.reveal_type(inst.static_method)\n typing.reveal_type(inst.class_method)\n typing.reveal_type(inst.instance_method)\n\n result = mypy_parse_and_type_check(test)\n tree = result.graph[TEST_MODULE].tree\n assert tree\n reveled_types = get_revealed_types(result, tree)\n assert len(reveled_types) == 9\n assert all(isinstance(t, mypy.types.CallableType) for t in reveled_types)\n\n\ndef test_special_indexing() -> None:\n def test():\n import typing\n\n def func(abc: typing.Literal[\"a\", \"b\", \"c\"]) -> str:\n X = typing.Literal[0]\n Y = tuple[typing.Literal[0, 1, 2], str]\n y = tuple[typing.Literal[0, 1, 2], str]((0, abc))\n return abc\n\n result = mypy_parse_and_type_check(test)\n tree = result.graph[TEST_MODULE].tree\n assert tree\n\n\n@pytest.mark.xfail(reason=\"mypy doesn't consider equality in match-case with value patterns\")\ndef test_match_case_reachability() -> None:\n def test():\n import typing\n\n class MyInt:\n def __init__(self, value: int):\n self.value = value\n\n def __eq__(self, other: object) -> bool:\n return (other == self.value) or (\n isinstance(other, MyInt) and other.value == self.value\n )\n\n match MyInt(1):\n case 1:\n x = None\n typing.reveal_type(x)\n case _:\n x = \"ironically unreachable\"\n typing.reveal_type(x)\n\n return typing.reveal_type(x)\n\n assert test() is None\n\n result = mypy_parse_and_type_check(test)\n tree = result.graph[TEST_MODULE].tree\n assert list(map(str, get_revealed_types(result, tree))) == [\n \"None\",\n \"builtins.str\",\n \"Union[builtins.str, None]\",\n ]\n","repo_name":"algorandfoundation\/puya","path":"tests\/test_mypy_behaviour.py","language":"Python","license":"NOASSERTION","size":30008} {"code":"from collections.abc import Mapping\n\nimport pytest\n\nfrom puyapy.awst_build import pytypes\nfrom tests import VCS_ROOT\n\n_STUB_SUFFIX = \".pyi\"\n\n\ndef stub_class_names_and_predefined_aliases() -> list[str]:\n from mypy import build, find_sources, fscache, nodes\n\n from puyapy.compile import get_mypy_options\n\n stubs_dir = (VCS_ROOT \/ \"stubs\" \/ \"algopy-stubs\").resolve()\n mypy_options = get_mypy_options()\n fs_cache = fscache.FileSystemCache()\n mypy_build_sources = find_sources.create_source_list(\n paths=[str(stubs_dir)], options=mypy_options, fscache=fs_cache\n )\n build_result = build.build(sources=mypy_build_sources, options=mypy_options, fscache=fs_cache)\n result = set()\n\n algopy_module = build_result.files[\"algopy\"]\n modules_to_visit = [algopy_module]\n seen_modules = set()\n while modules_to_visit:\n module = modules_to_visit.pop()\n if module in seen_modules:\n continue\n seen_modules.add(module)\n for name, symbol in module.names.items():\n if name.startswith(\"_\") or symbol.module_hidden or symbol.kind != nodes.GDEF:\n continue\n match symbol.node:\n case nodes.MypyFile() as new_module:\n modules_to_visit.append(new_module)\n case nodes.TypeAlias(fullname=alias_name):\n result.add(alias_name)\n case nodes.TypeInfo(fullname=class_name):\n result.add(class_name)\n return sorted(result)\n\n\n@pytest.fixture(scope=\"session\")\ndef builtins_registry() -> Mapping[str, pytypes.PyType]:\n return pytypes.builtins_registry()\n\n\n@pytest.mark.parametrize(\n \"fullname\",\n stub_class_names_and_predefined_aliases(),\n ids=str,\n)\ndef test_stub_class_names_lookup(\n builtins_registry: Mapping[str, pytypes.PyType], fullname: str\n) -> None:\n assert fullname in builtins_registry, f\"{fullname} is missing from pytypes\"\n","repo_name":"algorandfoundation\/puya","path":"tests\/test_pytypes.py","language":"Python","license":"NOASSERTION","size":1939} {"code":"import json\nfrom collections.abc import Iterable, Mapping\nfrom pathlib import Path\n\nimport attrs\nimport mypy.nodes\nimport mypy.types\nimport pytest\n\nfrom puya.awst.txn_fields import TxnField\nfrom puya.parse import SourceLocation\nfrom puyapy.awst_build import pytypes\nfrom puyapy.awst_build.context import type_to_pytype\nfrom puyapy.awst_build.eb.transaction.itxn_args import PYTHON_ITXN_ARGUMENTS\nfrom puyapy.awst_build.eb.transaction.txn_fields import PYTHON_TXN_FIELDS\nfrom tests import EXAMPLES_DIR, VCS_ROOT\nfrom tests.utils import get_awst_cache\n\n# the need to use approval \/ clear_state pages is abstracted away by\n# allowing a tuple of pages in the stubs layer\n_MAPPED_INNER_TXN_FIELDS = {\n TxnField.ApprovalProgramPages: TxnField.ApprovalProgram,\n TxnField.ClearStateProgramPages: TxnField.ClearStateProgram,\n}\n_INTENTIONALLY_OMITTED_INNER_TXN_FIELDS = {\n *_MAPPED_INNER_TXN_FIELDS.values(),\n # only allow enum version of type\n TxnField.Type,\n}\n\n\n@attrs.frozen\nclass FieldType:\n is_array: bool\n field_type: pytypes.PyType\n\n\ndef _get_type_infos(type_names: Iterable[str]) -> Iterable[mypy.nodes.TypeInfo]:\n awst_cache = get_awst_cache(EXAMPLES_DIR)\n\n for type_name in type_names:\n module_id, symbol_name = type_name.rsplit(\".\", maxsplit=1)\n module = awst_cache.parse_result.ordered_modules[module_id].node\n\n symbol = module.names[symbol_name]\n node = symbol.node\n assert isinstance(node, mypy.nodes.TypeInfo), f\"{type_name} not found in {module}\"\n yield node\n\n\n@pytest.fixture(scope=\"session\")\ndef builtins_registry() -> Mapping[str, pytypes.PyType]:\n return pytypes.builtins_registry()\n\n\ndef test_group_transaction_members() -> None:\n gtxn_types = [t.name for t in pytypes.GroupTransactionTypes.values()]\n gtxn_types.append(pytypes.GroupTransactionBaseType.name)\n for type_info in _get_type_infos(gtxn_types):\n unknown = sorted(set(type_info.protocol_members) - PYTHON_TXN_FIELDS.keys())\n assert not unknown, f\"{type_info.fullname}: Unknown TxnField members: {unknown}\"\n\n\ndef test_field_vs_argument_name_consistency() -> None:\n itxn_args = {\n (_MAPPED_INNER_TXN_FIELDS.get(params.field, params.field), name)\n for name, params in PYTHON_ITXN_ARGUMENTS.items()\n }\n txn_fields = {(f.field, name) for name, f in PYTHON_TXN_FIELDS.items()}\n bad_itxn_args = itxn_args - txn_fields\n assert not bad_itxn_args\n\n\ndef test_inner_transaction_field_setters() -> None:\n unmapped = {\n tf for tf in TxnField if tf.is_inner_param\n } - _INTENTIONALLY_OMITTED_INNER_TXN_FIELDS\n for type_info in _get_type_infos(\n t.name for t in pytypes.InnerTransactionFieldsetTypes.values()\n ):\n init_args: set[str] | None = None\n for member in (\"__init__\", \"set\"):\n func_def = type_info.names[member].node\n assert isinstance(func_def, mypy.nodes.FuncDef)\n arg_names = {a for a in func_def.arg_names if a is not None}\n arg_names.remove(\"self\")\n unknown = sorted(arg_names - PYTHON_ITXN_ARGUMENTS.keys())\n assert not unknown, f\"{type_info.fullname}: Unknown TxnField param members: {unknown}\"\n unmapped -= {\n PYTHON_ITXN_ARGUMENTS[arg_name].field\n for arg_name in arg_names\n if arg_name not in unknown\n }\n\n if init_args is None:\n init_args = arg_names\n else:\n difference = init_args.symmetric_difference(arg_names)\n assert (\n not difference\n ), f\"{type_info.fullname}.{member} field difference: {difference}\"\n assert not unmapped, f\"Unmapped inner param fields: {sorted(f.immediate for f in unmapped)}\"\n\n\ndef test_inner_transaction_members() -> None:\n for type_info in _get_type_infos(t.name for t in pytypes.InnerTransactionResultTypes.values()):\n unknown = sorted(set(type_info.protocol_members) - PYTHON_TXN_FIELDS.keys())\n assert not unknown, f\"{type_info.fullname}: Unknown TxnField members: {unknown}\"\n\n\n_FAKE_SOURCE_LOCATION = SourceLocation(file=Path(__file__).resolve(), line=1)\n\n\ndef test_txn_fields(builtins_registry: Mapping[str, pytypes.PyType]) -> None:\n # collect all fields that are protocol members\n txn_types = [t.name for t in pytypes.GroupTransactionTypes.values()]\n txn_types.append(pytypes.GroupTransactionBaseType.name)\n txn_types.extend(t.name for t in pytypes.InnerTransactionResultTypes.values())\n seen_fields = set[str]()\n invalid_types = \"\"\n for type_info in _get_type_infos(txn_types):\n for member in type_info.protocol_members:\n seen_fields.add(member)\n txn_field_data = PYTHON_TXN_FIELDS[member]\n field_type = FieldType(\n is_array=txn_field_data.field.is_array, field_type=txn_field_data.type\n )\n member_mypy_type = type_info[member].type\n assert member_mypy_type is not None, f\"Expected {type_info}.{member} to have a type\"\n member_type = _member_to_field_type(builtins_registry, member_mypy_type)\n assert field_type == member_type\n\n # add fields that are arguments\n for type_info in _get_type_infos(\n t.name for t in pytypes.InnerTransactionFieldsetTypes.values()\n ):\n for member in (\"__init__\", \"set\"):\n func_def = type_info.names[member].node\n assert isinstance(func_def, mypy.nodes.FuncDef)\n assert func_def.type is not None\n func_type = type_to_pytype(\n builtins_registry, func_def.type, source_location=_FAKE_SOURCE_LOCATION\n )\n assert isinstance(func_type, pytypes.FuncType)\n for arg in func_type.args:\n assert arg.name is not None\n if arg.name == \"self\":\n continue\n seen_fields.add(arg.name)\n txn_field_param = PYTHON_ITXN_ARGUMENTS[arg.name]\n txn_field = txn_field_param.field\n if isinstance(arg.type, pytypes.UnionType):\n arg_types = arg.type.types\n else:\n arg_types = (arg.type,)\n assert set(txn_field_param.literal_overrides.keys()).issubset(arg_types)\n if txn_field.is_array:\n arg_types = tuple(\n vt.items for vt in arg_types if isinstance(vt, pytypes.VariadicTupleType)\n )\n if txn_field_param.auto_serialize_bytes:\n assert arg_types == (pytypes.ObjectType,)\n else:\n non_literal_arg_types = {\n at for at in arg_types if not isinstance(at, pytypes.LiteralOnlyType)\n }\n assert non_literal_arg_types == {\n txn_field_param.type,\n *txn_field_param.additional_types,\n }\n\n # anything missing is an error\n missing_fields = sorted(PYTHON_TXN_FIELDS.keys() - seen_fields)\n assert not missing_fields, f\"Txn Fields not mapped: {missing_fields}\"\n\n # any invalid_types is an error\n assert not invalid_types, f\"Invalid field types: {invalid_types}\"\n\n\ndef test_mismatched_langspec_txn_fields() -> None:\n langspec_path = VCS_ROOT \/ \"langspec.puya.json\"\n langspec = json.loads(langspec_path.read_text())\n arg_enums = langspec[\"arg_enums\"]\n all_txn_fields = {field[\"name\"] for field in arg_enums[\"txn\"]}\n txn_array_fields = {field[\"name\"] for field in arg_enums[\"txna\"]}\n txn_single_fields = all_txn_fields - txn_array_fields\n inner_txn_fields = {field[\"name\"] for field in arg_enums[\"itxn_field\"]}\n\n assert not _set_difference(\n all_txn_fields, [f.immediate for f in TxnField]\n ), \"txn field mismatch\"\n\n assert not _set_difference(\n txn_single_fields, [f.immediate for f in TxnField if not f.is_array]\n ), \"single txn field mismatch\"\n\n assert not _set_difference(\n txn_array_fields, [f.immediate for f in TxnField if f.is_array]\n ), \"array txn field mismatch\"\n\n assert not _set_difference(\n inner_txn_fields, [f.immediate for f in TxnField if f.is_inner_param]\n ), \"inner txn field mismatch\"\n\n\ndef _set_difference(expected: set[str], actual: list[str]) -> list[str]:\n return list(expected.symmetric_difference(actual))\n\n\ndef _member_to_field_type(\n builtins_registry: Mapping[str, pytypes.PyType], typ: mypy.types.Type\n) -> FieldType:\n is_array = False\n if isinstance(typ, mypy.types.CallableType):\n is_array = len(typ.arg_names) > 1\n typ = typ.ret_type\n\n field_type = type_to_pytype(builtins_registry, typ, source_location=_FAKE_SOURCE_LOCATION)\n\n return FieldType(is_array=is_array, field_type=field_type)\n","repo_name":"algorandfoundation\/puya","path":"tests\/test_transaction_fields.py","language":"Python","license":"NOASSERTION","size":8838} {"code":"import functools\nimport typing\nfrom collections.abc import Collection, Iterable, Mapping, Sequence\nfrom pathlib import Path\n\nimport attrs\n\nfrom puya.awst import nodes as awst_nodes\nfrom puya.compilation_artifacts import CompilationArtifact\nfrom puya.compile import awst_to_teal\nfrom puya.errors import CodeError\nfrom puya.log import Log, LogLevel, logging_context\nfrom puya.parse import SourceLocation\nfrom puya.program_refs import ContractReference, LogicSigReference\nfrom puya.utils import pushd\nfrom puyapy.awst_build.main import transform_ast\nfrom puyapy.compile import output_awst, parse_with_mypy, write_arc4_clients\nfrom puyapy.options import PuyaPyOptions\nfrom puyapy.parse import ParseResult, SourceDiscoveryMechanism\nfrom puyapy.template import parse_template_key_value\nfrom puyapy.utils import determine_out_dir\nfrom tests import EXAMPLES_DIR, TEST_CASES_DIR\n\nAPPROVAL_EXTENSIONS = frozenset((\".teal\", \".awst\", \".ir\", \".mir\", \".arc32.json\", \".arc56.json\"))\nUNSTABLE_LOG_PREFIXES = {\n LogLevel.debug: (\n \"Building AWST for \",\n \"Skipping algopy stub \",\n \"Skipping typeshed stub \",\n \"Skipping stdlib stub \",\n \"Discovered user module \",\n # ignore platform specific paths\n \"Using python executable: \",\n \"Using python site-packages: \",\n \"Found algopy: \",\n ),\n}\n\n\ndef _get_root_dir(path: Path) -> Path:\n if path.is_relative_to(EXAMPLES_DIR):\n return EXAMPLES_DIR\n if path.is_relative_to(TEST_CASES_DIR):\n return TEST_CASES_DIR\n return path if path.is_dir() else path.parent\n\n\nclass _CompileCache(typing.NamedTuple):\n parse_result: ParseResult\n module_awst: awst_nodes.AWST\n compilation_set: Sequence[ContractReference | LogicSigReference]\n logs: list[Log]\n\n\n@functools.cache\ndef get_awst_cache(root_dir: Path) -> _CompileCache:\n # note that this caching assumes that AWST is the same across all\n # optimisation and debug levels, which is currently true.\n # if this were to no longer be true, this test speedup strategy would need to be revisited\n with pushd(root_dir), logging_context() as log_ctx:\n parse_result = parse_with_mypy([root_dir])\n awst, compilation_set = transform_ast(parse_result)\n return _CompileCache(parse_result, awst, compilation_set, log_ctx.logs)\n\n\n@attrs.frozen(kw_only=True)\nclass CompilationResult:\n module_awst: awst_nodes.AWST\n logs: list[Log]\n teal: list[CompilationArtifact]\n src_path: Path\n \"\"\"original source path\"\"\"\n root_dir: Path\n \"\"\"examples or test_cases path\"\"\"\n\n\ndef narrowed_parse_result(parse_result: ParseResult, src_path: Path) -> ParseResult:\n filtered_ordered_modules = {\n name: sm\n for name, sm in parse_result.ordered_modules.items()\n if sm.path.resolve().is_relative_to(src_path.resolve())\n or sm.discovery_mechanism == SourceDiscoveryMechanism.dependency\n }\n return ParseResult(\n mypy_options=parse_result.mypy_options,\n ordered_modules=filtered_ordered_modules,\n )\n\n\ndef narrowed_compile_context(\n parse_result: ParseResult,\n src_path: Path,\n awst: awst_nodes.AWST,\n compilation_set: Collection[ContractReference | LogicSigReference],\n puyapy_options: PuyaPyOptions,\n) -> tuple[\n Mapping[Path, Sequence[str] | None],\n Mapping[ContractReference | LogicSigReference, Path],\n]:\n narrowed_sources_by_path = {\n sm.path: sm.lines\n for sm in parse_result.ordered_modules.values()\n if sm.path.resolve().is_relative_to(src_path)\n and sm.discovery_mechanism != SourceDiscoveryMechanism.dependency\n }\n awst_lookup = {n.id: n for n in awst}\n compilation_set = {\n target_id: determine_out_dir(loc.file.parent, puyapy_options)\n for target_id, loc in ((t, awst_lookup[t].source_location) for t in compilation_set)\n if loc.file in narrowed_sources_by_path\n }\n return narrowed_sources_by_path, compilation_set\n\n\ndef _filter_logs(logs: list[Log], root_dir: Path, src_path: Path) -> list[Log]:\n root_dir = root_dir.resolve()\n relative_src_root = src_path.relative_to(root_dir)\n result = []\n for log in logs:\n # ignore logs that come from files outside of src_path as these are\n # logs emitted during the cached AWST parsing step\n relative_path = get_relative_path(log.location, root_dir)\n if relative_path and relative_src_root not in (\n relative_path,\n *relative_path.parents,\n ):\n continue\n\n # ignore logs that are not output in a consistent order\n log_prefixes_to_ignore = UNSTABLE_LOG_PREFIXES.get(log.level)\n if log_prefixes_to_ignore and log.message.startswith(log_prefixes_to_ignore):\n continue\n\n result.append(log)\n return result\n\n\ndef get_relative_path(location: SourceLocation | None, root_dir: Path) -> Path | None:\n if not location or not location.file:\n return None\n try:\n return location.file.relative_to(root_dir)\n except ValueError:\n return None\n\n\ndef _get_log_errors(logs: Iterable[Log]) -> str:\n return \"\\n\".join(str(log) for log in logs if log.level == LogLevel.error)\n\n\ndef compile_src_from_options(options: PuyaPyOptions) -> CompilationResult:\n if options.out_dir is None:\n options = attrs.evolve(options, out_dir=Path(\"out_tests\"))\n (src_path,) = options.paths\n root_dir = _get_root_dir(src_path)\n src_path = src_path.resolve()\n parse_result, awst, compilation_set, awst_logs = get_awst_cache(root_dir)\n awst_logs = _filter_logs(awst_logs, root_dir, src_path)\n\n awst_errors = _get_log_errors(awst_logs)\n if awst_errors:\n raise CodeError(awst_errors)\n # create a new context from cache and specified src\n with logging_context() as log_ctx:\n narrow_sources_by_path, narrow_compilation_set = narrowed_compile_context(\n parse_result, src_path, awst, compilation_set, options\n )\n # this should be correct and exhaustive but relies on independence of examples\n narrowed_awst = [n for n in awst if n.source_location.file in narrow_sources_by_path]\n\n with pushd(root_dir):\n if options.output_awst and options.out_dir:\n output_awst(narrowed_awst, options.out_dir)\n\n try:\n teal = awst_to_teal(\n log_ctx, options, narrow_compilation_set, narrow_sources_by_path, narrowed_awst\n )\n except SystemExit as ex:\n raise CodeError(_get_log_errors(log_ctx.logs)) from ex\n\n filtered_teal = [t for t in teal if t.id in narrow_compilation_set]\n\n if options.output_client:\n write_arc4_clients(\n options.template_vars_prefix, narrow_compilation_set, filtered_teal\n )\n\n return CompilationResult(\n module_awst=narrowed_awst,\n logs=awst_logs + log_ctx.logs,\n teal=filtered_teal,\n root_dir=root_dir,\n src_path=src_path,\n )\n\n\n@attrs.frozen\nclass PuyaTestCase:\n path: Path\n\n @property\n def root(self) -> Path:\n return self.path.parent\n\n @property\n def name(self) -> str:\n return self.path.name\n\n @property\n def template_vars_path(self) -> Path | None:\n template_vars_path = self.path \/ \"template.vars\"\n return template_vars_path.resolve() if template_vars_path.exists() else None\n\n @property\n def id(self) -> str:\n return f\"{self.root.stem}\/{self.name}\"\n\n\ndef load_template_vars(path: Path | None) -> tuple[str, dict[str, int | bytes]]:\n prefix = \"TMPL_\"\n prefix_prefix = \"prefix=\"\n\n result = {}\n if path is not None:\n for line in path.read_text(\"utf8\").splitlines():\n if line.startswith(prefix_prefix):\n prefix = line.removeprefix(prefix_prefix)\n else:\n key, value = parse_template_key_value(line)\n result[key] = value\n return prefix, result\n","repo_name":"algorandfoundation\/puya","path":"tests\/utils\/__init__.py","language":"Python","license":"NOASSERTION","size":8011} {"code":"import hashlib\nimport itertools\n\n\ndef sha_256_raw(b: bytes) -> bytes:\n return hashlib.sha256(b).digest()\n\n\nclass MerkleTree:\n def __init__(self, data: list[bytes]):\n self._tree = [[sha_256_raw(d) for d in data]]\n\n while len(self._tree[-1]) != 1:\n next_level = list[bytes]()\n for pair in itertools.batched(self._tree[-1], 2):\n a, b = pair if len(pair) == 2 else (pair[0], pair[0])\n a_b_hash = self.hash_pair(a, b)\n next_level.append(a_b_hash)\n self._tree.append(next_level)\n\n @property\n def root(self) -> bytes:\n return self._tree[-1][0]\n\n @staticmethod\n def hash_pair(a: bytes, b: bytes) -> bytes:\n return sha_256_raw(a + b if a < b else b + a)\n\n def get_proof(self, data: bytes) -> list[bytes]:\n proof = list[bytes]()\n current = sha_256_raw(data)\n for level in self._tree:\n index = level.index(current)\n sibling_index = index - 1 if index % 2 == 1 else index + 1\n if sibling_index >= len(level):\n proof.append(current)\n else:\n proof.append(level[sibling_index])\n current = self.hash_pair(current, proof[-1])\n return proof[:-1]\n\n def verify_proof(self, data: bytes, proof: list[bytes]) -> bool:\n result = sha_256_raw(data)\n for item in proof:\n result = self.hash_pair(result, item)\n return result == self.root\n\n def __repr__(self) -> str:\n return \"\\n\".join([str(level) for level in self._tree])\n","repo_name":"algorandfoundation\/puya","path":"tests\/utils\/merkle_tree.py","language":"Python","license":"NOASSERTION","size":1580}