# Copyright (c) 2026 Huawei Technologies Co., Ltd.
# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
# CANN Open Software License Agreement Version 2.0 (the "License").
# Please refer to the License for details. You may not use this file except in compliance with the License.
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
# See LICENSE in the root of the software repository for the full text of the License.
# -----------------------------------------------------------------------------------------------------------

"""Expression parsing helpers for ASTParser."""

from __future__ import annotations

import ast
import math
from typing import Any

from pypto.pypto_impl import ir
from pypto.pypto_impl.ir import DataType
from pypto_pro.ir import op as ir_op
from pypto_pro.ir._operators import make_binary as _make_binary
from pypto_pro.ir._utils import _const_int_value, _normalize_expr, _to_make_tuple
from pypto_pro.ir.op._op_registry import _OP_REGISTRY

from ..._errors import (
    InvalidFormat,
    InvalidOperation,
    InvalidShape,
    InvalidType,
    InvalidVal,
    NameNotFound,
    NotSupported,
    OutOfRange,
    PyptoProError,
    current_span,
)
from ._expr_evaluator import ExprEvaluator
from ._tuple_type_registry import TupleTypeInfo
from ._utils import _check_expression_value, _is_const_expr, _is_simt_func_type
from .diagnostics import (
    check_fits_dtype,
    make_const_int,
)


def _is_enum_value(value: Any) -> bool:
    """Whether ``value`` is an enum constant (DataType or a pybind enum).

    DataType is a py::class_ without ``__members__``, so it is matched by type;
    generic pybind enums (MemorySpace, RoundMode, ...) expose ``.value`` and a
    class-level ``__members__``. Mirrors the predicate used in parse_attribute /
    parse_name.
    """
    return isinstance(value, ir.DataType) or (
        hasattr(type(value), "__members__") and hasattr(value, "value")
    )

class ExpressionParserMixin:
    """Mixin containing expression, attribute, and subscript parsing."""

    _OBJECT_OP_PREFIXES = {
        ir.SimtGroupKind.ThreadBlock: "simt.ThreadBlock",
        ir.SimtGroupKind.ThreadBlockTile: "simt.ThreadBlockTile",
        ir.SimtGroupKind.CoalescedGroup: "simt.CoalescedGroup",
        ir.SimtGroupKind.GridGroup: "simt.GridGroup",
        ir.TupleType: "TileGroup",
        ir.WindowType: "dist.Window",
    }

    def lookup_expr_by_name(self, name: str) -> Any | None:
        """Resolve a parser name to its current expression."""
        value = self.scope_manager.lookup_var_bounded(name)
        if not isinstance(value, ir.Var):
            return value

        constant = self.const_env.get(value.name)
        if constant is not None:
            return constant

        make_tuple = self.make_tuple_env.get(value.name)
        return make_tuple if make_tuple is not None else value

    def local_binding(self, name: str) -> "tuple[str, Any] | None":
        """How *name* is bound inside the kernel, or None if it is not bound there.

        The single definition of kernel-local name precedence, shared by name
        parsing and by compile-time evaluation so the two cannot disagree:

        * ``("const", <IR constant>)`` — folded in ``const_env`` (``addr = 0x10000``);
        * ``("runtime", <MakeTuple>)`` — an immutable tuple expression containing
          one or more runtime values;
        * ``("parse_time", <object>)`` — bound to a value that has no IR form and
          therefore only exists while parsing (``dt = pl.DT_FP16``);
        * ``("runtime", <IR expression>)`` — a value that only exists at run time.

        A name not bound in the kernel returns None and falls back to the
        enclosing Python scope, matching Python's own scoping.
        """
        value = self.lookup_expr_by_name(name)
        if value is None:
            return None
        if _is_const_expr(value):
            return ("const", value)
        return ("runtime", value) if isinstance(value, ir.Expr) else ("parse_time", value)

    @staticmethod
    def _const_scalar_value(expr: ir.Expr) -> bool | int | float | None:
        """Return a scalar constant's value, including the effect of constant casts."""
        found, value = ExprEvaluator.ir_to_python_value(expr)
        return value if found and isinstance(value, (bool, int, float)) else None

    @staticmethod
    def _const_truth(expr: ir.Expr) -> bool | None:
        value = ExpressionParserMixin._const_scalar_value(expr)
        return None if value is None else bool(value)

    @staticmethod
    def _make_scalar_constant(value: bool | int | float, dtype: DataType, span: ir.Span) -> ir.Expr:
        if dtype == DataType.BOOL:
            return ir.ConstBool(bool(value), span)
        if dtype.is_float():
            # Folding must not change a program's meaning: a result the dtype cannot represent would
            # otherwise become inf (or a wrapped integer, on the branch below) with no diagnostic.
            check_fits_dtype(float(value), dtype, subject="float constant")
            return ir.ConstFloat(float(value), dtype, span)
        return make_const_int(int(value), dtype, span=span)

    @staticmethod
    def _check_uniform_tuple_types(value_type: ir.TupleType, span: ir.Span) -> None:
        """Validate that all elements of a tuple share the same type (required for variable indexing)."""
        elem_types = list(value_type.types)
        if not elem_types:
            raise OutOfRange("Cannot index into empty tuple", span=span, parser_retry=True)
        first_type = elem_types[0]
        for i, t in enumerate(elem_types[1:], 1):
            if not ir.structural_equal(t, first_type, enable_auto_mapping=False):
                raise InvalidType(
                    f"Variable tuple index requires all elements to have the same type, "
                    f"but element 0 has type {first_type} and element {i} has type {t}",
                    span=span,
                    hint="Use a constant index to access elements of different types",
                    parser_retry=True,
                )

    @staticmethod
    def _is_pl_range_call(call: ast.Call) -> bool:
        """Check if call node is pl.range()."""
        func = call.func
        return isinstance(func, ast.Attribute) and func.attr == "range"

    @staticmethod
    def _try_const_fold_in(left, elements, is_not_in, span):
        """Decide ``x in (...)`` when every operand is known at parse time.

        The single place membership is evaluated. Handles IR constants and
        parse-time-only values alike, so both callers share it: ``_desugar_in_literal``
        uses it as an optimization before building an eq-chain.
        Returns None when any operand is a runtime value, leaving the caller to
        lower the comparison instead.
        """
        known, left_value = ExprEvaluator.ir_to_python_value(left)
        if not known:
            return None
        values = []
        for elt in elements:
            known, value = ExprEvaluator.ir_to_python_value(elt)
            if not known:
                return None
            values.append(value)
        found = any(left_value == value for value in values)
        return ir.ConstBool(found != is_not_in, span)

    def parse_evaluation_statement(self, stmt: ast.Expr) -> None:
        """Parse an expression statement as an assignment with no targets.

        Evaluation statements represent operations executed for their side effects,
        with the return value discarded (e.g., synchronization barriers).

        Args:
            stmt: Expr AST node
        """
        expr = self.parse_expression(stmt.value, nested=False)
        span = self.span_tracker.get_span(stmt)

        from ...ir.op.dist_ops import _ChannelCreate

        if isinstance(expr, _ChannelCreate):
            raise InvalidOperation(
                "pld.channel must be assigned to a variable",
                span=span,
                hint="Write `ch = pld.channel(...)` at the section scope.",
            )
        # Void inline functions or python_var method calls (e.g. nbuf.advance())
        # return None or a non-IR sentinel — nothing to emit.
        if expr is None or not isinstance(expr, ir.Expr):
            return

        # Emit an assignment that discards the expression result
        self.builder.assign([], expr, span)

    def parse_expression(self, expr: ast.expr, *, nested: bool = True) -> Any:
        """Parse expression and return IR Expr.

        Args:
            expr: AST expression node
            nested: True (default) when this expression should materialize a
                ir.Call result through a let-binding so the outer expression
                only references the temporary Var. Direct AssignStmt RHS
                (``var = expr``) and expression-statement positions should pass
                ``nested=False`` to avoid redundant ``_expr_tmp_N`` indirection.
                Field and subscript assignments lower to calls whose RHS is
                an argument, so they keep the default nested materialization.

        Returns:
            IR expression
        """
        if expr in self._parsed_expr_cache:
            result = self._parsed_expr_cache[expr]
            _check_expression_value(result, self.span_tracker.get_span(expr), nested=nested)
            return result
        self._current_node = expr
        try:
            # Publish where this expression was written, so anything raised while
            # parsing it reports that location even when it never passed a span of
            # its own. Nested expressions publish over their enclosing expression,
            # so the innermost active location wins; this also covers paths
            # the dispatcher does not reach -- hand-written ``@op_impl`` handlers,
            # method calls, builtin min/max, subscripts.
            with current_span(self.span_tracker.get_span(expr)):
                result = self._parse_expression_node(expr)
        except PyptoProError as rejection:
            # Retry is opt-in: only a rejection raised with ``parser_retry=True``
            # may be re-evaluated as Python. Everything else — including a
            # position that deliberately rejected this value — propagates, so a
            # retry can never accept what the IR path refused.
            if not rejection.parser_retry:
                raise
            # Some compile-time expressions have no IR form to build at all: a
            # plain Python helper call, a dict lookup, a test against a DataType.
            # Evaluate those as Python and keep the constant; kernel-local names
            # resolve because the evaluator reads const_env as well as the closure.
            #
            # A value Python cannot produce re-raises the original IR error, and
            # one ``python_value_to_ir`` cannot lower reports its own type error,
            # so an unusable value never silently survives the retry.
            #
            # ast.Slice is not an expression position (it only appears inside a
            # rejected subscript); evaluating it would produce a Python slice
            # object and bury the real "Unsupported expression type" error.
            if isinstance(expr, ast.Slice):
                raise
            success, value = self.expr_evaluator.try_eval_expr(expr)
            if not success:
                raise
            if _is_enum_value(value):
                result = value
            else:
                span = self.span_tracker.get_span(expr)
                with current_span(span):
                    result = self.expr_evaluator.python_value_to_ir(value, span)

        _check_expression_value(result, self.span_tracker.get_span(expr), nested=nested)
        if nested:
            result = self._materialize_nested_expr(result, self.span_tracker.get_span(expr))
        self._parsed_expr_cache[expr] = result
        return result

    def _parse_expression_node(self, expr: ast.expr) -> Any:
        """Dispatch an AST expression node to its parser."""
        if isinstance(expr, ast.Name):
            result = self.parse_name(expr)
        elif isinstance(expr, ast.Constant):
            result = self.parse_constant(expr)
        elif isinstance(expr, ast.BinOp):
            result = self.parse_binop(expr)
        elif isinstance(expr, ast.Compare):
            result = self.parse_compare(expr)
        elif isinstance(expr, ast.Call):
            result = self.parse_call(expr)
        elif isinstance(expr, ast.Attribute):
            result = self.parse_attribute(expr)
        elif isinstance(expr, ast.UnaryOp):
            result = self.parse_unaryop(expr)
        elif isinstance(expr, ast.List):
            result = self.parse_list(expr)
        elif isinstance(expr, ast.Tuple):
            result = self.parse_tuple_literal(expr)
        elif isinstance(expr, ast.Subscript):
            result = self.parse_subscript(expr)
        elif isinstance(expr, ast.BoolOp):
            result = self.parse_boolop(expr)
        elif isinstance(expr, ast.IfExp):
            result = self.parse_ifexp(expr)
        else:
            raise InvalidType(
                f"Unsupported expression type: {type(expr).__name__}",
                span=self.span_tracker.get_span(expr),
                hint="Use supported expressions like variables, constants, operations, or function calls",
                parser_retry=True,
            )
        return result

    def _tensor_data_ptr(self, value):
        """The GM data pointer of a tensor descriptor, or None without a view."""
        tensor_view = value.type.tensor_view
        ptr = tensor_view.ptr if tensor_view is not None else None
        return ptr if isinstance(ptr, ir.Expr) else None

    def parse_name(self, name: ast.Name) -> ir.Expr | Any:
        """Parse variable name reference.

        Resolves names by checking the DSL scope first, then falling back
        to closure variables from the enclosing Python scope.

        Args:
            name: Name AST node

        Returns:
            IR expression (Var from scope, or constant/tuple from closure)
        """
        var_name = name.id
        # An inline helper may only resolve its own parameters and locals from
        # the DSL scope.  ``lookup_var_bounded`` behaves like the normal lookup
        # outside an inline scope, but stops at the inline boundary so a helper
        # cannot silently capture a caller IR variable.
        binding = self.local_binding(var_name)
        if binding is not None:
            value = binding[1]
            if not (isinstance(value, ir.Expr) and isinstance(value.type, ir.NoneType)):
                return value

        raise NameNotFound(
            f"Use of potentially undefined variable '{var_name}'",
            span=self.span_tracker.get_span(name),
            hint="Ensure the variable is defined before using it.",
            parser_retry=True,
        )

    def parse_constant(self, const: ast.Constant) -> ir.Expr:
        """Parse constant value.

        Args:
            const: Constant AST node

        Returns:
            IR constant expression
        """
        span = self.span_tracker.get_span(const)
        value = const.value

        if isinstance(value, bool):
            return ir.ConstBool(value, span)
        elif isinstance(value, int):
            return make_const_int(value, span=span)
        elif isinstance(value, float):
            check_fits_dtype(value, DataType.DEFAULT_CONST_FLOAT, subject="float constant")
            return ir.ConstFloat(value, DataType.DEFAULT_CONST_FLOAT, span)
        elif isinstance(value, str):
            return value
        elif value is None:
            return self.builder.builder.none()
        else:
            raise InvalidType(
                f"Unsupported constant type: {type(value)}",
                span=self.span_tracker.get_span(const),
                hint="Use int, float, or bool constants",
                parser_retry=True,
            )

    def _check_vf_scalar_division(self, op: ast.operator, left: ir.Expr, right: ir.Expr,
                                  span: ir.Span) -> None:
        """Reject scalar division-family ops inside a vector function.

        '/' constructs a scalar FloatDiv, and float '//', '%' emit
        float math; neither can be lowered inside the VF vector scope.
        """
        if not self._in_simd_vf_body():
            return
        if not (isinstance(left.type, ir.ScalarType) and isinstance(right.type, ir.ScalarType)):
            return
        if isinstance(op, ast.Div) or (
            isinstance(op, (ast.FloorDiv, ast.Mod))
            and (left.type.dtype.is_float() or right.type.dtype.is_float())
        ):
            raise NotSupported(
                "Scalar division ('/', or float '//', '%') is not supported "
                "inside a vector function",
                span=span,
                hint="Use '//' on integer scalars for integer division, or "
                "hoist the division to the kernel level.",
            )

    def parse_binop(self, binop: ast.BinOp) -> ir.Expr:
        """Parse binary operation.

        Args:
            binop: BinOp AST node

        Returns:
            IR binary expression
        """
        span = self.span_tracker.get_span(binop)
        left = self.parse_expression(binop.left)
        right = self.parse_expression(binop.right)
        self._check_vf_scalar_division(binop.op, left, right, span)

        # Tile + offset: only supported in VF section as pointer arithmetic.
        # Non-VF sections require slice syntax (tile[r:r+h, c:c+w]) for sub-views.
        if isinstance(binop.op, ast.Add) and isinstance(left.type, ir.TileType):
            if not self._in_simd_vf_body():
                raise NotSupported(
                    "Tile + offset is not supported outside VF section; "
                    "use tile[i:i+h, j:j+w] slice syntax for sub-view",
                    span=span,
                    hint="Replace `tile + offset` with `tile[row:row+h, :]` for offset access",
                )
            # VF section: lower to block.subview with original shape (VF codegen
            # only uses the offset as pointer arithmetic, shape is ignored).
            from pypto_pro.ir.op.block_ops import block_ir_op
            shape_tuple = ir.MakeTuple(left.type.shape, span)
            result = ir.create_op_call(
                block_ir_op("subview"),
                [left, right, shape_tuple],
                {},
                span,
            )
            self._transfer_tile_group_metadata(result, left)
            return result

        # Raw pointer arithmetic: only `ptr + offset` is meaningful (→ pl.addptr).
        # Every other operator on a pointer (-, *, /, //, %) is forbidden.
        if isinstance(left.type, ir.PtrType):
            if isinstance(binop.op, ast.Add):
                # Sub-byte element types (INT4/UINT4/FP4/FP4E2M1/FP4E1M2/HF4) pack two elements per
                # byte, so an element offset cannot address a half-byte and there is
                # no valid C element type to lower to. Forbid `ptr + offset` on them.
                elem_type = left.type.type
                if isinstance(elem_type, ir.ScalarType) and elem_type.dtype.get_bit() < 8:
                    raise NotSupported(
                        f"Pointer arithmetic ('ptr + offset') is not supported on the "
                        f"sub-byte element type '{elem_type.dtype.to_string()}'",
                        span=span,
                        hint="Offsetting by elements cannot address a half-byte. "
                        "Reinterpret the pointer as a byte-addressable dtype via "
                        "pl.make_ptr (e.g. pl.DT_UINT8) before pointer arithmetic.",
                        parser_retry=True,
                    )
                return ir_op.ptr.addptr(left, right, span=span)
            raise NotSupported(
                f"Unsupported operator '{type(binop.op).__name__}' on a pointer (pl.Ptr)",
                span=span,
                hint="Only 'ptr + offset' is supported for pointer arithmetic (equivalent to pl.addptr(ptr, offset)).",
                parser_retry=True,
            )

        # Route AST operators through the IR builders so scalar promotion and
        # validation apply before constant folding as well as to runtime expressions.
        op_map = {
            ast.Add: "add",
            ast.Sub: "sub",
            ast.Mult: "mul",
            ast.Div: "truediv",
            ast.FloorDiv: "floordiv",
            ast.Mod: "mod",
            ast.BitAnd: "bit_and",
            ast.BitOr: "bit_or",
            ast.BitXor: "bit_xor",
            ast.LShift: "bit_shift_left",
            ast.RShift: "bit_shift_right",
        }

        op_type = type(binop.op)
        if op_type not in op_map:
            raise NotSupported(
                f"Unsupported binary operator: {op_type.__name__}",
                span=self.span_tracker.get_span(binop),
                hint="Use supported operators: +, -, *, /, //, %, &, |, ^, <<, >>",
                parser_retry=True,
            )

        op_name = op_map[op_type]
        operation = _make_binary(op_name, left, right, span)
        folded = self._fold_const_binop(op_name, operation, span)
        return folded if folded is not None else operation

    def parse_compare(self, compare: ast.Compare) -> ir.Expr:
        """Parse comparison operation.

        Args:
            compare: Compare AST node

        Returns:
            IR comparison expression
        """
        if len(compare.ops) != 1 or len(compare.comparators) != 1:
            raise NotSupported(
                "Only simple comparisons supported",
                span=self.span_tracker.get_span(compare),
                hint="Use single comparison operators like: a < b, not chained comparisons",
            )

        span = self.span_tracker.get_span(compare)
        op_type = type(compare.ops[0])

        # Dispatch `in` / `not in` to the desugar path: they are not scalar
        # binary comparisons, so they cannot enter the op_map below.
        if op_type in (ast.In, ast.NotIn):
            return self._parse_in_operator(compare, span)

        # ── Handle 'is None' / 'is not None' for null checks ──
        # Lowers to cast(ptr, UINT64) == 0 / != 0. pl.Ptr checks the pointer;
        # a tensor checks its GM data pointer, the flattened form of the
        # cpp ``Tensor* != nullptr && GetData() != nullptr`` guard.
        if op_type in (ast.Is, ast.IsNot):
            comparator = compare.comparators[0]
            if isinstance(comparator, ast.Constant) and comparator.value is None:
                # Left side must be a simple variable name (typically a pl.Ptr or pl.Tensor parameter)
                if not isinstance(compare.left, ast.Name):
                    raise InvalidVal(
                        "'is None' only supported on simple variable names",
                        span=span,
                        hint="Use 'param_name is None' for null checks on pl.Ptr parameters",
                    )
                # Parse the left operand. A compile-time value (for example an
                # inline helper that returned None) folds directly; there is no
                # pointer to test at run time.
                left = self.parse_expression(compare.left)
                is_none = op_type is ast.Is
                if not isinstance(left, ir.Expr):
                    return ir.ConstBool((left is None) if is_none else (left is not None), span)
                # Runtime null check, shared by aicore and aicpu kernels.
                # pl.Ptr tests the pointer itself; a tensor tests its GM data
                # pointer, the flattened form of the cpp
                # ``Tensor* != nullptr && GetData() != nullptr`` guard.
                if isinstance(left.type, ir.PtrType):
                    ptr = left
                elif isinstance(left.type, ir.TensorType):
                    ptr = self._tensor_data_ptr(left)
                    if ptr is None:
                        raise InvalidVal(
                            "tensor has no pointer view to null-check",
                            span=span,
                            parser_retry=True,
                        )
                else:
                    raise InvalidVal(
                        "'is None' / 'is not None' is only supported on pl.Ptr and pl.Tensor parameters",
                        span=span,
                        hint="pl.Ptr[dtype] and pl.Tensor[...] parameters (with a "
                        "None default when optional) both support null checks",
                        parser_retry=True,
                    )
                ptr_as_int = ir.cast(ptr, ir.DataType.UINT64, span)
                zero = ir.ConstInt(0, ir.DataType.UINT64, span)
                return _make_binary("eq" if is_none else "ne", ptr_as_int, zero, span)
            else:
                raise InvalidVal(
                    "'is' / 'is not' only supported with None",
                    span=span,
                    hint="Use '==' for value comparison, or 'param is None' for pointer null checks",
                    parser_retry=True,
                )

        # ── Standard comparison operators (==, !=, <, <=, >, >=) ──
        left = self.parse_expression(compare.left)
        right = self.parse_expression(compare.comparators[0])

        # Compile-time enum comparison (e.g. dtype generalization: ``x_dtype ==
        # pl.DT_FP16``). Enum operands (DataType / pybind enum) are Python objects,
        # not ir.Expr, so they cannot go through make_binary/ir.eq; fold ``==`` /
        # ``!=`` here into a ConstBool. Only equality is meaningful for enums.
        if _is_enum_value(left) and _is_enum_value(right):
            if op_type is ast.Eq:
                return ir.ConstBool(left == right, span)
            if op_type is ast.NotEq:
                return ir.ConstBool(left != right, span)
            raise NotSupported(
                f"Unsupported comparison {op_type.__name__} between enum values",
                span=span,
                hint="Only == and != are supported for enum comparisons",
                parser_retry=True,
            )

        # Non-IR values use parse_expression's compile-time Python fallback.
        if not isinstance(left, ir.Expr) or not isinstance(right, ir.Expr):
            raise NotSupported(
                "Comparison of Python values requires compile-time evaluation",
                span=span, parser_retry=True,
            )

        # Comparisons also promote mixed int/float operands to float via make_binary.
        op_map = {
            ast.Eq: "eq",
            ast.NotEq: "ne",
            ast.Lt: "lt",
            ast.LtE: "le",
            ast.Gt: "gt",
            ast.GtE: "ge",
        }

        if op_type not in op_map:
            raise NotSupported(
                f"Unsupported comparison: {op_type.__name__}",
                span=span,
                hint="Use supported comparisons: ==, !=, <, <=, >, >=",
                parser_retry=True,
            )

        op_name = op_map[op_type]
        operation = _make_binary(op_name, left, right, span)
        folded = self._fold_const_binop(op_name, operation, span)
        return folded if folded is not None else operation

    def parse_unaryop(self, unary: ast.UnaryOp) -> ir.Expr:
        """Parse unary operation.

        Args:
            unary: UnaryOp AST node

        Returns:
            IR unary expression
        """
        span = self.span_tracker.get_span(unary)
        operand = self.parse_expression(unary.operand)

        op_map = {
            ast.USub: ("neg", ir.neg),
            ast.Not: ("not", ir.not_),
            ast.Invert: ("invert", ir.bit_not),
            ast.UAdd: ("pos", lambda value, _span: value),
        }
        op_type = type(unary.op)
        if op_type not in op_map:
            raise NotSupported(
                f"Unsupported unary operator: {op_type.__name__}",
                span=self.span_tracker.get_span(unary),
                hint="Use supported unary operators: +, -, not, ~",
                parser_retry=True,
            )

        op_name, make_operation = op_map[op_type]
        operation = make_operation(operand, span)
        folded = self._fold_const_unaryop(op_name, operation, span)
        return folded if folded is not None else operation

    def parse_boolop(self, expr: ast.BoolOp) -> ir.Expr:
        span = self.span_tracker.get_span(expr)
        bool_dtype = DataType.BOOL
        if isinstance(expr.op, ast.And):
            fold_fn = ir.And
        elif isinstance(expr.op, ast.Or):
            fold_fn = ir.Or
        else:
            raise InvalidType(
                f"Unsupported boolean operator: {type(expr.op).__name__}",
                span=span,
                parser_retry=True,
            )

        result = self.parse_expression(expr.values[0])
        for value_node in expr.values[1:]:
            result_truth = self._const_truth(result)
            if isinstance(expr.op, ast.And) and result_truth is False:
                return ir.ConstBool(False, span)
            if isinstance(expr.op, ast.Or) and result_truth is True:
                return ir.ConstBool(True, span)
            operand = self.parse_expression(value_node)
            operand_truth = self._const_truth(operand)
            if result_truth is not None and operand_truth is not None:
                value = (
                    result_truth and operand_truth
                    if isinstance(expr.op, ast.And)
                    else result_truth or operand_truth
                )
                result = ir.ConstBool(value, span)
            else:
                result = fold_fn(result, operand, bool_dtype, span)
        return result

    def _reject_ternary_branch(self, value: Any, node: ast.expr, branch: str, test_node: "ast.expr | None"):
        """The one diagnostic for a ternary branch that has no value to select.

        ``test_node`` is the condition when the ternary became a runtime select, and
        None when it const-folded. The distinction is the whole message: a
        compile-time enum is a legal branch once the condition folds (parse_ifexp
        returns it directly), so it is the condition — not the branch — that makes
        the same source text illegal here, and the diagnostic has to say so.
        """
        written = ast.unparse(node)
        if test_node is not None and _is_enum_value(value):
            raise InvalidOperation(
                f"'{written}' has no runtime value, so a runtime condition cannot select it",
                span=self.span_tracker.get_span(node),
                hint=f"'{ast.unparse(test_node)}' is a runtime value, which makes this ternary a "
                "runtime select rather than a compile-time choice. Give it a compile-time "
                "condition — a Python constant, or a tiling_key field, which "
                "@pl.jit(tiling_key=...) bakes to one constant per specialization — or write a "
                "branch that has a runtime value.",
                parser_retry=True,
            )
        raise InvalidVal(
            f"the {branch} branch of this ternary has no value to select, got '{written}'",
            span=self.span_tracker.get_span(node),
            hint="Each branch must be a scalar, tile or tensor expression. A call that performs "
            "an action rather than producing a value (pl.load(...), pl.store(...)) and a type "
            "descriptor (pl.TileType(...)) have nothing to select.",
            parser_retry=True,
        )

    def parse_ifexp(self, expr: ast.IfExp) -> ir.Expr:
        condition = self.parse_expression(expr.test)

        if isinstance(condition, (ir.ConstBool, ir.ConstInt)):
            is_true = condition.value if isinstance(condition, ir.ConstBool) else condition.value != 0
            chosen = expr.body if is_true else expr.orelse
            result = self.parse_expression(chosen, nested=False)
            _check_expression_value(result, self.span_tracker.get_span(chosen), nested=True)
            if _is_enum_value(result):
                return result
            if not isinstance(result, ir.Expr):
                self._reject_ternary_branch(result, chosen, "chosen", None)
            return result

        for branch, branch_name in ((expr.body, "then"), (expr.orelse, "else")):
            success, branch_value = self.expr_evaluator.try_eval_expr(branch)
            if success and _is_enum_value(branch_value):
                self._reject_ternary_branch(branch_value, branch, branch_name, expr.test)

        tmp_name = f"_ifexpr_tmp_{self._ifexpr_tmp_counter}"
        self._ifexpr_tmp_counter += 1
        then_assign = ast.copy_location(
            ast.Assign(targets=[ast.Name(id=tmp_name, ctx=ast.Store())], value=expr.body),
            expr.body,
        )
        else_assign = ast.copy_location(
            ast.Assign(targets=[ast.Name(id=tmp_name, ctx=ast.Store())], value=expr.orelse),
            expr.orelse,
        )
        lowered_if = ast.copy_location(
            ast.If(test=expr.test, body=[then_assign], orelse=[else_assign]),
            expr,
        )
        ast.fix_missing_locations(lowered_if)
        self.parse_if_statement(lowered_if)
        # The synthetic branch assignments parse their RHS with nested=False,
        # but a conditional expression still requires a value from each branch.
        for branch in (expr.body, expr.orelse):
            _check_expression_value(self._parsed_expr_cache[branch], self.span_tracker.get_span(branch), nested=True)
        result = self.lookup_expr_by_name(tmp_name)
        if not isinstance(result, ir.Expr):
            branch = expr.body if result is None else expr.orelse
            self._reject_ternary_branch(result, branch, "runtime", expr.test)
        return result

    def make_named_tuple(
        self,
        elements: list,
        field_names,
        span: ir.Span,
        *,
        name: str | None = None,
    ) -> ir.Expr:
        """Build a named ``MakeTuple`` and register its semantic tuple metadata."""
        field_names = tuple(field_names)
        mt = ir.MakeTuple(elements, span)
        self.tuple_type_registry.register_named_tuple(mt.type, field_names, name=name)
        return mt

    def classify_tuple_type(self, tuple_type: ir.TupleType) -> TupleTypeInfo:
        """Classify a tuple type by its parser-session kind, name, and fields."""
        return self.tuple_type_registry.classify(tuple_type)

    def named_fields(self, expr) -> list[str]:
        """Return parser-registered field names for a named tuple or struct expression."""
        if not (isinstance(expr, ir.Expr) and isinstance(expr.type, ir.TupleType)):
            return []
        return list(self.classify_tuple_type(expr.type).fields)

    def register_struct_type(self, expr: ir.Expr, struct_name: str, field_names) -> ir.Expr:
        """Register a struct's semantic tuple metadata in IRDebugInfo."""
        expr_type = expr.type
        if not isinstance(expr_type, ir.TupleType):
            raise InvalidVal(f"Struct '{struct_name}' must have TupleType")
        self.tuple_type_registry.register_struct(expr_type, struct_name, field_names)
        return expr

    def lower_attr_access(self, base: ir.Expr, field_name: str, span: ir.Span):
        """Lower attribute read ``base.field`` to its named tuple element.

        Resolves the field index from the parser's tuple type registry. When *base* is a parse-time
        constant ``MakeTuple`` (never for struct_array, whose elements are
        mutable structs with backing-array alias semantics), constant-folds the
        read to the static element instead of emitting a ``GetItemExpr``.
        Returns None if ``base`` is not a named tuple or has no such field
        (caller keeps its own error handling).
        """
        fields = self.named_fields(base)
        if not fields or field_name not in fields:
            return None
        idx = fields.index(field_name)
        if isinstance(base, ir.MakeTuple) and not self._is_struct_array_tuple(base):
            return base.elements[idx]
        return ir.GetItemExpr(base, ir.ConstInt(idx, DataType.INT64, span), span)

    def parse_attribute(self, attr: ast.Attribute) -> ir.Expr:
        """Parse attribute access.

        Args:
            attr: Attribute AST node

        Returns:
            IR expression
        """
        span = self.span_tracker.get_span(attr)

        # Generic pybind enum constant (pl.MemorySpace.Vec, pl.RoundMode.CAST_FLOOR,
        # pl.DT_FP16, pl.QuantMode.SYM, pl.STPhase.Partial, ...): evaluate the
        # attribute and, if it is an enum value, return the enum object. kwarg
        # consumers use it directly / the C++ boundary extracts .value as int.
        # Generic pybind enums (MemorySpace, RoundMode, ...) expose .value and a
        # class-level __members__; DataType is a py::class_ without __members__, so
        # match it by type. NOTE: enum objects are not IR Exprs, so they cannot be
        # used as positional op args or list elements (only as kwargs).
        success, val = self.expr_evaluator.try_eval_expr(attr)
        if success and _is_enum_value(val):
            return val

        # Attribute access on a parsed base (e.g. arr[0].field, arr[i].field, or
        # x.shape on a Tensor): Tensor.shape yields its shape MakeTuple; any other
        # base lowers through the named-field lookup.
        base_expr = self.parse_expression(attr.value)
        if attr.attr == "shape" and isinstance(base_expr, ir.Expr) and isinstance(base_expr.type, ir.TensorType):
            return ir.MakeTuple(list(base_expr.type.shape), span)
        if attr.attr == "stride" and isinstance(base_expr, ir.Expr) and isinstance(base_expr.type, ir.TensorType):
            # Every axis, read the way tensor.stride[axis] reads one.
            return ir.MakeTuple(
                [self._tensor_stride_axis(base_expr, axis, span) for axis in range(len(base_expr.type.shape))],
                span,
            )
        if isinstance(base_expr, ir.Expr):
            lowered = self.lower_attr_access(base_expr, attr.attr, span)
            if lowered is not None:
                return lowered

        raise InvalidShape(
            f"Standalone attribute access not supported: {ast.unparse(attr)}",
            span=span,
            hint="Attribute access is supported on named tuples, structs, Tensor values "
            "(tensor.shape, tensor.stride, and either indexed), tiling parameters, or enum constants",
            parser_retry=True,
        )

    def parse_list(self, list_node: ast.List) -> ir.MakeTuple:
        """Parse list literal into MakeTuple IR expression.


        Args:
            list_node: List AST node

        Returns:
            MakeTuple IR expression
        """
        span = self.span_tracker.get_span(list_node)
        elements = [self.parse_expression(elt) for elt in list_node.elts]
        return _to_make_tuple(elements, span)

    def parse_tuple_literal(self, tuple_node: ast.Tuple) -> ir.MakeTuple:
        """Parse tuple literal like (x, y, z).

        Args:
            tuple_node: Tuple AST node

        Returns:
            MakeTuple IR expression
        """
        span = self.span_tracker.get_span(tuple_node)
        elements = [self.parse_expression(elt) for elt in tuple_node.elts]
        result = _to_make_tuple(elements, span)
        self._transfer_tile_group_metadata(result, *elements)
        return result

    def parse_subscript(self, subscript: ast.Subscript) -> ir.Expr:
        span = self.span_tracker.get_span(subscript)

        if isinstance(subscript.value, ast.Attribute) and subscript.value.attr == "valid_shape":
            base_expr = self.parse_expression(subscript.value.value)
            if isinstance(base_expr, ir.Expr) and isinstance(base_expr.type, ir.TileType):
                return self._parse_tile_valid_shape_subscript(base_expr, subscript.slice, span)

        if isinstance(subscript.value, ast.Attribute) and subscript.value.attr == "shape":
            base_expr = self.parse_expression(subscript.value.value)
            if isinstance(base_expr, ir.Expr) and isinstance(base_expr.type, ir.TensorType):
                return self._parse_tensor_shape_subscript(base_expr, subscript.slice, span)

        if isinstance(subscript.value, ast.Attribute) and subscript.value.attr == "stride":
            base_expr = self.parse_expression(subscript.value.value)
            if isinstance(base_expr, ir.Expr) and isinstance(base_expr.type, ir.TensorType):
                return self._parse_tensor_stride_subscript(base_expr, subscript.slice, span)

        value_expr = self.parse_expression(subscript.value)

        # A tile-group handle is a named tuple, so this must precede the TupleType
        # dispatch below: g[0] means "slot 0 of the group", not "field 0 of the handle".
        if self.is_tile_group(value_expr):
            return self.lower_group_subscript(value_expr, subscript.slice, span)

        value_type = value_expr.type

        # Tile/Tensor subscript: dispatch by index type
        #   - Integer index (no ':') → getval (scalar access, Tile and Tensor)
        #   - Slice index (has ':')  → sub-view (block.subview, Tile only)
        if isinstance(value_type, (ir.TensorType, ir.TileType)):
            has_slice = isinstance(subscript.slice, ast.Slice) or (
                isinstance(subscript.slice, ast.Tuple)
                and any(isinstance(e, ast.Slice) for e in subscript.slice.elts)
            )
            if has_slice:
                return self._parse_slice_subscript(value_expr, subscript.slice, span)
            # Retain logical coordinates until backend address lowering.
            index_expr = self._parse_scalar_subscript_index(value_expr, subscript.slice, span)
            from pypto_pro.ir.op.block_ops import _ir_getval
            is_simt = _is_simt_func_type(self._current_func_type)
            result = _ir_getval(value_expr, index_expr, preserve_dtype=is_simt, span=span)
            self._record_op_access("getval", [(0, None, value_expr)], (), span)
            result = self._materialize_nested_expr(result, span)
            return result

        if isinstance(value_type, ir.ArrayType):
            index_expr = self._parse_array_index(value_type, subscript.slice, span)
            return ir.create_op_call("array.load", [value_expr, index_expr], {}, span)

        if not isinstance(value_type, ir.TupleType):
            raise InvalidType(
                f"Subscript requires tuple, tile, or tensor type, got {type(value_type).__name__}",
                span=span,
                hint="Subscript access is supported on Tuple, Tile, and Tensor types",
                parser_retry=True,
            )

        # TupleType subscript: tuple[i] element access
        if isinstance(subscript.slice, ast.Constant):
            if not isinstance(subscript.slice.value, int):
                raise InvalidType(
                    "Tuple index must be an integer",
                    span=span,
                    hint="Use integer index like tuple[0]",
                )
        else:
            if isinstance(subscript.slice, ast.Tuple):
                raise InvalidShape(
                    "Multi-dimensional subscript is not supported for tuples",
                    span=span,
                    hint="Use a scalar index like tuple[0]",
                )
            self._check_uniform_tuple_types(value_type, span)

        index_expr = self.parse_expression(subscript.slice)
        if (
            isinstance(value_expr, ir.MakeTuple)
            and not self._is_struct_array_tuple(value_expr)
            and isinstance(index_expr, ir.ConstInt)
        ):
            index = index_expr.value
            if 0 <= index < len(value_expr.elements):
                return value_expr.elements[index]

        # CCE resolves a non-folded GetItem through the underlying MakeTuple's
        # backing array. struct_array stays as a Var here because it is not a
        # parser constant; ordinary tuples may remain folded MakeTuple values.
        item_expr = ir.GetItemExpr(value_expr, index_expr, span)
        # A subscript aliases the base's buffer, so the item inherits the base's
        # buffer origin.
        self._transfer_tile_group_metadata(item_expr, value_expr)
        return item_expr

    def _is_struct_array_tuple(self, tuple_value: ir.MakeTuple) -> bool:
        return tuple_value in self._struct_array_tuples

    def _update_var_envs(self, target: Any, value: Any) -> None:
        """Record parser-known values under the destination's physical SSA name."""
        if not isinstance(target, ir.Var):
            return
        if _is_const_expr(value):
            self.const_env[target.name] = value
        if isinstance(value, ir.MakeTuple) and not self._is_struct_array_tuple(value):
            self.make_tuple_env[target.name] = value

    def _fold_const_binop(self, op_name: str, operation: ir.BinaryExpr, span: ir.Span) -> ir.Expr | None:
        """Fold a validated binary scalar operation using its promoted operands."""
        left_value = self._const_scalar_value(operation.left)
        right_value = self._const_scalar_value(operation.right)
        if op_name in ("truediv", "floordiv", "mod", "ceildiv") and right_value == 0:
            operator = {"truediv": "/", "floordiv": "//", "mod": "%", "ceildiv": "ceildiv"}[op_name]
            raise InvalidVal(
                f"Operator '{operator}' does not allow a zero divisor",
                span=span,
                hint="Use a nonzero divisor",
            )
        if left_value is None or right_value is None:
            return None
        dtype = operation.type.dtype
        binary_ops = {
            "add": lambda: left_value + right_value,
            "sub": lambda: left_value - right_value,
            "mul": lambda: left_value * right_value,
            "truediv": lambda: left_value / right_value,
            "floordiv": lambda: left_value // right_value,
            "mod": lambda: left_value % right_value,
            "bit_and": lambda: left_value & right_value,
            "bit_or": lambda: left_value | right_value,
            "bit_xor": lambda: left_value ^ right_value,
            "bit_shift_left": lambda: left_value << right_value,
            "bit_shift_right": lambda: left_value >> right_value,
            "min": lambda: min(left_value, right_value),
            "max": lambda: max(left_value, right_value),
            "ceildiv": lambda: -((-left_value) // right_value),
        }
        if op_name in binary_ops:
            try:
                value = binary_ops[op_name]()
            except (ArithmeticError, ValueError):
                return None
            return self._make_scalar_constant(value, dtype, span)
        comparisons = {
            "eq": lambda: left_value == right_value,
            "ne": lambda: left_value != right_value,
            "lt": lambda: left_value < right_value,
            "le": lambda: left_value <= right_value,
            "gt": lambda: left_value > right_value,
            "ge": lambda: left_value >= right_value,
        }
        if op_name in comparisons:
            return ir.ConstBool(comparisons[op_name](), span)
        raise NotSupported(f"Unsupported constant-folding binary operator: {op_name}")

    def _fold_const_unaryop(self, op_name: str, operation: ir.Expr, span: ir.Span) -> ir.Expr | None:
        """Fold a validated unary scalar operation using its operand and result dtype."""
        operand = operation.operand if isinstance(operation, ir.UnaryExpr) else operation
        value = self._const_scalar_value(operand)
        if value is None:
            return None
        unary_ops = {
            "neg": lambda: -value,
            "not": lambda: not value,
            "invert": lambda: ~value,
            "pos": lambda: value,
            "abs": lambda: abs(value),
            "ceil": lambda: math.ceil(value),
            "floor": lambda: math.floor(value),
        }
        return self._make_scalar_constant(unary_ops[op_name](), operation.type.dtype, span)

    def _desugar_in_literal(self, left, elements, is_not_in, span):
        """Desugar x in (a,b,c) -> Or-chain of eq; x not in -> And-chain of ne."""
        folded = self._try_const_fold_in(left, elements, is_not_in, span)
        if folded is not None:
            return folded
        if not elements:
            return ir.ConstBool(is_not_in, span)
        cmp_name = "ne" if is_not_in else "eq"
        fold_fn = ir.And if is_not_in else ir.Or

        result = _make_binary(cmp_name, left, elements[0], span)
        for elt in elements[1:]:
            result = fold_fn(result, _make_binary(cmp_name, left, elt, span), DataType.BOOL, span)
        return result

    def _desugar_in_range(self, left, range_call, is_not_in, span):
        """Desugar x in pl.range(start, stop, step).

        step == 1:  x >= start and x < stop
        step != 1:  x >= start and x < stop and (x - start) % step == 0
        """
        args = self._parse_range_call(range_call)
        start = _normalize_expr(args["start"], span)
        stop = _normalize_expr(args["stop"], span)
        step = _normalize_expr(args["step"], span)
        ge_start = _make_binary("ge", left, start, span)
        lt_stop = _make_binary("lt", left, stop, span)
        result = ir.And(ge_start, lt_stop, DataType.BOOL, span)
        step_is_one = (
            isinstance(step, ir.ConstInt) and step.value == 1 or isinstance(step, ir.ConstFloat) and step.value == 1.0
        )
        if not step_is_one:
            diff = _make_binary("sub", left, start, span)
            mod_val = _make_binary("mod", diff, step, span)
            zero = ir.ConstInt(0, DataType.INT64, span)
            result = ir.And(result, _make_binary("eq", mod_val, zero, span), DataType.BOOL, span)
        return ir.not_(result, span) if is_not_in else result

    def _parse_in_operator(self, compare: ast.Compare, span: ir.Span) -> ir.Expr:
        """Parse ``x in (...)`` / ``x not in (...)``.

        Supports three container forms, all desugared to existing IR ops:
          1. Literal tuple/list:  x in (a, b, c)      -> or-chain of eq
          2. pl.range() call:     x in pl.range(s,e,k) -> range bounds + modulo check
          3. Closure variable:    x in my_list          -> eval at compile time, expand to eq-chain
        """
        is_not_in = isinstance(compare.ops[0], ast.NotIn)
        left = self.parse_expression(compare.left)
        container = compare.comparators[0]

        if isinstance(container, ast.Call) and self._is_pl_range_call(container):
            return self._desugar_in_range(left, container, is_not_in, span)

        # A literal, a kernel-local list and a closure list all parse to a MakeTuple.
        parsed = self.parse_expression(container)
        if isinstance(parsed, ir.MakeTuple):
            return self._desugar_in_literal(left, list(parsed.elements), is_not_in, span)

        raise NotSupported(
            f"'{'not in' if is_not_in else 'in'}' only supports tuple/list literals, "
            f"pl.range(), or compile-time list/tuple variables, "
            f"got {ast.unparse(container)}",
            span=span,
            hint="Use: x in (a, b, c), x in pl.range(10), or x in <compile-time-list>",
        )

    def _parse_tensor_shape_subscript(
        self,
        base_expr: ir.Expr,
        index_node: ast.expr,
        span: ir.Span,
    ) -> ir.Expr:
        """Resolve ``tensor.shape[index]`` to the dimension stored in its TensorType.

        TensorType shape expressions are the logical tensor dimensions and are the
        source of truth for both static dimensions and dynamic shape ABI variables.
        No runtime tensor operation is emitted.
        """
        if not isinstance(base_expr.type, ir.TensorType):
            raise InvalidType(
                "tensor.shape requires TensorType input",
                span=span,
                hint="Use tensor.shape[index] only on Tensor values",
                parser_retry=True,
            )

        success, axis = self.expr_evaluator.try_eval_expr(index_node)
        if not success or type(axis) is not int:
            raise InvalidType(
                "tensor.shape index must be a compile-time integer",
                span=span,
                hint="Use tensor.shape[0], tensor.shape[-1], or a compile-time integer expression",
            )

        original_axis = axis
        tensor_type = base_expr.type
        rank = len(tensor_type.shape)
        if axis < 0:
            axis += rank
        if axis < 0 or axis >= rank:
            raise InvalidShape(
                f"shape index {original_axis} out of range for tensor of rank {rank}",
                span=span,
                parser_retry=True,
            )
        return tensor_type.shape[axis]

    def _parse_tensor_stride_subscript(
        self,
        base_expr: ir.Expr,
        index_node: ast.expr,
        span: ir.Span,
    ) -> ir.Expr:
        """Resolve ``tensor.stride[index]`` to the step of that axis."""
        success, axis = self.expr_evaluator.try_eval_expr(index_node)
        if not success or type(axis) is not int:
            raise InvalidType(
                "tensor.stride index must be a compile-time integer",
                span=span,
                hint="Use tensor.stride[0], tensor.stride[-1], or a compile-time integer expression",
            )

        original_axis = axis
        rank = len(base_expr.type.shape)
        if axis < 0:
            axis += rank
        if axis < 0 or axis >= rank:
            raise InvalidShape(
                f"stride index {original_axis} out of range for tensor of rank {rank}",
                span=span,
                parser_retry=True,
            )
        return self._tensor_stride_axis(base_expr, axis, span)

    def _tensor_stride_axis(self, base_expr: ir.Expr, axis: int, span: ir.Span) -> ir.Expr:
        """The step of one axis of a tensor, for an ``axis`` already within its rank.

        A view created with a stride reads it back. Without one, an ND/NCHW/NCDHW
        tensor is laid out contiguously in row-major order, so the step is the
        product of the inner axes' extents. No runtime tensor operation is emitted.
        """
        shape = list(base_expr.type.shape)
        tensor_view = base_expr.type.tensor_view
        if tensor_view is not None and tensor_view.stride:
            return tensor_view.stride[axis]
        if tensor_view is not None and tensor_view.layout not in (
            ir.Layout.ND,
            ir.Layout.NCHW,
            ir.Layout.NCDHW,
        ):
            raise InvalidType(
                f"tensor.stride of a {tensor_view.layout} tensor requires an explicit stride",
                span=span,
                hint="Only ND/NCHW/NCDHW tensors have an implicit row-major stride; create the view with "
                "pl.make_tensor(ptr, shape, stride).",
            )
        if axis == len(shape) - 1:
            return ir.ConstInt(1, DataType.INT64, span)
        step = shape[axis + 1]
        for extent in shape[axis + 2:]:
            operation = _make_binary("mul", step, extent, span)
            folded = self._fold_const_binop("mul", operation, span)
            step = folded if folded is not None else operation
        return step

    def _parse_tile_valid_shape_subscript(
        self,
        base_expr: ir.Expr,
        index_node: ast.expr,
        span: ir.Span,
    ) -> ir.Expr:
        """Parse a runtime ``tile.valid_shape[axis]`` query."""
        success, axis = self.expr_evaluator.try_eval_expr(index_node)
        if not success or type(axis) is not int:
            raise InvalidType(
                "tile.valid_shape index must be a compile-time integer",
                span=span,
                hint="Use tile.valid_shape[0] or tile.valid_shape[1].",
            )

        rank = len(base_expr.type.shape)
        original_axis = axis
        if axis < 0:
            axis += rank
        if axis < 0 or axis >= rank:
            raise InvalidShape(
                f"valid_shape index {original_axis} out of range for Tile rank {rank}",
                span=span,
                parser_retry=True,
            )

        return ir.create_op_call("block.tile_valid_shape", [base_expr], {"axis": axis}, span)

    @staticmethod
    def _validate_subscript_value(
        value: ir.Expr,
        kind: str,
        axis: int,
        upper_bound: ir.Expr | None = None,
    ) -> int | None:
        """Validate an index or slice bound and return its static value when available."""
        value_type = getattr(value, "type", None)
        if not (isinstance(value_type, ir.ScalarType) and value_type.dtype.is_int()):
            raise InvalidType(
                f"{kind} for axis {axis} must be an integer scalar, got {value_type}",
                parser_retry=True,
            )

        value_int = _const_int_value(value)
        if value_int is not None and value_int < 0:
            raise InvalidVal(
                f"{kind} for axis {axis} must be non-negative, got {value_int}",
                hint="Use an index greater than or equal to 0; Tile and Tensor subscripts do not "
                "support Python-style negative indexing",
            )

        upper_value = _const_int_value(upper_bound) if upper_bound is not None else None
        if value_int is not None and upper_value is not None and value_int >= upper_value:
            raise OutOfRange(
                f"{kind} {value_int} for axis {axis} is out of range for dimension size {upper_value}",
                hint=f"Use an index in [0, {upper_value})",
                parser_retry=True,
            )
        return value_int

    def _parse_array_index(self, array_type: ir.ArrayType, index_node: ast.expr, span: ir.Span) -> ir.Expr:
        """Validate a single integer index into a fixed-length array."""
        if isinstance(index_node, ast.Tuple):
            raise InvalidShape(
                "Multi-dimensional subscript is not supported for arrays",
                span=span,
                hint="Use a scalar index like datas[0]",
                parser_retry=True,
            )
        index = self.parse_expression(index_node)
        index_type = getattr(index, "type", None)
        if not (isinstance(index_type, ir.ScalarType) and index_type.dtype.is_int()):
            raise InvalidType(
                f"Array index must be an integer scalar, got {index_type}",
                span=span,
                hint="Use an integer index like datas[0] or datas[i]",
                parser_retry=True,
            )
        value = _const_int_value(index)
        if value is not None and not 0 <= value < array_type.length:
            raise OutOfRange(
                f"Array index {value} out of bounds for {array_type.length} elements",
                span=span,
                hint=f"Use an index in [0, {array_type.length})",
                parser_retry=True,
            )
        return index

    def _parse_scalar_subscript_index(
        self,
        container_expr: ir.Expr,
        index_node: ast.expr,
        span: ir.Span,
    ) -> ir.Expr:
        """Validate scalar coordinates and preserve their axes until codegen."""
        container_type = container_expr.type
        shape = container_type.shape

        # Single index A[x]: only valid for 1D containers (rank 1)
        if not isinstance(index_node, ast.Tuple):
            if len(shape) != 1:
                if self._in_simd_vf_body():
                    raise NotSupported(
                        "Tile[x] in VF section is not supported; use `tile + x` for pointer offset",
                        span=span,
                        hint="Replace `tile[x]` with `tile + x`",
                    )
                raise InvalidShape(
                    f"Subscript A[x] requires 1D container, but got rank {len(shape)}; "
                    f"use {len(shape)} indices or add ':' for sub-view (Tile)",
                    span=span,
                    hint="Use A[i, j] for scalar access or A[x:, :] for sub-view",
                )
            index = self.parse_expression(index_node)
            self._validate_subscript_value(index, "Subscript index", 0, shape[0])
            return ir.MakeTuple([index], span)

        # A[i, j, ...] — multi-dimensional coordinate
        elts = index_node.elts

        if len(elts) != len(shape):
            raise InvalidShape(
                f"Subscript has {len(elts)} indices but container has rank {len(shape)}",
                span=span,
                hint=f"Use {len(shape)} indices to match the container shape",
                parser_retry=True,
            )
        indices = [self.parse_expression(e) for e in elts]

        for axis, index in enumerate(indices):
            self._validate_subscript_value(index, "Subscript index", axis, shape[axis])

        return ir.MakeTuple(indices, span)

    def _parse_slice_subscript(
        self,
        container_expr: ir.Expr,
        slice_node: ast.expr,
        span: ir.Span,
    ) -> ir.Expr:
        """Parse tile[r:, c:] into a block.subview op (Tile only, 2D).

        Result tile preserves the original shape (row_stride unchanged);
        codegen auto-emits SetValidShape with the sub-window dimensions.
        - If slice start exceeds tile shape → error; an empty window at the boundary is allowed.
        - If an explicit static slice end exceeds tile shape or declared valid_shape → error.
        - An omitted end reads the current valid_shape when it is not statically declared.
        """
        from pypto_pro.ir.op.block_ops import _tile_layout, block_ir_op

        container_type = container_expr.type
        physical_shape_exprs = container_type.shape

        if isinstance(container_type, ir.TensorType):
            raise NotSupported(
                "Tensor slice sub-view is not supported",
                span=span,
                hint="Use pl.load/pl.store with offset lists for tensor access",
            )

        if _is_simt_func_type(self._current_func_type):
            raise InvalidOperation(
                "Tile subview is not supported inside a SIMT function",
                span=span,
                hint="Access the Tile directly with tile[row, col].",
                parser_retry=True,
            )

        # VF section: tile slice 'tile[a:b, c:d]' is not supported.
        # Use load_align(tile, [row, col]) / store_align(tile, ..., [row, col]) instead.
        if self._in_simd_vf_body():
            raise NotSupported(
                "Tile slice 'tile[a:b, c:d]' is not supported in VF section; "
                "use load_align(tile, [row, col]) or store_align(tile, reg, mask, [row, col]) instead",
                span=span,
                hint="Replace `tile[a:a+1, b:b+1]` with `tile, [a, b]` in load_align/store_align",
            )

        memref = container_type.memref
        mem_space = memref.memory_space if memref is not None else None
        hw_info = container_type.hardware_info
        layout = _tile_layout(container_type)
        allowed_layouts = {
            ir.MemorySpace.Vec: {ir.Layout.ND, ir.Layout.DN, ir.Layout.NZ},
            ir.MemorySpace.Mat: {
                ir.Layout.ND,
                ir.Layout.DN,
                ir.Layout.NZ,
                ir.Layout.ZN,
            },
            ir.MemorySpace.Acc: {ir.Layout.NZ},
        }
        if layout not in allowed_layouts.get(mem_space, set()):
            raise InvalidFormat(
                "Tile slice supports Vec ND/DN/NZ, Mat ND/DN/NZ/ZN, and Acc NZ tiles",
                span=span,
                hint="Use pl.load with offset or pl.move with offset for unsupported tiles",
            )

        if not isinstance(slice_node, ast.Tuple):
            raise NotSupported(
                "1D tile slice is not supported; use 2D slice like tile[i:i+h, j:j+w]",
                span=span,
                hint="Use tile[i:i+h, j:j+w] for sub-view access",
            )

        slices = slice_node.elts
        if len(slices) != len(physical_shape_exprs):
            raise InvalidShape(
                f"Slice subscript has {len(slices)} dimensions but tile has rank {len(physical_shape_exprs)}",
                span=span,
                hint=f"Use {len(physical_shape_exprs)} indices to match the tile shape",
                parser_retry=True,
            )

        valid_shape_exprs = getattr(getattr(container_type, "tile_view", None), "valid_shape", None)
        offset_exprs = []
        shape_exprs = []
        offset_vals = []
        physical_shape_vals = [_const_int_value(dim) for dim in physical_shape_exprs]

        for i, s in enumerate(slices):
            if not isinstance(s, ast.Slice):
                raise NotSupported(
                    f"Tile slice does not support integer index in dimension {i}",
                    span=span,
                    hint="Tile slices must use ':' for all dimensions",
                )
            # Build bound expressions, resolving an omitted end from declared or runtime valid_shape.
            step_expr = ir.ConstInt(1, DataType.INT64, span) if s.step is None else self.parse_expression(s.step)
            start_expr = ir.ConstInt(0, DataType.INT64, span) if s.lower is None else self.parse_expression(s.lower)
            vs_expr = valid_shape_exprs[i] if valid_shape_exprs is not None and i < len(valid_shape_exprs) else None
            vs_val = _const_int_value(vs_expr) if vs_expr is not None else None
            if s.upper is not None:
                upper_expr = self.parse_expression(s.upper)
            elif vs_val is not None and vs_val >= 0:
                upper_expr = vs_expr
            else:
                upper_expr = ir.create_op_call("block.tile_valid_shape", [container_expr], {"axis": i}, span)

            # Validate types and each bound whose value is statically known.
            start_val = self._validate_subscript_value(start_expr, "Tile slice start", i)
            upper_val = (
                self._validate_subscript_value(upper_expr, "Tile slice end", i) if s.upper is not None else None
            )
            shape_val = physical_shape_vals[i]
            if _const_int_value(step_expr) != 1:
                raise InvalidShape(
                    f"Tile slice step for axis {i} must be the compile-time integer 1",
                    span=span,
                    hint="Omit the step or use a contiguous slice with step 1",
                )
            for bound_name, bound_val in (("physical shape", shape_val), ("valid_shape", vs_val)):
                if bound_val is None or bound_val < 0:
                    continue
                if upper_val is not None and upper_val > bound_val:
                    raise InvalidShape(
                        f"Tile slice end ({upper_val}) exceeds {bound_name} dim {i} ({bound_val})",
                        span=span,
                    )
                if start_val is not None and start_val > bound_val:
                    raise InvalidShape(
                        f"Tile slice start ({start_val}) must not exceed {bound_name} dim {i} ({bound_val})",
                        span=span,
                        hint=f"Use a slice start in [0, {bound_name}[{i}]]",
                    )
            if start_val is not None and upper_val is not None and start_val > upper_val:
                raise InvalidShape(
                    f"Tile slice for axis {i} must satisfy start <= end, "
                    f"got start={start_val}, end={upper_val}",
                    span=span,
                    hint="Tile slices cannot be reversed",
                )
            dim_expr = upper_expr if start_val == 0 else upper_expr - start_expr
            offset_exprs.append(start_expr)
            offset_vals.append(start_val)
            shape_exprs.append(dim_expr)

        dtype_bits = int(container_type.dtype.get_bit())

        # Match pto::GetTileOffset: plain layouts use row/column strides,
        # while boxed layouts must start at an inner-fractal boundary.
        if layout in (ir.Layout.ND, ir.Layout.DN):
            static_vals = [*offset_vals, *physical_shape_vals]
            if None not in static_vals:
                row_start, col_start, rows, cols = static_vals
                if layout == ir.Layout.ND:
                    element_offset = row_start * cols + col_start
                else:
                    element_offset = col_start * rows + row_start
                if element_offset * dtype_bits % 256 != 0:
                    raise InvalidShape(
                        f"{mem_space.name} {layout.name} Tile slice start must produce a 32-byte-aligned "
                        f"Tile address, got [{row_start}, {col_start}]",
                        span=span,
                    )

        elif layout in (ir.Layout.NZ, ir.Layout.ZN):
            c0 = 256 // dtype_bits
            fractal = hw_info.fractal
            if fractal == 1024:
                inner_rows, inner_cols = 16, 16
            elif layout == ir.Layout.NZ:
                inner_rows, inner_cols = 16, c0
            else:
                inner_rows, inner_cols = c0, 16

            row_start, col_start = offset_vals
            row_unaligned = row_start is not None and row_start % inner_rows != 0
            col_unaligned = col_start is not None and col_start % inner_cols != 0
            if row_unaligned or col_unaligned:
                raise InvalidShape(
                    f"{mem_space.name} {layout.name} Tile slice start must align to "
                    f"[{inner_rows}, {inner_cols}], got [{row_start}, {col_start}]",
                    span=span,
                )

        # Pass [row_start, col_start] as a tuple; codegen computes the byte offset
        # according to the tile's layout (ND row-major, DN col-major, NZ fractal).
        shape_tuple = ir.MakeTuple(shape_exprs, span)
        offset_tuple = ir.MakeTuple(offset_exprs, span)
        view_expr = ir.create_op_call(
            block_ir_op("subview"),
            [container_expr, offset_tuple, shape_tuple],
            {},
            span,
        )
        self._transfer_auto_mutex_type(view_expr, container_expr)
        # A window onto a slot is that slot: an access to it is an access to its buffer.
        self._transfer_tile_group_metadata(view_expr, container_expr)

        return view_expr

    def _mark_make_tuple_anchor(self, result) -> None:
        """Record that a MakeTuple already has an emitted assignment anchor."""
        if isinstance(result, ir.MakeTuple):
            self._anchored_make_tuples.add(result)


    def _materialize_nested_expr(self, result, span: ir.Span):
        """Materialize nested expressions and anchor nested MakeTuples.

        Non-trivial expressions return a temporary Var so an enclosing expression
        does not duplicate their computation. Vars and constants are already
        atomic and remain inline. A MakeTuple instead keeps its expression result:
        the temporary let is only a CCE backing-array anchor, so callers can
        continue folding the enclosing expression.

        Expressions with UnknownType or NoneType are skipped to avoid
        materializing void/sentinel results (e.g. nbuf.advance() void calls).
        """
        from ...ir.op.dist_ops import _ChannelCreate

        if isinstance(result, _ChannelCreate):
            raise InvalidOperation(
                "pld.channel must be assigned to a variable",
                span=span,
                hint="Write `ch = pld.channel(...)` at the section scope.",
            )
        if isinstance(result, ir.MakeTuple):
            if result not in self._anchored_make_tuples:
                name = f"_tuple_anchor_{self._expr_tmp_counter}"
                self._expr_tmp_counter += 1
                self.builder.let(name, result, span=span)
                self._mark_make_tuple_anchor(result)
            return result
        if isinstance(result, (ir.Var, ir.ConstInt, ir.ConstFloat, ir.ConstBool)):
            return result
        if not isinstance(result, ir.Expr):
            return result
        if isinstance(result.type, (ir.UnknownType, ir.NoneType)):
            return result
        name = f"_expr_tmp_{self._expr_tmp_counter}"
        self._expr_tmp_counter += 1
        value = self.builder.let(name, result, span=span)
        self._transfer_tile_group_metadata(value, result)
        return value

    def _get_object_method_op_name(self, obj: ir.Expr, method: str) -> str | None:
        """Resolve an object's method to its registered operation name."""
        obj_type = obj.type
        if isinstance(obj_type, ir.TupleType) and not self.is_tile_group(obj):
            return None

        key = obj_type.kind if isinstance(obj_type, ir.SimtGroupType) else type(obj_type)
        prefix = self._OBJECT_OP_PREFIXES.get(key)
        return f"{prefix}.{method}" if prefix is not None else None

    def _route_ir_node_method(self, node: ast.Call) -> ir.Expr | None:
        """Resolve and dispatch an object method, returning its IR result."""
        if not isinstance(node.func, ast.Attribute):
            return None
        try:
            obj = self.parse_expression(node.func.value)
        except PyptoProError:
            return None
        method = node.func.attr
        if not isinstance(obj, ir.Expr):
            return None
        op_name = self._get_object_method_op_name(obj, method)
        if op_name is None:
            return None
        if isinstance(obj.type, ir.SimtGroupType) and not _is_simt_func_type(self._current_func_type):
            raise InvalidOperation(
                f"pl.{op_name}() can only be used inside a SIMT function",
                hint='Move SIMT-context-dependent logic into @pl.vector_function(mode="simt").',
            )

        op_func = _OP_REGISTRY.get(op_name)
        if op_func is None:
            raise NotSupported(f"Unsupported operation call: {ast.unparse(node)}", parser_retry=True)
        return self._dispatch_op(op_name, node, op_func, obj=obj)

    _CHANNEL_METHODS = frozenset(
        {"remote_ptr", "write", "read", "write_reduce", "atomic_fetch_add", "atomic_cas",
         "write_notify", "submit", "drain", "lock", "unlock", "is_shared"}
    )

    def _route_channel_method(self, node: ast.Call):
        """Route ``ch.<method>(...)`` when ``ch`` resolves to a pld.Channel handle.

        Returns the IR result, or None when the receiver is not a channel. Runs before
        the declaration gate and auto-mutex dispatch, so it enforces its own execution
        domain: channel operations drive the AIV write engine.
        """
        if not isinstance(node.func, ast.Attribute) or node.func.attr not in self._CHANNEL_METHODS:
            return None
        from ..distribute import BufferChannel, Channel

        if not isinstance(node.func.value, ast.Name):
            # A channel handle is always a bound variable; any other receiver shape
            # (e.g. pl.simt.atomic_cas, unrelated to the channel op of the same name)
            # cannot be a channel, so leave it to the regular dispatch without parsing.
            return None
        binding = self.local_binding(node.func.value.id)
        if binding is None:
            return None
        receiver = binding[1]
        is_buffer = isinstance(receiver, BufferChannel)
        if not is_buffer and not isinstance(receiver, Channel):
            return None
        span = self.span_tracker.get_span(node)
        if (
            self.target != ir.SectionKind.Vector
            or self._in_simd_vf_body()
            or self._current_func_type in (ir.FunctionType.SimtVF, ir.FunctionType.SimtCallee)
        ):
            raise InvalidOperation(
                f"pld.Channel.{node.func.attr}() requires the Vector section",
                span=span,
                hint="Channel operations run on the AIV; move them into pl.section_vector().",
            )
        from ...ir.op import dist_ops

        if is_buffer:
            return dist_ops.parse_buffer_channel_method(self, receiver, node.func.attr, node)
        return dist_ops.parse_channel_method(self, receiver, node.func.attr, node)