Merged
fix(pypto_pro):add arguments name and type check #6717
huanyongbenAdd on Sep 24
fix(pypto_pro):add arguments name and type check #6717
Merged
huanyongbenAdd on Sep 24
Total: 30 files changed+1837-314
@@ -453,14 +453,12 @@ REGISTER_OP("block.reshape")
453 return DeduceBlockOutTileType(args, kwargs, "block.reshape", 3);453 return DeduceBlockOutTileType(args, kwargs, "block.reshape", 3);
454 });454 });
455 455 
456-// block.transpose: (out, src_tile) -> out's type; axis attrs.456+// block.transpose: (out, src_tile) -> out's type; swaps the last two dimensions.
457REGISTER_OP("block.transpose")457REGISTER_OP("block.transpose")
458 .set_op_category("BlockOp")458 .set_op_category("BlockOp")
459- .set_description("Block explicit-output transpose: swap two axes of src tile into out")459+ .set_description("Block explicit-output transpose: swap the last two dimensions of src tile into out")
460 .add_argument("out", "Pre-allocated output tile with transposed shape (TileType)")460 .add_argument("out", "Pre-allocated output tile with transposed shape (TileType)")
461 .add_argument("src", "Source tile (TileType)")461 .add_argument("src", "Source tile (TileType)")
462- .set_attr<int>("axis1")
463- .set_attr<int>("axis2")
464 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,462 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
465 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {463 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
466 return DeduceBlockOutUnary(args, kwargs, "block.transpose");464 return DeduceBlockOutUnary(args, kwargs, "block.transpose");
@@ -934,10 +934,9 @@ TEST_F(BlockOpsOutElemwiseTest, BlockReshape_ReturnsOutType)
934TEST_F(BlockOpsOutElemwiseTest, BlockTranspose_ReturnsOutType)934TEST_F(BlockOpsOutElemwiseTest, BlockTranspose_ReturnsOutType)
935{935{
936 auto& reg = OpRegistry::GetInstance();936 auto& reg = OpRegistry::GetInstance();
937- std::vector<std::pair<std::string, std::any>> kwargs = {{"axis1", int(0)}, {"axis2", int(1)}};
938 auto call = reg.Create("block.transpose",937 auto call = reg.Create("block.transpose",
939- {MakeTileVar("o", {32, 16}, DataType::FP16), MakeTileVar("s", {16, 32}, DataType::FP16)},938+ {MakeTileVar("o", {32, 16}, DataType::FP16), MakeTileVar("s", {16, 32}, DataType::FP16)}, {},
940- kwargs, Sp());939+ Sp());
941 EXPECT_NE(As<TileType>(call->GetType()), nullptr);940 EXPECT_NE(As<TileType>(call->GetType()), nullptr);
942}941}
943 942 
@@ -30,6 +30,7 @@ __all__ = [
30 "PyptoProError",30 "PyptoProError",
31 "argument_span",31 "argument_span",
32 "remembered_span",32 "remembered_span",
33+ "source_lines_of",
33 "span_of",34 "span_of",
34 "span_source",35 "span_source",
35 "current_span",36 "current_span",
@@ -214,6 +215,21 @@ def remembered_span(error: BaseException) -> ir.Span | None:
214 return getattr(error, _SPAN_ATTR, None)215 return getattr(error, _SPAN_ATTR, None)
215 216 
216 217 
218+def source_lines_of(filename: str) -> list[str] | None:
219+ """Every line of *filename*, to render the caret preview, or None if unreadable.
220+ 
221+ The whole file, not just the declaration being reported: a span carries absolute
222+ line numbers and the preview is indexed by them, so a slice starting at some
223+ ``def`` or ``class`` would quote the wrong lines. Without it the ``-->`` header
224+ still renders and only the quoted source goes missing.
225+ """
226+ try:
227+ with open(filename, encoding="utf-8") as handle:
228+ return handle.read().split("\n")
229+ except OSError:
230+ return None
231+ 
232+ 
217def _normalize_span(span: ir.Span | None) -> dict[str, str | int | None] | None:233def _normalize_span(span: ir.Span | None) -> dict[str, str | int | None] | None:
218 """Convert an IR span to a plain dict, so no C++ object is kept alive."""234 """Convert an IR span to a plain dict, so no C++ object is kept alive."""
219 if span is None:235 if span is None:
@@ -76,6 +76,11 @@ def _make_handler(spec: OpSpec) -> Callable:
76 kwargs = self.parse_op_kwargs(call) if spec.parse_kwargs else {}76 kwargs = self.parse_op_kwargs(call) if spec.parse_kwargs else {}
77 for hook in spec.pre_hooks:77 for hook in spec.pre_hooks:
78 hook(self, call, kwargs)78 hook(self, call, kwargs)
79+ # The arguments are values now, which is what the type gate needs and the
80+ # name-and-count gate at the dispatch point could not have.
81+ op_name = self._extract_op_name(call.func)
82+ if op_name is not None:
83+ self._check_declared_types(op_name, call, args, kwargs, span)
79 # Publish where the caller wrote each argument, so a builder that rejects84 # Publish where the caller wrote each argument, so a builder that rejects
80 # one can point at that argument rather than at the whole call. Every85 # one can point at that argument rather than at the whole call. Every
81 # @op_impl operator is dispatched here, so this one site covers them all.86 # @op_impl operator is dispatched here, so this one site covers them all.
@@ -177,8 +177,8 @@ def _ir_binary_cast(
177 177 
178 178 
179def _ir_load(179def _ir_load(
180- out: Expr,180+ dst_tile: Expr,
181- tensor: Expr,181+ src_tensor: Expr,
182 offsets: Sequence[int | Expr] | _ir_core.MakeTuple,182 offsets: Sequence[int | Expr] | _ir_core.MakeTuple,
183 *,183 *,
184 span: Span | None = None,184 span: Span | None = None,
@@ -188,14 +188,14 @@ def _ir_load(
188 actual_span = span or _span()188 actual_span = span or _span()
189 offsets_tuple = _to_make_tuple(offsets, actual_span)189 offsets_tuple = _to_make_tuple(offsets, actual_span)
190 190 
191- tensor_ndim = len(tensor.type.shape)191+ tensor_ndim = len(src_tensor.type.shape)
192- tile_ndim = len(out.type.shape)192+ tile_ndim = len(dst_tile.type.shape)
193 tile_dims, is_transpose = _resolve_order(order, tensor_ndim, tile_ndim, op_name)193 tile_dims, is_transpose = _resolve_order(order, tensor_ndim, tile_ndim, op_name)
194 194 
195 tensor_ndim, tile_shape, tile_dims, _ = _validate_load_operands(195 tensor_ndim, tile_shape, tile_dims, _ = _validate_load_operands(
196- out, tensor, offsets_tuple, tile_dims, op_name196+ dst_tile, src_tensor, offsets_tuple, tile_dims, op_name
197 )197 )
198- _validate_nz_transfer_axes(tensor.type, tile_dims, op_name)198+ _validate_nz_transfer_axes(src_tensor.type, tile_dims, op_name)
199 199 
200 kwargs: dict[str, Any] = {}200 kwargs: dict[str, Any] = {}
201 if is_transpose:201 if is_transpose:
@@ -205,16 +205,16 @@ def _ir_load(
205 if order is not None and tile_dims is not None:205 if order is not None and tile_dims is not None:
206 kwargs["tile_dims"] = tile_dims206 kwargs["tile_dims"] = tile_dims
207 if isinstance(offsets, _ir_core.MakeTuple):207 if isinstance(offsets, _ir_core.MakeTuple):
208- _validate_offset_bounds("load", tensor.type.shape, offsets.elements)208+ _validate_offset_bounds("load", src_tensor.type.shape, offsets.elements)
209 else:209 else:
210- _validate_offset_bounds("load", tensor.type.shape, offsets)210+ _validate_offset_bounds("load", src_tensor.type.shape, offsets)
211- _check_layout_dtype(op_name, tensor, out, is_transpose=is_transpose)211+ _check_layout_dtype(op_name, src_tensor, dst_tile, is_transpose=is_transpose)
212- return _ir_core.create_op_call(block_ir_op(op_name), [out, tensor, offsets_tuple], kwargs, actual_span)212+ return _ir_core.create_op_call(block_ir_op(op_name), [dst_tile, src_tensor, offsets_tuple], kwargs, actual_span)
213 213 
214 214 
215def _ir_load_tile(215def _ir_load_tile(
216- out: Expr,216+ dst_tile: Expr,
217- tensor: Expr,217+ src_tensor: Expr,
218 tile_offsets: Sequence[int | Expr] | _ir_core.MakeTuple,218 tile_offsets: Sequence[int | Expr] | _ir_core.MakeTuple,
219 *,219 *,
220 span: Span | None = None,220 span: Span | None = None,
@@ -224,19 +224,19 @@ def _ir_load_tile(
224 actual_span = span or _span()224 actual_span = span or _span()
225 offsets_tuple = _to_make_tuple(tile_offsets, actual_span)225 offsets_tuple = _to_make_tuple(tile_offsets, actual_span)
226 226 
227- tensor_ndim = len(tensor.type.shape)227+ tensor_ndim = len(src_tensor.type.shape)
228- tile_ndim = len(out.type.shape)228+ tile_ndim = len(dst_tile.type.shape)
229 tile_dims, is_transpose = _resolve_order(order, tensor_ndim, tile_ndim, op_name)229 tile_dims, is_transpose = _resolve_order(order, tensor_ndim, tile_ndim, op_name)
230 230 
231 tensor_ndim, tile_shape, tile_dims, access_size = _validate_load_operands(231 tensor_ndim, tile_shape, tile_dims, access_size = _validate_load_operands(
232- out,232+ dst_tile,
233- tensor,233+ src_tensor,
234 offsets_tuple,234 offsets_tuple,
235 tile_dims,235 tile_dims,
236 op_name,236 op_name,
237 use_tile_absolute=True,237 use_tile_absolute=True,
238 )238 )
239- _validate_nz_transfer_axes(tensor.type, tile_dims, op_name)239+ _validate_nz_transfer_axes(src_tensor.type, tile_dims, op_name)
240 240 
241 abs_offsets = _compute_absolute_offsets(241 abs_offsets = _compute_absolute_offsets(
242 offsets_tuple,242 offsets_tuple,
@@ -246,14 +246,14 @@ def _ir_load_tile(
246 access_size=access_size,246 access_size=access_size,
247 )247 )
248 # Validate offset bounds at Python frontend level248 # Validate offset bounds at Python frontend level
249- _validate_offset_bounds("load_tile", tensor.type.shape, abs_offsets.elements)249+ _validate_offset_bounds("load_tile", src_tensor.type.shape, abs_offsets.elements)
250- _check_layout_dtype("load_tile", tensor, out, is_transpose=is_transpose)250+ _check_layout_dtype("load_tile", src_tensor, dst_tile, is_transpose=is_transpose)
251 kwargs: dict[str, Any] = {}251 kwargs: dict[str, Any] = {}
252 if is_transpose:252 if is_transpose:
253 kwargs["is_transpose"] = is_transpose253 kwargs["is_transpose"] = is_transpose
254 if order is not None and tile_dims is not None:254 if order is not None and tile_dims is not None:
255 kwargs["tile_dims"] = tile_dims255 kwargs["tile_dims"] = tile_dims
256- return _ir_core.create_op_call(block_ir_op("load"), [out, tensor, abs_offsets], kwargs, actual_span)256+ return _ir_core.create_op_call(block_ir_op("load"), [dst_tile, src_tensor, abs_offsets], kwargs, actual_span)
257 257 
258 258 
259def _encode_deq_scalar(scale: float) -> int:259def _encode_deq_scalar(scale: float) -> int:
@@ -303,8 +303,8 @@ def _resolve_scale_param(
303 303 
304 304 
305def _ir_store(305def _ir_store(
306- out: Expr,306+ dst_tensor: Expr,
307- tile: Expr,307+ src_tile: Expr,
308 offsets: Sequence[int | Expr] | _ir_core.MakeTuple,308 offsets: Sequence[int | Expr] | _ir_core.MakeTuple,
309 *,309 *,
310 span: Span | None = None,310 span: Span | None = None,
@@ -318,12 +318,12 @@ def _ir_store(
318 actual_span = span or _span()318 actual_span = span or _span()
319 offsets_tuple = _to_make_tuple(offsets, actual_span)319 offsets_tuple = _to_make_tuple(offsets, actual_span)
320 320 
321- if not isinstance(out.type, _ir_core.TensorType):321+ if not isinstance(dst_tensor.type, _ir_core.TensorType):
322- raise InvalidType(f"{op_name}: dst must be a Tensor, got {type(out.type).__name__}")322+ raise InvalidType(f"{op_name}: dst must be a Tensor, got {type(dst_tensor.type).__name__}")
323 323 
324- if not isinstance(tile.type, _ir_core.TileType):324+ if not isinstance(src_tile.type, _ir_core.TileType):
325- raise InvalidType(f"{op_name}: src must be a Tile, got {type(tile.type).__name__}")325+ raise InvalidType(f"{op_name}: src must be a Tile, got {type(src_tile.type).__name__}")
326- _src_mem = getattr(getattr(tile.type, "memref", None), "memory_space", None)326+ _src_mem = getattr(getattr(src_tile.type, "memref", None), "memory_space", None)
327 if _src_mem is not None and _src_mem not in (_ir_core.MemorySpace.Vec, _ir_core.MemorySpace.Acc):327 if _src_mem is not None and _src_mem not in (_ir_core.MemorySpace.Vec, _ir_core.MemorySpace.Acc):
328 raise InvalidOperation(f"{op_name}: src tile must be in Vec (UB) or Acc (L0C) memory, got {_src_mem.name}")328 raise InvalidOperation(f"{op_name}: src tile must be in Vec (UB) or Acc (L0C) memory, got {_src_mem.name}")
329 329 
@@ -332,27 +332,27 @@ def _ir_store(
332 if not isinstance(atomic, AtomicType):332 if not isinstance(atomic, AtomicType):
333 raise InvalidType(f"{op_name}: invalid atomic value {atomic!r}, expected AtomicType")333 raise InvalidType(f"{op_name}: invalid atomic value {atomic!r}, expected AtomicType")
334 334 
335- tensor_ndim = len(out.type.shape)335+ tensor_ndim = len(dst_tensor.type.shape)
336- tile_shape = list(tile.type.shape)336+ tile_shape = list(src_tile.type.shape)
337 tile_dims, access_size = _validate_tile_dims(order, tensor_ndim, tile_shape, op_name)337 tile_dims, access_size = _validate_tile_dims(order, tensor_ndim, tile_shape, op_name)
338 tile_ndim = len(tile_shape)338 tile_ndim = len(tile_shape)
339 if order is not None and order != sorted(order):339 if order is not None and order != sorted(order):
340 raise InvalidVal(f"{op_name}: order must be ascending, got {order}")340 raise InvalidVal(f"{op_name}: order must be ascending, got {order}")
341- _validate_nz_transfer_axes(out.type, tile_dims, op_name)341+ _validate_nz_transfer_axes(dst_tensor.type, tile_dims, op_name)
342 _validate_offsets(342 _validate_offsets(
343 offsets_tuple,343 offsets_tuple,
344 tile_dims,344 tile_dims,
345 tile_shape,345 tile_shape,
346- out.type.shape,346+ dst_tensor.type.shape,
347 op_name,347 op_name,
348 access_size=access_size,348 access_size=access_size,
349 )349 )
350 350 
351- _validate_offset_bounds("store", out.type.shape, offsets_tuple.elements)351+ _validate_offset_bounds("store", dst_tensor.type.shape, offsets_tuple.elements)
352 352 
353 pre_quant_scalar, fp_tile = _resolve_scale_param(scale, actual_span)353 pre_quant_scalar, fp_tile = _resolve_scale_param(scale, actual_span)
354 is_quant = pre_quant_scalar is not None or fp_tile is not None354 is_quant = pre_quant_scalar is not None or fp_tile is not None
355- _check_layout_dtype(op_name, tile, out, quant=is_quant)355+ _check_layout_dtype(op_name, src_tile, dst_tensor, quant=is_quant)
356 if relu_pre_mode is not None and _src_mem is not None and _src_mem != _ir_core.MemorySpace.Acc:356 if relu_pre_mode is not None and _src_mem is not None and _src_mem != _ir_core.MemorySpace.Acc:
357 raise NotSupported(f"{op_name}: relu_pre_mode is only supported for Acc (L0C) source tiles")357 raise NotSupported(f"{op_name}: relu_pre_mode is only supported for Acc (L0C) source tiles")
358 if fp_tile is not None and atomic != AtomicType.AtomicNone:358 if fp_tile is not None and atomic != AtomicType.AtomicNone:
@@ -368,7 +368,7 @@ def _ir_store(
368 atomic=atomic,368 atomic=atomic,
369 phase=phase,369 phase=phase,
370 )370 )
371- operands: list[Expr] = [out, tile, offsets_tuple]371+ operands: list[Expr] = [dst_tensor, src_tile, offsets_tuple]
372 if fp_tile is not None:372 if fp_tile is not None:
373 operands.append(fp_tile)373 operands.append(fp_tile)
374 elif pre_quant_scalar is not None:374 elif pre_quant_scalar is not None:
@@ -382,8 +382,8 @@ def _ir_store(
382 382 
383 383 
384def _ir_store_tile(384def _ir_store_tile(
385- out: Expr,385+ dst_tensor: Expr,
386- tile: Expr,386+ src_tile: Expr,
387 tile_offsets: Sequence[int | Expr] | _ir_core.MakeTuple,387 tile_offsets: Sequence[int | Expr] | _ir_core.MakeTuple,
388 *,388 *,
389 span: Span | None = None,389 span: Span | None = None,
@@ -397,12 +397,12 @@ def _ir_store_tile(
397 actual_span = span or _span()397 actual_span = span or _span()
398 offsets_tuple = _to_make_tuple(tile_offsets, actual_span)398 offsets_tuple = _to_make_tuple(tile_offsets, actual_span)
399 399 
400- if not isinstance(out.type, _ir_core.TensorType):400+ if not isinstance(dst_tensor.type, _ir_core.TensorType):
401- raise InvalidType(f"{op_name}: dst must be a Tensor, got {type(out.type).__name__}")401+ raise InvalidType(f"{op_name}: dst must be a Tensor, got {type(dst_tensor.type).__name__}")
402 402 
403- if not isinstance(tile.type, _ir_core.TileType):403+ if not isinstance(src_tile.type, _ir_core.TileType):
404- raise InvalidType(f"{op_name}: src must be a Tile, got {type(tile.type).__name__}")404+ raise InvalidType(f"{op_name}: src must be a Tile, got {type(src_tile.type).__name__}")
405- _src_mem = getattr(getattr(tile.type, "memref", None), "memory_space", None)405+ _src_mem = getattr(getattr(src_tile.type, "memref", None), "memory_space", None)
406 if _src_mem is not None and _src_mem not in (_ir_core.MemorySpace.Vec, _ir_core.MemorySpace.Acc):406 if _src_mem is not None and _src_mem not in (_ir_core.MemorySpace.Vec, _ir_core.MemorySpace.Acc):
407 raise InvalidOperation(f"{op_name}: src tile must be in Vec (UB) or Acc (L0C) memory, got {_src_mem.name}")407 raise InvalidOperation(f"{op_name}: src tile must be in Vec (UB) or Acc (L0C) memory, got {_src_mem.name}")
408 408 
@@ -411,18 +411,18 @@ def _ir_store_tile(
411 if not isinstance(atomic, AtomicType):411 if not isinstance(atomic, AtomicType):
412 raise InvalidType(f"{op_name}: invalid atomic value {atomic!r}, expected AtomicType")412 raise InvalidType(f"{op_name}: invalid atomic value {atomic!r}, expected AtomicType")
413 413 
414- tensor_ndim = len(out.type.shape)414+ tensor_ndim = len(dst_tensor.type.shape)
415- tile_shape = list(tile.type.shape)415+ tile_shape = list(src_tile.type.shape)
416 tile_dims, access_size = _validate_tile_dims(order, tensor_ndim, tile_shape, op_name)416 tile_dims, access_size = _validate_tile_dims(order, tensor_ndim, tile_shape, op_name)
417 tile_ndim = len(tile_shape)417 tile_ndim = len(tile_shape)
418 if order is not None and order != sorted(order):418 if order is not None and order != sorted(order):
419 raise InvalidVal(f"{op_name}: order must be ascending, got {order}")419 raise InvalidVal(f"{op_name}: order must be ascending, got {order}")
420- _validate_nz_transfer_axes(out.type, tile_dims, op_name)420+ _validate_nz_transfer_axes(dst_tensor.type, tile_dims, op_name)
421 _validate_offsets(421 _validate_offsets(
422 offsets_tuple,422 offsets_tuple,
423 tile_dims,423 tile_dims,
424 tile_shape,424 tile_shape,
425- out.type.shape,425+ dst_tensor.type.shape,
426 op_name,426 op_name,
427 use_tile_absolute=True,427 use_tile_absolute=True,
428 access_size=access_size,428 access_size=access_size,
@@ -435,11 +435,11 @@ def _ir_store_tile(
435 actual_span,435 actual_span,
436 access_size=access_size,436 access_size=access_size,
437 )437 )
438- _validate_offset_bounds("store_tile", out.type.shape, abs_offsets.elements)438+ _validate_offset_bounds("store_tile", dst_tensor.type.shape, abs_offsets.elements)
439 439 
440 pre_quant_scalar, fp_tile = _resolve_scale_param(scale, actual_span)440 pre_quant_scalar, fp_tile = _resolve_scale_param(scale, actual_span)
441 is_quant = pre_quant_scalar is not None or fp_tile is not None441 is_quant = pre_quant_scalar is not None or fp_tile is not None
442- _check_layout_dtype(op_name, tile, out, quant=is_quant)442+ _check_layout_dtype(op_name, src_tile, dst_tensor, quant=is_quant)
443 if relu_pre_mode is not None and _src_mem is not None and _src_mem != _ir_core.MemorySpace.Acc:443 if relu_pre_mode is not None and _src_mem is not None and _src_mem != _ir_core.MemorySpace.Acc:
444 raise NotSupported(f"{op_name}: relu_pre_mode is only supported for Acc (L0C) source tiles")444 raise NotSupported(f"{op_name}: relu_pre_mode is only supported for Acc (L0C) source tiles")
445 if fp_tile is not None and atomic != AtomicType.AtomicNone:445 if fp_tile is not None and atomic != AtomicType.AtomicNone:
@@ -455,7 +455,7 @@ def _ir_store_tile(
455 atomic=atomic,455 atomic=atomic,
456 phase=phase,456 phase=phase,
457 )457 )
458- operands: list[Expr] = [out, tile, abs_offsets]458+ operands: list[Expr] = [dst_tensor, src_tile, abs_offsets]
459 if fp_tile is not None:459 if fp_tile is not None:
460 operands.append(fp_tile)460 operands.append(fp_tile)
461 elif pre_quant_scalar is not None:461 elif pre_quant_scalar is not None:
@@ -615,8 +615,8 @@ def _maybe_dispatch_to_insert(
615 615 
616 616 
617def _ir_move(617def _ir_move(
618- out: Expr,618+ dst_tile: Expr,
619- src: Expr,619+ src_tile: Expr,
620 offset: Expr | Sequence[Any] | None = None,620 offset: Expr | Sequence[Any] | None = None,
621 *,621 *,
622 span: Span | None = None,622 span: Span | None = None,
@@ -627,16 +627,16 @@ def _ir_move(
627) -> Expr:627) -> Expr:
628 actual_span = span or _span()628 actual_span = span or _span()
629 629 
630- if _maybe_dispatch_to_insert(out, src, offset, acc_to_vec_mode, relu_pre_mode, scale):630+ if _maybe_dispatch_to_insert(dst_tile, src_tile, offset, acc_to_vec_mode, relu_pre_mode, scale):
631 actual_offset = offset if offset is not None else [0, 0]631 actual_offset = offset if offset is not None else [0, 0]
632- return _ir_insert(out, src, actual_offset, span=actual_span)632+ return _ir_insert(dst_tile, src_tile, actual_offset, span=actual_span)
633 633 
634- if not isinstance(out.type, _ir_core.TileType):634+ if not isinstance(dst_tile.type, _ir_core.TileType):
635- raise InvalidType(f"move: dst must be a Tile, got {type(out.type).__name__}")635+ raise InvalidType(f"move: dst must be a Tile, got {type(dst_tile.type).__name__}")
636- if not isinstance(src.type, _ir_core.TileType):636+ if not isinstance(src_tile.type, _ir_core.TileType):
637- raise InvalidType(f"move: src must be a Tile, got {type(src.type).__name__}")637+ raise InvalidType(f"move: src must be a Tile, got {type(src_tile.type).__name__}")
638- _dst_mem = getattr(getattr(out.type, "memref", None), "memory_space_", None)638+ _dst_mem = getattr(getattr(dst_tile.type, "memref", None), "memory_space_", None)
639- _src_mem = getattr(getattr(src.type, "memref", None), "memory_space_", None)639+ _src_mem = getattr(getattr(src_tile.type, "memref", None), "memory_space_", None)
640 _supported_move_paths = {640 _supported_move_paths = {
641 (MemorySpace.Mat, MemorySpace.Left),641 (MemorySpace.Mat, MemorySpace.Left),
642 (MemorySpace.Mat, MemorySpace.Right),642 (MemorySpace.Mat, MemorySpace.Right),
@@ -671,12 +671,12 @@ def _ir_move(
671 raise InvalidArgument(f"move: invalid phase value {phase!r}, expected STPhase")671 raise InvalidArgument(f"move: invalid phase value {phase!r}, expected STPhase")
672 672 
673 # Validate src/dst tile shape compatibility (issue #99: transpose-style mismatch)673 # Validate src/dst tile shape compatibility (issue #99: transpose-style mismatch)
674- _check_move_shape_compat(out, src, offset, acc_to_vec_mode, actual_span)674+ _check_move_shape_compat(dst_tile, src_tile, offset, acc_to_vec_mode, actual_span)
675 if offset is not None:675 if offset is not None:
676 if isinstance(offset, _ir_core.MakeTuple):676 if isinstance(offset, _ir_core.MakeTuple):
677- _validate_offset_bounds("move", src.type.shape, offset.elements)677+ _validate_offset_bounds("move", src_tile.type.shape, offset.elements)
678 elif isinstance(offset, (list, tuple)):678 elif isinstance(offset, (list, tuple)):
679- _validate_offset_bounds("move", src.type.shape, offset)679+ _validate_offset_bounds("move", src_tile.type.shape, offset)
680 680 
681 pre_quant_scalar, fp_tile = _resolve_scale_param(scale, actual_span)681 pre_quant_scalar, fp_tile = _resolve_scale_param(scale, actual_span)
682 if fp_tile is not None and (_src_mem, _dst_mem) not in {682 if fp_tile is not None and (_src_mem, _dst_mem) not in {
@@ -684,7 +684,7 @@ def _ir_move(
684 }:684 }:
685 raise NotSupported("move: Scaling Tile scale only supports Acc-to-Vec moves")685 raise NotSupported("move: Scaling Tile scale only supports Acc-to-Vec moves")
686 is_quant = pre_quant_scalar is not None or fp_tile is not None686 is_quant = pre_quant_scalar is not None or fp_tile is not None
687- _check_layout_dtype("move", src, out, quant=is_quant)687+ _check_layout_dtype("move", src_tile, dst_tile, quant=is_quant)
688 688 
689 if offset is not None and (fp_tile is not None or pre_quant_scalar is not None):689 if offset is not None and (fp_tile is not None or pre_quant_scalar is not None):
690 raise NotSupported(690 raise NotSupported(
@@ -708,8 +708,8 @@ def _ir_move(
708 if phase is not None:708 if phase is not None:
709 kwargs["phase"] = phase709 kwargs["phase"] = phase
710 if fp_tile is not None:710 if fp_tile is not None:
711- return _ir_core.create_op_call(block_ir_op("move_fp"), [out, src, fp_tile], kwargs, actual_span)711+ return _ir_core.create_op_call(block_ir_op("move_fp"), [dst_tile, src_tile, fp_tile], kwargs, actual_span)
712- args = [out, src]712+ args = [dst_tile, src_tile]
713 if offset is not None:713 if offset is not None:
714 args.append(_to_make_tuple(offset, actual_span))714 args.append(_to_make_tuple(offset, actual_span))
715 if pre_quant_scalar is not None:715 if pre_quant_scalar is not None:
@@ -730,18 +730,18 @@ def _normalize_2d_sequence(value: Any, parameter: str, span: Span) -> tuple[Expr
730 730 
731 731 
732def _ir_insert(732def _ir_insert(
733- out: Expr,733+ dst_tile: Expr,
734- src: Expr,734+ src_tile: Expr,
735 offset: Sequence[int | Expr] | _ir_core.MakeTuple,735 offset: Sequence[int | Expr] | _ir_core.MakeTuple,
736 *,736 *,
737 span: Span | None = None,737 span: Span | None = None,
738) -> Expr:738) -> Expr:
739 actual_span = span or _span()739 actual_span = span or _span()
740- _check_layout_dtype("insert", src, out)740+ _check_layout_dtype("insert", src_tile, dst_tile)
741 row, col = _normalize_2d_sequence(offset, "offset", actual_span)741 row, col = _normalize_2d_sequence(offset, "offset", actual_span)
742 # Validate offset bounds at Python frontend level742 # Validate offset bounds at Python frontend level
743- _validate_offset_bounds("insert", out.type.shape, [row, col])743+ _validate_offset_bounds("insert", dst_tile.type.shape, [row, col])
744- return _ir_core.create_op_call(block_ir_op("insert"), [out, src, row, col], {}, actual_span)744+ return _ir_core.create_op_call(block_ir_op("insert"), [dst_tile, src_tile, row, col], {}, actual_span)
745 745 
746 746 
747def _ir_sel(out: Expr, mask: Expr, lhs: Expr, rhs: Expr, tmp: Expr, *, span: Span | None = None) -> Expr:747def _ir_sel(out: Expr, mask: Expr, lhs: Expr, rhs: Expr, tmp: Expr, *, span: Span | None = None) -> Expr:
@@ -786,7 +786,7 @@ def _ir_relu(out: Expr, src: Expr, *, span: Span | None = None) -> Expr:
786 return _ir_core.create_op_call(block_ir_op("relu"), [out, src], {}, span or _span())786 return _ir_core.create_op_call(block_ir_op("relu"), [out, src], {}, span or _span())
787 787 
788 788 
789-def _ir_axpy(out: Expr, src: Expr, scalar: Expr, *, span: Span | None = None) -> Expr:789+def _ir_axpy(out: Expr, src: Expr, alpha: Expr, *, span: Span | None = None) -> Expr:
790 dt = getattr(out.type, "dtype", None)790 dt = getattr(out.type, "dtype", None)
791 src_dt = getattr(src.type, "dtype", None)791 src_dt = getattr(src.type, "dtype", None)
792 _check_dtype("axpy", dt, _AXPY_DTYPES)792 _check_dtype("axpy", dt, _AXPY_DTYPES)
@@ -798,7 +798,7 @@ def _ir_axpy(out: Expr, src: Expr, scalar: Expr, *, span: Span | None = None) ->
798 f"Supported: same type, or src=FP16 + out=FP32."798 f"Supported: same type, or src=FP16 + out=FP32."
799 )799 )
800 actual_span = span or _span()800 actual_span = span or _span()
801- scalar_expr = _normalize_expr(scalar, actual_span)801+ scalar_expr = _normalize_expr(alpha, actual_span)
802 from pypto_pro.language.parser.diagnostics import check_const_expr_fits_dtype802 from pypto_pro.language.parser.diagnostics import check_const_expr_fits_dtype
803 803 
804 check_const_expr_fits_dtype(scalar_expr, dt, span=actual_span, api="pl.axpy")804 check_const_expr_fits_dtype(scalar_expr, dt, span=actual_span, api="pl.axpy")
@@ -1223,9 +1223,7 @@ def _ir_setval(container: Expr, offset: int | Expr, value: int | float | Expr, *
1223 return _ir_core.create_op_call(block_ir_op("setval"), [container, offset_expr, value_expr], {}, actual_span)1223 return _ir_core.create_op_call(block_ir_op("setval"), [container, offset_expr, value_expr], {}, actual_span)
1224 1224 
1225 1225 
1226-def _ir_transpose(1226+def _ir_transpose(out: Expr, src: Expr, *, span: Span | None = None) -> Expr:
1227- out: Expr, src: Expr, axis1: int | Expr = 0, axis2: int | Expr = 1, *, span: Span | None = None
1228-) -> Expr:
1229 dt = getattr(out.type, "dtype", None)1227 dt = getattr(out.type, "dtype", None)
1230 if dt is not None and dt.get_bit() not in (8, 16, 32):1228 if dt is not None and dt.get_bit() not in (8, 16, 32):
1231 raise InvalidType(f"transpose: unsupported dtype {dt}, supported: b8/b16/b32")1229 raise InvalidType(f"transpose: unsupported dtype {dt}, supported: b8/b16/b32")
@@ -1235,7 +1233,7 @@ def _ir_transpose(
1235 return _ir_core.create_op_call(1233 return _ir_core.create_op_call(
1236 block_ir_op("transpose"),1234 block_ir_op("transpose"),
1237 [out, src],1235 [out, src],
1238- {"axis1": _const_int_attr(axis1, "axis1"), "axis2": _const_int_attr(axis2, "axis2")},1236+ {},
1239 span or _span(),1237 span or _span(),
1240 )1238 )
1241 1239 
@@ -3436,6 +3434,7 @@ def _parse_tile_type_call(self, call: ast.Call):
3436 ]3434 ]
3437 else:3435 else:
3438 kwargs[kw.arg] = self.resolve_single_kwarg(kw.arg, kw.value)3436 kwargs[kw.arg] = self.resolve_single_kwarg(kw.arg, kw.value)
3437+ self._check_declared_types("TileType", call, [], kwargs, self.span_tracker.get_span(call))
3439 return TileType(**kwargs)3438 return TileType(**kwargs)
3440 3439 
3441 3440 
@@ -3609,6 +3608,7 @@ def _parse_reinterpret(self, call: ast.Call) -> Expr:
3609 )3608 )
3610 src = self.parse_expression(call.args[0])3609 src = self.parse_expression(call.args[0])
3611 kwargs = self.parse_op_kwargs(call)3610 kwargs = self.parse_op_kwargs(call)
3611+ self._check_declared_types("reinterpret", call, [src], kwargs, span)
3612 3612 
3613 if kwargs.get("dtype") is None and kwargs.get("shape") is None and kwargs.get("layout") is None:3613 if kwargs.get("dtype") is None and kwargs.get("shape") is None and kwargs.get("layout") is None:
3614 raise InvalidType(3614 raise InvalidType(
@@ -4020,6 +4020,7 @@ def _parse_set_validshape(self, call: ast.Call) -> Expr:
4020 span = self.span_tracker.get_span(call)4020 span = self.span_tracker.get_span(call)
4021 args = [self.parse_expression(arg) for arg in call.args]4021 args = [self.parse_expression(arg) for arg in call.args]
4022 kwargs = self.parse_op_kwargs(call)4022 kwargs = self.parse_op_kwargs(call)
4023+ self._check_declared_types("set_validshape", call, args, kwargs, span)
4023 4024 
4024 if args and self.is_tile_group(args[0]):4025 if args and self.is_tile_group(args[0]):
4025 group_var = args[0]4026 group_var = args[0]
@@ -4110,6 +4111,7 @@ def _parse_matmul(self, call: ast.Call) -> Expr:
4110 span = self.span_tracker.get_span(call)4111 span = self.span_tracker.get_span(call)
4111 args = [self.parse_expression(arg) for arg in call.args]4112 args = [self.parse_expression(arg) for arg in call.args]
4112 kwargs = self.parse_op_kwargs(call)4113 kwargs = self.parse_op_kwargs(call)
4114+ self._check_declared_types("matmul", call, args, kwargs, span)
4113 if len(args) == 4:4115 if len(args) == 4:
4114 return _ir_matmul_bias(*args, **kwargs, span=span)4116 return _ir_matmul_bias(*args, **kwargs, span=span)
4115 return _ir_matmul(*args, **kwargs, span=span)4117 return _ir_matmul(*args, **kwargs, span=span)
@@ -4120,6 +4122,7 @@ def _parse_matmul_acc(self, call: ast.Call) -> Expr:
4120 span = self.span_tracker.get_span(call)4122 span = self.span_tracker.get_span(call)
4121 args = [self.parse_expression(arg) for arg in call.args]4123 args = [self.parse_expression(arg) for arg in call.args]
4122 kwargs = self.parse_op_kwargs(call)4124 kwargs = self.parse_op_kwargs(call)
4125+ self._check_declared_types("matmul_acc", call, args, kwargs, span)
4123 return _ir_matmul_acc(*args, **kwargs, span=span)4126 return _ir_matmul_acc(*args, **kwargs, span=span)
4124 4127 
4125 4128 
@@ -4269,6 +4272,7 @@ def _parse_matmul_mx(self, call: ast.Call) -> Expr:
4269 span = self.span_tracker.get_span(call)4272 span = self.span_tracker.get_span(call)
4270 args = [self.parse_expression(arg) for arg in call.args]4273 args = [self.parse_expression(arg) for arg in call.args]
4271 kwargs = self.parse_op_kwargs(call)4274 kwargs = self.parse_op_kwargs(call)
4275+ self._check_declared_types("matmul_mx", call, args, kwargs, span)
4272 return _ir_matmul_mx(*args, **kwargs, span=span)4276 return _ir_matmul_mx(*args, **kwargs, span=span)
4273 4277 
4274 4278 
@@ -4277,6 +4281,7 @@ def _parse_matmul_mx_acc(self, call: ast.Call) -> Expr:
4277 span = self.span_tracker.get_span(call)4281 span = self.span_tracker.get_span(call)
4278 args = [self.parse_expression(arg) for arg in call.args]4282 args = [self.parse_expression(arg) for arg in call.args]
4279 kwargs = self.parse_op_kwargs(call)4283 kwargs = self.parse_op_kwargs(call)
4284+ self._check_declared_types("matmul_mx_acc", call, args, kwargs, span)
4280 return _ir_matmul_mx_acc(*args, **kwargs, span=span)4285 return _ir_matmul_mx_acc(*args, **kwargs, span=span)
4281 4286 
4282 4287 
@@ -4343,6 +4348,7 @@ def _parse_get_saturation_flag(self, call: ast.Call) -> Expr:
4343def _parse_set_ctrl_spr(self, call: ast.Call) -> Expr:4348def _parse_set_ctrl_spr(self, call: ast.Call) -> Expr:
4344 span = self.span_tracker.get_span(call)4349 span = self.span_tracker.get_span(call)
4345 args = [self.parse_expression(arg) for arg in call.args]4350 args = [self.parse_expression(arg) for arg in call.args]
4351+ self._check_declared_types("set_ctrl_spr", call, args, {}, span)
4346 return _ir_set_ctrl_spr(*args, span=span)4352 return _ir_set_ctrl_spr(*args, span=span)
4347 4353 
4348 4354 
@@ -4350,6 +4356,7 @@ def _parse_set_ctrl_spr(self, call: ast.Call) -> Expr:
4350def _parse_get_ctrl_spr(self, call: ast.Call) -> Expr:4356def _parse_get_ctrl_spr(self, call: ast.Call) -> Expr:
4351 span = self.span_tracker.get_span(call)4357 span = self.span_tracker.get_span(call)
4352 args = [self.parse_expression(arg) for arg in call.args]4358 args = [self.parse_expression(arg) for arg in call.args]
4359+ self._check_declared_types("get_ctrl_spr", call, args, {}, span)
4353 return _ir_get_ctrl_spr(*args, span=span)4360 return _ir_get_ctrl_spr(*args, span=span)
4354 4361 
4355 4362 
@@ -4357,4 +4364,5 @@ def _parse_get_ctrl_spr(self, call: ast.Call) -> Expr:
4357def _parse_reset_ctrl_spr(self, call: ast.Call) -> Expr:4364def _parse_reset_ctrl_spr(self, call: ast.Call) -> Expr:
4358 span = self.span_tracker.get_span(call)4365 span = self.span_tracker.get_span(call)
4359 args = [self.parse_expression(arg) for arg in call.args]4366 args = [self.parse_expression(arg) for arg in call.args]
4367+ self._check_declared_types("reset_ctrl_spr", call, args, {}, span)
4360 return _ir_reset_ctrl_spr(*args, span=span)4368 return _ir_reset_ctrl_spr(*args, span=span)
@@ -506,6 +506,7 @@ def _parse_dump_data(self, call: ast.Call):
506 span = self.span_tracker.get_span(call)506 span = self.span_tracker.get_span(call)
507 args = [self.parse_expression(a) for a in call.args]507 args = [self.parse_expression(a) for a in call.args]
508 kwargs = self.parse_op_kwargs(call)508 kwargs = self.parse_op_kwargs(call)
509+ self._check_declared_types("dump_data", call, args, kwargs, span)
509 return dump_data(*args, section=self.target, **kwargs, span=span)510 return dump_data(*args, section=self.target, **kwargs, span=span)
510 511 
511 512 
@@ -514,5 +515,6 @@ def _parse_pto_assert(self, call: ast.Call):
514 span = self.span_tracker.get_span(call)515 span = self.span_tracker.get_span(call)
515 args = [self.parse_expression(a) for a in call.args]516 args = [self.parse_expression(a) for a in call.args]
516 kwargs = self.parse_op_kwargs(call)517 kwargs = self.parse_op_kwargs(call)
518+ self._check_declared_types("pto_assert", call, args, kwargs, span)
517 condition_text = self.span_tracker.get_source_text(call.args[0])519 condition_text = self.span_tracker.get_source_text(call.args[0])
518 return pto_assert(*args, condition_text=condition_text, **kwargs, span=span)520 return pto_assert(*args, condition_text=condition_text, **kwargs, span=span)
@@ -33,6 +33,7 @@ def _parse_min(self, call: ast.Call):
33 )33 )
34 lhs = self.parse_expression(call.args[0])34 lhs = self.parse_expression(call.args[0])
35 rhs = self.parse_expression(call.args[1])35 rhs = self.parse_expression(call.args[1])
36+ self._check_declared_types("min", call, [lhs, rhs], {}, call_span)
36 operation = _ir_core.min_(lhs, rhs, call_span)37 operation = _ir_core.min_(lhs, rhs, call_span)
37 folded = self._fold_const_binop("min", operation, call_span)38 folded = self._fold_const_binop("min", operation, call_span)
38 return folded if folded is not None else operation39 return folded if folded is not None else operation
@@ -51,6 +52,7 @@ def _parse_max(self, call: ast.Call):
51 )52 )
52 lhs = self.parse_expression(call.args[0])53 lhs = self.parse_expression(call.args[0])
53 rhs = self.parse_expression(call.args[1])54 rhs = self.parse_expression(call.args[1])
55+ self._check_declared_types("max", call, [lhs, rhs], {}, call_span)
54 operation = _ir_core.max_(lhs, rhs, call_span)56 operation = _ir_core.max_(lhs, rhs, call_span)
55 folded = self._fold_const_binop("max", operation, call_span)57 folded = self._fold_const_binop("max", operation, call_span)
56 return folded if folded is not None else operation58 return folded if folded is not None else operation
@@ -569,6 +569,7 @@ register_table(
569def _parse_system_sync(self, call: ast.Call, op_name: str):569def _parse_system_sync(self, call: ast.Call, op_name: str):
570 span = self.span_tracker.get_span(call)570 span = self.span_tracker.get_span(call)
571 kwargs = self.parse_op_kwargs(call)571 kwargs = self.parse_op_kwargs(call)
572+ self._check_declared_types(op_name, call, [], kwargs, span)
572 _validate_sync_pipes(kwargs["set_pipe"], kwargs["wait_pipe"], self.target, span)573 _validate_sync_pipes(kwargs["set_pipe"], kwargs["wait_pipe"], self.target, span)
573 return _create_sync_op(op_name, **kwargs, span=span)574 return _create_sync_op(op_name, **kwargs, span=span)
574 575 
@@ -589,6 +590,7 @@ def _parse_system_sync_all(self, call: ast.Call):
589 if call.args:590 if call.args:
590 raise InvalidArgument("sync_all does not accept positional arguments", span=span)591 raise InvalidArgument("sync_all does not accept positional arguments", span=span)
591 kwargs = self.parse_op_kwargs(call)592 kwargs = self.parse_op_kwargs(call)
593+ self._check_declared_types("system.sync_all", call, [], kwargs, span)
592 return sync_all(**kwargs, span=span)594 return sync_all(**kwargs, span=span)
593 595 
594 596 
@@ -602,5 +604,6 @@ def _parse_system_set_mm_layout_transform(self, call: ast.Call):
602 "set_mm_layout_transform requires keyword argument 'enabled'",604 "set_mm_layout_transform requires keyword argument 'enabled'",
603 span=call_span,605 span=call_span,
604 )606 )
607+ self._check_declared_types("system.set_mm_layout_transform", call, [], kwargs, call_span)
605 enabled = bool(kwargs["enabled"])608 enabled = bool(kwargs["enabled"])
606 return set_mm_layout_transform(enabled=enabled, span=call_span)609 return set_mm_layout_transform(enabled=enabled, span=call_span)
@@ -267,11 +267,8 @@ from pypto.pypto_impl.ir import (
267 TensorLayout,267 TensorLayout,
268 TilePad,268 TilePad,
269)269)
270-from pypto_pro.ir.op import system_ops as system
271from pypto_pro.ir.op.block_ops import FillPadMode, TileType270from pypto_pro.ir.op.block_ops import FillPadMode, TileType
272from pypto_pro.ir.op.ptr_ops import addptr, make_ptr, make_tensor271from pypto_pro.ir.op.ptr_ops import addptr, make_ptr, make_tensor
273-from pypto_pro.ir.op.system_ops import mutex_lock as _mutex_lock
274-from pypto_pro.ir.op.system_ops import mutex_unlock as _mutex_unlock
275from pypto_pro.runtime import jit, pipeline272from pypto_pro.runtime import jit, pipeline
276 273 
277from . import parser274from . import parser
@@ -382,11 +379,14 @@ from ._api import (
382 xor,379 xor,
383)380)
384from ._simt_api import Simt as simt # noqa: N813381from ._simt_api import Simt as simt # noqa: N813
382+from ._system_api import System as system # noqa: N813
385from ._vf_api import Vf383from ._vf_api import Vf
386from .parser.decorator import inline, vector_function384from .parser.decorator import inline, vector_function
387from .typing import DYNAMIC, STATIC, Input, Output, Ptr, Scalar, Tensor385from .typing import DYNAMIC, STATIC, Input, Output, Ptr, Scalar, Tensor
388 386 
389-mutex = SimpleNamespace(mutex_lock=_mutex_lock, mutex_unlock=_mutex_unlock)387+# Legacy spelling of the two system mutex ops; the declarations are the same ones,
388+# so neither spelling exposes the framework-internal span parameter.
389+mutex = SimpleNamespace(mutex_lock=system.mutex_lock, mutex_unlock=system.mutex_unlock)
390 390 
391# Public frontend dtype constants follow the python/pypto DT_* spelling.391# Public frontend dtype constants follow the python/pypto DT_* spelling.
392DT_FP4 = DataType.FP4392DT_FP4 = DataType.FP4
@@ -44,7 +44,8 @@ from pypto.ir import (
44from pypto_pro.ir.op.block_ops import FillPadMode44from pypto_pro.ir.op.block_ops import FillPadMode
45 45 
46from .._errors import InvalidOperation46from .._errors import InvalidOperation
47-from . import TensorLayout47+from . import MemorySpace, TensorLayout, TilePad
48+from .typing import Ptr
48 49 
49# ---------------------------------------------------------------------------50# ---------------------------------------------------------------------------
50# User-facing type aliases (NOT IR types)51# User-facing type aliases (NOT IR types)
@@ -24,7 +24,7 @@ it. Outside a kernel, calling a declaration raises ``RuntimeError``.
24 24 
25from __future__ import annotations25from __future__ import annotations
26 26 
27-from typing import Any27+from typing import Any, Union
28 28 
29from pypto.ir import RoundMode29from pypto.ir import RoundMode
30 30 
@@ -98,7 +98,7 @@ class Simt:
98 @staticmethod98 @staticmethod
99 @_api_decl99 @_api_decl
100 def cast(100 def cast(
101- value: Scalar,101+ value: Union[int, float],
102 dtype: DType,102 dtype: DType,
103 *,103 *,
104 mode: RoundMode = RoundMode.CAST_NONE,104 mode: RoundMode = RoundMode.CAST_NONE,
@@ -113,7 +113,7 @@ class Simt:
113 113 
114 @staticmethod114 @staticmethod
115 @_api_decl115 @_api_decl
116- def bitcast(value: Scalar, dtype: DType) -> Scalar:116+ def bitcast(value: Union[int, float], dtype: DType) -> Scalar:
117 """Reinterpret one scalar bit pattern as a supported equal-width dtype.117 """Reinterpret one scalar bit pattern as a supported equal-width dtype.
118 118 
119 Unlike :meth:`cast`, this operation performs no numerical conversion,119 Unlike :meth:`cast`, this operation performs no numerical conversion,
@@ -123,117 +123,117 @@ class Simt:
123 123 
124 @staticmethod124 @staticmethod
125 @_api_decl125 @_api_decl
126- def abs(value: Scalar) -> Scalar:126+ def abs(value: Union[int, float]) -> Scalar:
127 """Return the absolute value of a FP16, BF16, FP32, or INT64 Scalar."""127 """Return the absolute value of a FP16, BF16, FP32, or INT64 Scalar."""
128 128 
129 @staticmethod129 @staticmethod
130 @_api_decl130 @_api_decl
131- def min(lhs: Scalar, rhs: Scalar) -> Scalar:131+ def min(lhs: Union[int, float], rhs: Union[int, float]) -> Scalar:
132 """Return the minimum of two same-dtype floating-point or integer Scalars."""132 """Return the minimum of two same-dtype floating-point or integer Scalars."""
133 133 
134 @staticmethod134 @staticmethod
135 @_api_decl135 @_api_decl
136- def max(lhs: Scalar, rhs: Scalar) -> Scalar:136+ def max(lhs: Union[int, float], rhs: Union[int, float]) -> Scalar:
137 """Return the maximum of two same-dtype floating-point or integer Scalars."""137 """Return the maximum of two same-dtype floating-point or integer Scalars."""
138 138 
139 @staticmethod139 @staticmethod
140 @_api_decl140 @_api_decl
141- def sqrt(value: Scalar) -> Scalar:141+ def sqrt(value: Union[int, float]) -> Scalar:
142 """Return the square root of a FP16, BF16, or FP32 Scalar."""142 """Return the square root of a FP16, BF16, or FP32 Scalar."""
143 143 
144 @staticmethod144 @staticmethod
145 @_api_decl145 @_api_decl
146- def rsqrt(value: Scalar) -> Scalar:146+ def rsqrt(value: Union[int, float]) -> Scalar:
147 """Return the reciprocal square root of a FP16, BF16, or FP32 Scalar."""147 """Return the reciprocal square root of a FP16, BF16, or FP32 Scalar."""
148 148 
149 @staticmethod149 @staticmethod
150 @_api_decl150 @_api_decl
151- def exp(value: Scalar) -> Scalar:151+ def exp(value: Union[int, float]) -> Scalar:
152 """Return e raised to a FP16, BF16, or FP32 Scalar."""152 """Return e raised to a FP16, BF16, or FP32 Scalar."""
153 153 
154 @staticmethod154 @staticmethod
155 @_api_decl155 @_api_decl
156- def exp2(value: Scalar) -> Scalar:156+ def exp2(value: Union[int, float]) -> Scalar:
157 """Return two raised to a FP16, BF16, or FP32 Scalar."""157 """Return two raised to a FP16, BF16, or FP32 Scalar."""
158 158 
159 @staticmethod159 @staticmethod
160 @_api_decl160 @_api_decl
161- def log(value: Scalar) -> Scalar:161+ def log(value: Union[int, float]) -> Scalar:
162 """Return the natural logarithm of a FP16, BF16, or FP32 Scalar."""162 """Return the natural logarithm of a FP16, BF16, or FP32 Scalar."""
163 163 
164 @staticmethod164 @staticmethod
165 @_api_decl165 @_api_decl
166- def log2(value: Scalar) -> Scalar:166+ def log2(value: Union[int, float]) -> Scalar:
167 """Return the base-two logarithm of a FP16, BF16, or FP32 Scalar."""167 """Return the base-two logarithm of a FP16, BF16, or FP32 Scalar."""
168 168 
169 @staticmethod169 @staticmethod
170 @_api_decl170 @_api_decl
171- def log1p(value: Scalar) -> Scalar:171+ def log1p(value: Union[int, float]) -> Scalar:
172 """Return the FP32 natural logarithm of one plus ``value``."""172 """Return the FP32 natural logarithm of one plus ``value``."""
173 173 
174 @staticmethod174 @staticmethod
175 @_api_decl175 @_api_decl
176- def sin(value: Scalar) -> Scalar:176+ def sin(value: Union[int, float]) -> Scalar:
177 """Return the sine of a FP16, BF16, or FP32 Scalar."""177 """Return the sine of a FP16, BF16, or FP32 Scalar."""
178 178 
179 @staticmethod179 @staticmethod
180 @_api_decl180 @_api_decl
181- def cos(value: Scalar) -> Scalar:181+ def cos(value: Union[int, float]) -> Scalar:
182 """Return the cosine of a FP16, BF16, or FP32 Scalar."""182 """Return the cosine of a FP16, BF16, or FP32 Scalar."""
183 183 
184 @staticmethod184 @staticmethod
185 @_api_decl185 @_api_decl
186- def tanh(value: Scalar) -> Scalar:186+ def tanh(value: Union[int, float]) -> Scalar:
187 """Return the hyperbolic tangent of a FP16, BF16, or FP32 Scalar."""187 """Return the hyperbolic tangent of a FP16, BF16, or FP32 Scalar."""
188 188 
189 @staticmethod189 @staticmethod
190 @_api_decl190 @_api_decl
191- def rint(value: Scalar) -> Scalar:191+ def rint(value: Union[int, float]) -> Scalar:
192 """Round a floating-point Scalar to the nearest integer value."""192 """Round a floating-point Scalar to the nearest integer value."""
193 193 
194 @staticmethod194 @staticmethod
195 @_api_decl195 @_api_decl
196- def round(value: Scalar) -> Scalar:196+ def round(value: Union[int, float]) -> Scalar:
197 """Round a floating-point Scalar halfway away from zero."""197 """Round a floating-point Scalar halfway away from zero."""
198 198 
199 @staticmethod199 @staticmethod
200 @_api_decl200 @_api_decl
201- def floor(value: Scalar) -> Scalar:201+ def floor(value: Union[int, float]) -> Scalar:
202 """Round a floating-point Scalar down to an integer value."""202 """Round a floating-point Scalar down to an integer value."""
203 203 
204 @staticmethod204 @staticmethod
205 @_api_decl205 @_api_decl
206- def ceil(value: Scalar) -> Scalar:206+ def ceil(value: Union[int, float]) -> Scalar:
207 """Round a floating-point Scalar up to an integer value."""207 """Round a floating-point Scalar up to an integer value."""
208 208 
209 @staticmethod209 @staticmethod
210 @_api_decl210 @_api_decl
211- def trunc(value: Scalar) -> Scalar:211+ def trunc(value: Union[int, float]) -> Scalar:
212 """Round a floating-point Scalar toward zero to an integer value."""212 """Round a floating-point Scalar toward zero to an integer value."""
213 213 
214 @staticmethod214 @staticmethod
215 @_api_decl215 @_api_decl
216- def isnan(value: Scalar) -> Scalar:216+ def isnan(value: Union[int, float]) -> Scalar:
217 """Return a BOOL Scalar indicating whether a floating-point Scalar is NaN."""217 """Return a BOOL Scalar indicating whether a floating-point Scalar is NaN."""
218 218 
219 @staticmethod219 @staticmethod
220 @_api_decl220 @_api_decl
221- def isinf(value: Scalar) -> Scalar:221+ def isinf(value: Union[int, float]) -> Scalar:
222 """Return a BOOL Scalar indicating whether a floating-point Scalar is infinite."""222 """Return a BOOL Scalar indicating whether a floating-point Scalar is infinite."""
223 223 
224 @staticmethod224 @staticmethod
225 @_api_decl225 @_api_decl
226- def isfinite(value: Scalar) -> Scalar:226+ def isfinite(value: Union[int, float]) -> Scalar:
227 """Test whether an FP16 or FP32 Scalar is finite, returning BOOL."""227 """Test whether an FP16 or FP32 Scalar is finite, returning BOOL."""
228 228 
229 @staticmethod229 @staticmethod
230 @_api_decl230 @_api_decl
231- def popcount(value: Scalar) -> Scalar:231+ def popcount(value: Union[int, float]) -> Scalar:
232 """Count the set bits in a UINT32 or UINT64 Scalar, returning INT32."""232 """Count the set bits in a UINT32 or UINT64 Scalar, returning INT32."""
233 233 
234 @staticmethod234 @staticmethod
235 @_api_decl235 @_api_decl
236- def mul_hi(lhs: Scalar, rhs: Scalar) -> Scalar:236+ def mul_hi(lhs: Union[int, float], rhs: Union[int, float]) -> Scalar:
237 """Return the high half of the full product of two same-dtype integers.237 """Return the high half of the full product of two same-dtype integers.
238 238 
239 Supports INT32, UINT32, INT64, and UINT64; the result has the input dtype.239 Supports INT32, UINT32, INT64, and UINT64; the result has the input dtype.
@@ -241,7 +241,7 @@ class Simt:
241 241 
242 @staticmethod242 @staticmethod
243 @_api_decl243 @_api_decl
244- def fmod(lhs: Scalar, rhs: Scalar) -> Scalar:244+ def fmod(lhs: Union[int, float], rhs: Union[int, float]) -> Scalar:
245 """Return the FP32 remainder with a quotient truncated toward zero.245 """Return the FP32 remainder with a quotient truncated toward zero.
246 246 
247 Both operands must be FP32. The result retains the dividend's sign,247 Both operands must be FP32. The result retains the dividend's sign,
@@ -251,12 +251,12 @@ class Simt:
251 251 
252 @staticmethod252 @staticmethod
253 @_api_decl253 @_api_decl
254- def fma(lhs: Scalar, rhs: Scalar, addend: Scalar) -> Scalar:254+ def fma(lhs: Union[int, float], rhs: Union[int, float], addend: Union[int, float]) -> Scalar:
255 """Fused-multiply-add three same-dtype FP16, BF16, or FP32 Scalars."""255 """Fused-multiply-add three same-dtype FP16, BF16, or FP32 Scalars."""
256 256 
257 @staticmethod257 @staticmethod
258 @_api_decl258 @_api_decl
259- def atomic_add(target: Scalar, value: Scalar) -> Scalar | None:259+ def atomic_add(target: Union[int, float], value: Union[int, float]) -> Scalar | None:
260 """Atomically add ``value`` to one Tile or Tensor element.260 """Atomically add ``value`` to one Tile or Tensor element.
261 261 
262 ``target`` must be written directly as a subscript expression such as262 ``target`` must be written directly as a subscript expression such as
@@ -266,50 +266,50 @@ class Simt:
266 266 
267 @staticmethod267 @staticmethod
268 @_api_decl268 @_api_decl
269- def atomic_sub(target: Scalar, value: Scalar) -> Scalar:269+ def atomic_sub(target: Union[int, float], value: Union[int, float]) -> Scalar:
270 """Atomically subtract ``value`` from one Tile or Tensor element and return its old value."""270 """Atomically subtract ``value`` from one Tile or Tensor element and return its old value."""
271 271 
272 @staticmethod272 @staticmethod
273 @_api_decl273 @_api_decl
274- def atomic_exch(target: Scalar, value: Scalar) -> Scalar:274+ def atomic_exch(target: Union[int, float], value: Union[int, float]) -> Scalar:
275 """Atomically replace one Tile or Tensor element and return its old value."""275 """Atomically replace one Tile or Tensor element and return its old value."""
276 276 
277 @staticmethod277 @staticmethod
278 @_api_decl278 @_api_decl
279- def atomic_max(target: Scalar, value: Scalar) -> Scalar | None:279+ def atomic_max(target: Union[int, float], value: Union[int, float]) -> Scalar | None:
280 """Atomically update an element with its maximum; FP16/BF16 return no value."""280 """Atomically update an element with its maximum; FP16/BF16 return no value."""
281 281 
282 @staticmethod282 @staticmethod
283 @_api_decl283 @_api_decl
284- def atomic_min(target: Scalar, value: Scalar) -> Scalar | None:284+ def atomic_min(target: Union[int, float], value: Union[int, float]) -> Scalar | None:
285 """Atomically update an element with its minimum; FP16/BF16 return no value."""285 """Atomically update an element with its minimum; FP16/BF16 return no value."""
286 286 
287 @staticmethod287 @staticmethod
288 @_api_decl288 @_api_decl
289- def atomic_inc(target: Scalar, limit: Scalar) -> Scalar:289+ def atomic_inc(target: Union[int, float], limit: Union[int, float]) -> Scalar:
290 """Atomically increment and wrap one unsigned counter element, returning its old value."""290 """Atomically increment and wrap one unsigned counter element, returning its old value."""
291 291 
292 @staticmethod292 @staticmethod
293 @_api_decl293 @_api_decl
294- def atomic_dec(target: Scalar, limit: Scalar) -> Scalar:294+ def atomic_dec(target: Union[int, float], limit: Union[int, float]) -> Scalar:
295 """Atomically decrement and wrap one unsigned counter element, returning its old value."""295 """Atomically decrement and wrap one unsigned counter element, returning its old value."""
296 296 
297 @staticmethod297 @staticmethod
298 @_api_decl298 @_api_decl
299- def atomic_cas(target: Scalar, compare: Scalar, value: Scalar) -> Scalar:299+ def atomic_cas(target: Union[int, float], compare: Union[int, float], value: Union[int, float]) -> Scalar:
300 """Atomically compare and exchange one Tile or Tensor element, returning its old value."""300 """Atomically compare and exchange one Tile or Tensor element, returning its old value."""
301 301 
302 @staticmethod302 @staticmethod
303 @_api_decl303 @_api_decl
304- def atomic_and(target: Scalar, value: Scalar) -> Scalar:304+ def atomic_and(target: Union[int, float], value: Union[int, float]) -> Scalar:
305 """Atomically apply bitwise AND to one Tile or Tensor element and return its old value."""305 """Atomically apply bitwise AND to one Tile or Tensor element and return its old value."""
306 306 
307 @staticmethod307 @staticmethod
308 @_api_decl308 @_api_decl
309- def atomic_or(target: Scalar, value: Scalar) -> Scalar:309+ def atomic_or(target: Union[int, float], value: Union[int, float]) -> Scalar:
310 """Atomically apply bitwise OR to one Tile or Tensor element and return its old value."""310 """Atomically apply bitwise OR to one Tile or Tensor element and return its old value."""
311 311 
312 @staticmethod312 @staticmethod
313 @_api_decl313 @_api_decl
314- def atomic_xor(target: Scalar, value: Scalar) -> Scalar:314+ def atomic_xor(target: Union[int, float], value: Union[int, float]) -> Scalar:
315 """Atomically apply bitwise XOR to one Tile or Tensor element and return its old value."""315 """Atomically apply bitwise XOR to one Tile or Tensor element and return its old value."""
@@ -0,0 +1,221 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+ 
12+"""Python API declarations for the PyPTO Pro system namespace (``pl.system.*``).
13+ 
14+These declarations exist so that:
15+- IDE "Go to Definition" works for every ``pl.system.xxx`` call
16+- Python catches typos at import time
17+- Type checkers can validate argument types
18+- Docstrings document the user-facing calling convention
19+ 
20+None of these functions are meant to be called at runtime. Inside a PyPTO
21+kernel the AST parser intercepts every ``pl.system.xxx`` call before Python
22+executes it. Outside a kernel, calling a declaration raises ``InvalidOperation``.
23+ 
24+The ``span`` parameter every implementation in ``ir/op/system_ops.py`` carries is
25+absent here: the parser captures the source location itself, so it is not part of
26+what a user writes.
27+"""
28+ 
29+from __future__ import annotations
30+ 
31+from typing import List, Optional, Union
32+ 
33+from pypto.ir import CacheLine, CrossCoreSyncMode, DcciDst, PipeType, SyncCoreType
34+ 
35+from ._api import Tensor, Tile, _api_decl
36+ 
37+ 
38+class System:
39+ """System namespace (``pl.system.*``).
40+ 
41+ Provides pipeline barriers, intra- and cross-core synchronization, mutex
42+ tokens, cache maintenance, and matmul layout control.
43+ """
44+ 
45+ # -----------------------------------------------------------------
46+ # Pipeline barriers
47+ # -----------------------------------------------------------------
48+ 
49+ @staticmethod
50+ @_api_decl
51+ def bar_all() -> None:
52+ """Global barrier synchronization."""
53+ 
54+ @staticmethod
55+ @_api_decl
56+ def bar_m() -> None:
57+ """Matrix unit barrier."""
58+ 
59+ @staticmethod
60+ @_api_decl
61+ def bar_fix() -> None:
62+ """FIX pipeline barrier."""
63+ 
64+ @staticmethod
65+ @_api_decl
66+ def bar_mte1() -> None:
67+ """MTE1 pipeline barrier."""
68+ 
69+ @staticmethod
70+ @_api_decl
71+ def bar_mte2() -> None:
72+ """MTE2 pipeline barrier."""
73+ 
74+ @staticmethod
75+ @_api_decl
76+ def bar_mte3() -> None:
77+ """MTE3 pipeline barrier."""
78+ 
79+ # -----------------------------------------------------------------
80+ # Intra-core synchronization (flag set / wait)
81+ # -----------------------------------------------------------------
82+ 
83+ @staticmethod
84+ @_api_decl
85+ def sync_src(*, set_pipe: PipeType, wait_pipe: PipeType, event_id: int) -> None:
86+ """Send a synchronization signal (Set Flag).
87+ 
88+ Args:
89+ set_pipe: Pipe that sets the flag
90+ wait_pipe: Pipe that will wait on the flag
91+ event_id: Event identifier
92+ """
93+ 
94+ @staticmethod
95+ @_api_decl
96+ def sync_dst(*, set_pipe: PipeType, wait_pipe: PipeType, event_id: int) -> None:
97+ """Wait for a synchronization signal (Wait Flag).
98+ 
99+ Args:
100+ set_pipe: Pipe that sets the flag
101+ wait_pipe: Pipe that waits on the flag
102+ event_id: Event identifier
103+ """
104+ 
105+ # -----------------------------------------------------------------
106+ # Cross-core synchronization
107+ # -----------------------------------------------------------------
108+ 
109+ @staticmethod
110+ @_api_decl
111+ def set_cross_core(
112+ *,
113+ pipe: PipeType,
114+ event_id: int,
115+ sync_mode: CrossCoreSyncMode = CrossCoreSyncMode.INTRA_BLOCK,
116+ ) -> None:
117+ """Set a synchronization signal (cross core).
118+ 
119+ Args:
120+ pipe: Pipe that sets the flag
121+ event_id: Event identifier (int for static, Scalar expression for dynamic)
122+ sync_mode: Cross-core sync mode. ``pl.CrossCoreSyncMode.INTRA_BLOCK`` (default,
123+ mode 2) for AIC-AIV both subcores, ``UNICAST_BLOCK`` (mode 3) for AIC-AIV one
124+ subcore, ``INTER_BLOCK`` (mode 0) for inter-core, ``INTER_SUBBLOCK`` (mode 1)
125+ for AIV-to-AIV.
126+ """
127+ 
128+ @staticmethod
129+ @_api_decl
130+ def wait_cross_core(
131+ *,
132+ pipe: PipeType,
133+ event_id: int,
134+ sync_mode: CrossCoreSyncMode = CrossCoreSyncMode.INTRA_BLOCK,
135+ ) -> None:
136+ """Wait for a synchronization signal (cross core).
137+ 
138+ Args:
139+ pipe: Pipe that waits on the flag
140+ event_id: Event identifier (int for static, Scalar expression for dynamic)
141+ sync_mode: Cross-core sync mode. Must match the paired ``set_cross_core``.
142+ """
143+ 
144+ @staticmethod
145+ @_api_decl
146+ def sync_all(*, core_type: SyncCoreType = SyncCoreType.MIX) -> None:
147+ """Global core synchronization (delegates to pto-isa SYNCALL).
148+ 
149+ Uses the FFTS hardware signal and needs no workspace.
150+ 
151+ Args:
152+ core_type: Which cores participate. ``pl.SyncCoreType.AIV_ONLY`` syncs
153+ vector cores only, ``MIX`` (default) syncs both AIC and AIV cores.
154+ """
155+ 
156+ # -----------------------------------------------------------------
157+ # Mutex buffer-id tokens
158+ # -----------------------------------------------------------------
159+ 
160+ @staticmethod
161+ @_api_decl
162+ def mutex_lock(*, pipe: PipeType, mutex_id: int) -> None:
163+ """Acquire a Mutex buffer-id token on ``pipe``.
164+ 
165+ Blocks the ``pipe`` instruction queue until the previous holder of
166+ ``mutex_id`` releases it via ``mutex_unlock``.
167+ 
168+ Args:
169+ pipe: PipeType for which to acquire the lock (e.g. ``pl.PipeType.MTE2``)
170+ mutex_id: MutexID 0-31, as an int or an integer scalar expression
171+ """
172+ 
173+ @staticmethod
174+ @_api_decl
175+ def mutex_unlock(*, pipe: PipeType, mutex_id: int) -> None:
176+ """Release a Mutex buffer-id token previously acquired on ``pipe``.
177+ 
178+ Must be paired with ``mutex_lock`` on the same ``pipe`` and ``mutex_id``.
179+ 
180+ Args:
181+ pipe: PipeType for which to release the lock
182+ mutex_id: MutexID passed to the paired ``mutex_lock``
183+ """
184+ 
185+ # -----------------------------------------------------------------
186+ # Cache maintenance and matmul layout
187+ # -----------------------------------------------------------------
188+ 
189+ @staticmethod
190+ @_api_decl
191+ def dcci(
192+ target: Union[Tensor, Tile],
193+ offset: Optional[Union[int, List[int]]] = None,
194+ *,
195+ cache_line: CacheLine = CacheLine.ENTIRE_DATA_CACHE,
196+ dst: DcciDst = DcciDst.AUTO,
197+ ) -> None:
198+ """Data Cache Clean and Invalid for a GM Tensor or a UB Tile.
199+ 
200+ Args:
201+ target: GM Tensor or UB Tile
202+ offset: A Tensor target takes per-dimension offsets or a scalar element
203+ offset; a Tile target takes a scalar element offset. Omitted, the
204+ target base address is used.
205+ cache_line: ``pl.CacheLine.SINGLE_CACHE_LINE`` or ``ENTIRE_DATA_CACHE``
206+ dst: DCCI destination. ``pl.DcciDst.AUTO`` maps a Tensor to CACHELINE_OUT
207+ and a Tile to CACHELINE_UB.
208+ """
209+ 
210+ @staticmethod
211+ @_api_decl
212+ def set_mm_layout_transform(*, enabled: bool) -> None:
213+ """Set the matmul layout transform mode for the fixpipe drain direction.
214+ 
215+ When enabled, fixpipe drains L0C in the N direction (column-first) instead of
216+ the M direction (row-first), so cube and fixpipe access L0C along orthogonal
217+ axes within one slot.
218+ 
219+ Args:
220+ enabled: True to enable N-direction drain, False to restore M-direction
221+ """
@@ -0,0 +1,421 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+# CANN Open Software License Agreement Version 2.0 (the "License").
4+# Please refer to the License for details. You may not use this file except in compliance with the License.
5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+# See LICENSE in the root of the software repository for the full text of the License.
8+# -----------------------------------------------------------------------------------------------------------
9+ 
10+"""The two gates a gated call passes before its builder sees it.
11+ 
12+Both read the same source of truth, the ``@_api_decl`` declarations, and differ in
13+when they run. ``check_declared_params`` runs before any argument is evaluated and
14+settles which parameters the call names and how many it passes, which is all its
15+written form can answer. ``check_declared_types`` runs after, on the parsed values,
16+and settles what each one turned out to be.
17+Whether a value is *legal* -- a dtype off the whitelist, two shapes that disagree --
18+is neither gate's business and stays in the builders.
19+ 
20+A role is read from an annotation as it is *written*, never as typing resolves it:
21+the user-facing aliases in ``language/_api.py`` are all ``Any``, so the resolved form
22+says nothing. Anything a role does not describe is left alone -- an unannotated
23+parameter, ``Any``, a union with one unfamiliar branch -- because a role nobody wrote
24+down is not grounds to reject an argument the builder may well accept.
25+"""
26+ 
27+from __future__ import annotations
28+ 
29+import ast
30+import difflib
31+import inspect
32+import re
33+from typing import Any, Callable
34+ 
35+from pypto.pypto_impl import ir
36+ 
37+from ..._errors import InvalidArgument, InvalidType
38+from .. import _api as _language_api
39+from .. import _simt_api, _system_api
40+from .._vf_api import Vf
41+ 
42+# Where each gated namespace keeps its declarations. A call written without one --
43+# pl.add(...) -- is declared at the top level; a namespace this table does not name,
44+# such as the legacy mutex.*, is not gated at all.
45+_TOP_LEVEL_DECLARATIONS = _language_api
46+_NAMESPACE_DECLARATIONS = {
47+ "simt": _simt_api.Simt,
48+ "system": _system_api.System,
49+ "vf": Vf,
50+}
51+ 
52+ 
53+def spelled(op_name: str) -> str:
54+ """The op as a user writes it: vf.* is imported on its own, the rest hang off pl."""
55+ return op_name if op_name.startswith("vf.") else f"pl.{op_name}"
56+ 
57+ 
58+def declared_api(op_name: str) -> Callable | None:
59+ """The ``@_api_decl`` declaration for *op_name*, or None when it has none.
60+ 
61+ Coverage follows the declaration files rather than ``_OP_REGISTRY``: ``exp``,
62+ ``sqrt`` and ``gather`` are declared but dispatch through
63+ ``_parse_block_default``.
64+ """
65+ namespace, _, attribute = op_name.rpartition(".")
66+ declarations = _NAMESPACE_DECLARATIONS.get(namespace) if namespace else _TOP_LEVEL_DECLARATIONS
67+ if declarations is None:
68+ return None
69+ declared = getattr(declarations, attribute, None)
70+ return declared if getattr(declared, "__wrapped__", None) is not None else None
71+ 
72+ 
73+def _required_form(op_name: str, signature: inspect.Signature) -> str:
74+ """The shortest call the declaration accepts, keyword-only parameters included."""
75+ required: list[str] = []
76+ for name, parameter in signature.parameters.items():
77+ if parameter.default is not inspect.Parameter.empty:
78+ continue
79+ if parameter.kind in (parameter.POSITIONAL_ONLY, parameter.POSITIONAL_OR_KEYWORD):
80+ required.append(name)
81+ elif parameter.kind is parameter.KEYWORD_ONLY:
82+ required.append(f"{name}=...")
83+ return f"{spelled(op_name)}({', '.join(required)})"
84+ 
85+ 
86+def _keyword_names(signature: inspect.Signature) -> list[str]:
87+ """Every parameter a caller may name."""
88+ return [
89+ name
90+ for name, parameter in signature.parameters.items()
91+ if parameter.kind in (parameter.POSITIONAL_OR_KEYWORD, parameter.KEYWORD_ONLY)
92+ ]
93+ 
94+ 
95+# ---------------------------------------------------------------------------
96+# Gate 1 -- parameter names and counts, before any argument is evaluated
97+# ---------------------------------------------------------------------------
98+ 
99+ 
100+def check_declared_params(op_name: str, call: ast.Call, span: ir.Span, span_tracker: Any) -> None:
101+ """Bind the call's parameters to its declaration, before any argument is parsed.
102+ 
103+ The rule is the declaration's own binding; only the written form is supplied --
104+ one placeholder per positional argument, the written name for each keyword --
105+ so nothing is evaluated. Callers run this after the execution-domain check, which
106+ reports a call from the wrong domain first, and after receiver-method routing,
107+ whose names no declaration covers.
108+ """
109+ declared = declared_api(op_name)
110+ if declared is None:
111+ return
112+ if any(isinstance(argument, ast.Starred) for argument in call.args):
113+ return
114+ if any(keyword.arg is None for keyword in call.keywords):
115+ return
116+ try:
117+ # None stands in for every argument: binding counts positions and matches
118+ # names, and never looks at what it was handed.
119+ declared.bind_declared(*[None] * len(call.args), **{kw.arg: None for kw in call.keywords})
120+ except TypeError as error:
121+ _reject_declared_params(op_name, declared, call, span, span_tracker, error)
122+ 
123+ 
124+def _reject_declared_params(
125+ op_name: str,
126+ declared: Callable,
127+ call: ast.Call,
128+ span: ir.Span,
129+ span_tracker: Any,
130+ error: TypeError,
131+) -> None:
132+ """Re-raise what the binding rejected, marked at the argument that caused it.
133+ 
134+ The reason is quoted as the binding worded it; where to point is derived from
135+ the declared parameters, read only on the failing call.
136+ """
137+ signature = inspect.signature(declared)
138+ parameters = signature.parameters
139+ given = [keyword.arg for keyword in call.keywords]
140+ positional = [
141+ name
142+ for name, parameter in parameters.items()
143+ if parameter.kind in (parameter.POSITIONAL_ONLY, parameter.POSITIONAL_OR_KEYWORD)
144+ ]
145+ unexpected = [name for name in given if name not in parameters]
146+ duplicated = [name for name in positional[:len(call.args)] if name in given]
147+ positional_only = [name for name, parameter in parameters.items() if parameter.kind is parameter.POSITIONAL_ONLY]
148+ as_keyword = [name for name in given if name in positional_only]
149+ takes_var_positional = any(p.kind is p.VAR_POSITIONAL for p in parameters.values())
150+ 
151+ # Only the optional keyword-only parameters are worth naming: the required
152+ # ones already show up in the required form, written as ``name=...``.
153+ keyword_only = [
154+ name
155+ for name, parameter in parameters.items()
156+ if parameter.kind is parameter.KEYWORD_ONLY and parameter.default is not inspect.Parameter.empty
157+ ]
158+ reason = str(error)
159+ if unexpected:
160+ marked: str | int | None = unexpected[0]
161+ # Binding reports whichever fault it meets first, and a keyword nobody
162+ # declared usually reads as a required one missing. Name the keyword the
163+ # caller actually wrote, so the reason and the mark agree.
164+ reason = f"got an unexpected keyword argument '{marked}'"
165+ names = _keyword_names(signature)
166+ close = difflib.get_close_matches(marked, [n for n in names if n not in given], n=1)
167+ suggestion = f"did you mean '{close[0]}'? " if close else ""
168+ takes = ", ".join(names) if names else "no arguments"
169+ hint = f"{suggestion}{spelled(op_name)}() takes {takes}"
170+ elif duplicated:
171+ marked = duplicated[0]
172+ hint = f"'{marked}' is already given as positional argument {positional.index(marked) + 1}"
173+ elif as_keyword:
174+ # Naming a positional-only parameter is a fault of the name, and the binding
175+ # already words it; only where to point is left to decide.
176+ marked = as_keyword[0]
177+ hint = f"write it by position: {_required_form(op_name, signature)}"
178+ elif not takes_var_positional and len(call.args) > len(positional):
179+ marked = len(positional)
180+ hint = _required_form(op_name, signature)
181+ if keyword_only:
182+ hint += f"; {', '.join(keyword_only)} must be passed by keyword"
183+ else:
184+ # An argument the call never wrote: the call itself is the only location.
185+ marked = None
186+ hint = _required_form(op_name, signature)
187+ if marked is None:
188+ located = span
189+ elif isinstance(marked, str):
190+ # Both keyword faults are faults of the name, so the name is what is marked.
191+ located = span_tracker.call_keyword_name_span(call, marked, span)
192+ else:
193+ located = span_tracker.call_argument_span(call, marked, span)
194+ raise InvalidArgument(f"{spelled(op_name)}() {reason}", span=located, hint=hint) from error
195+ 
196+ 
197+# ---------------------------------------------------------------------------
198+# Gate 2 -- what each parsed argument turned out to be
199+# ---------------------------------------------------------------------------
200+ 
201+_NONE_TYPE = type(None)
202+ 
203+ 
204+# Every IR scalar shares one class, ScalarType, and carries what it really is in
205+# its dtype. A caller writing ``int`` means an integer, not "any scalar", so a
206+# scalar is described by its dtype family and these three stand for the families.
207+class _IntScalar:
208+ """An IR scalar whose dtype is an integer."""
209+ 
210+ 
211+class _FloatScalar:
212+ """An IR scalar whose dtype is a float."""
213+ 
214+ 
215+class _BoolScalar:
216+ """An IR scalar whose dtype is BOOL, which is neither integer nor float."""
217+ 
218+ 
219+# What each name written in a declaration accepts, as classes to match a value's
220+# kind against. A sequence, a scalar and an offset each have two shapes: a positional
221+# argument parses into an IR expression, while the same literal written as a keyword
222+# stays a Python value, because keywords take another route through the parser.
223+_LEAF_TYPES: dict[str, tuple[type, ...]] = {
224+ "Tile": (ir.TileType,),
225+ "Tensor": (ir.TensorType,),
226+ # A group handle lowers to a MakeTuple, so a group is a TupleType here; that
227+ # it is a group of tiles rather than a struct is the builder's to tell apart.
228+ "TileGroup": (ir.TileType, ir.TensorType, ir.TupleType),
229+ "Struct": (ir.TupleType,),
230+ "Ptr": (ir.PtrType,),
231+ # Every scalar, written as a literal or lowered to an IR value. A bool is one
232+ # of them: whether it is a legal value in a given position -- an event id, a
233+ # loop bound -- is the builder's judgement, not this gate's.
234+ "Scalar": (_IntScalar, _FloatScalar, _BoolScalar, int, float, bool),
235+ "Shape": (ir.TupleType, list, tuple),
236+ "Offset": (ir.TupleType, list, tuple, _IntScalar, int),
237+ # Python counts a bool as an int -- isinstance(True, int), min(True, 2) -- and
238+ # a declaration written in Python's own vocabulary says the same thing here.
239+ "int": (_IntScalar, _BoolScalar, int, bool),
240+ "float": (_FloatScalar, float),
241+ "bool": (_BoolScalar, bool),
242+ "str": (str,),
243+ "list": (ir.TupleType, list, tuple),
244+ "tuple": (ir.TupleType, list, tuple),
245+ "None": (_NONE_TYPE, ir.NoneType),
246+}
247+ 
248+# Names a declaration writes that do not match the class they stand for.
249+_CLASS_ALIASES = {"DType": "DataType"}
250+_UNCHECKED = {"Any", "object"}
251+_NOTHING = (_NONE_TYPE, ir.NoneType)
252+ 
253+_OPTIONAL_FORM = re.compile(r"^Optional\[(.*)\]$")
254+_UNION_FORM = re.compile(r"^Union\[(.*)\]$")
255+_SEQUENCE_FORM = re.compile(r"^(?:List|list|Sequence|tuple)\[.+\]$")
256+ 
257+ 
258+def _split_outside_brackets(text: str, separator: str) -> list[str]:
259+ """Split on *separator*, ignoring the ones nested inside square brackets."""
260+ parts: list[str] = []
261+ depth = 0
262+ current = ""
263+ for character in text:
264+ if character == "[":
265+ depth += 1
266+ elif character == "]":
267+ depth -= 1
268+ if character == separator and depth == 0:
269+ parts.append(current.strip())
270+ current = ""
271+ else:
272+ current += character
273+ parts.append(current.strip())
274+ return [part for part in parts if part]
275+ 
276+ 
277+def _named_class(name: str, declared: Callable) -> type | None:
278+ """The class a name stands for, resolved where the declaration was written.
279+ 
280+ Resolution follows Python's own rule -- the declaring module -- and falls back to
281+ the IR module, which is where a name an aliased declaration file never imported
282+ (``DType``) actually lives.
283+ """
284+ if name == "TileType":
285+ # The declaration module binds this name to the TileType declaration rather
286+ # than to the class a caller passes, and that class is the frontend's, which
287+ # is a different class from the IR type of the same name.
288+ from pypto_pro.ir.op.block_ops import TileType
289+ 
290+ return TileType
291+ wanted = _CLASS_ALIASES.get(name, name)
292+ written_in = getattr(declared, "__wrapped__", declared).__globals__
293+ for resolved in (written_in.get(wanted), getattr(ir, wanted, None)):
294+ if isinstance(resolved, type):
295+ return resolved
296+ return None
297+ 
298+ 
299+def _leaf_types(name: str, declared: Callable) -> tuple[type, ...] | None:
300+ if name in _UNCHECKED:
301+ return None
302+ if name in _LEAF_TYPES:
303+ return _LEAF_TYPES[name]
304+ if _SEQUENCE_FORM.match(name):
305+ # A sequence of anything is still a sequence; the element role is not checked.
306+ return _LEAF_TYPES["list"]
307+ named = _named_class(name, declared)
308+ return (named,) if named is not None else None
309+ 
310+ 
311+def accepted_types(annotation: str, declared: Callable) -> tuple[type, ...] | None:
312+ """The classes *annotation* accepts, or None when it names nothing worth checking.
313+ 
314+ A union accepts any of its branches, so the branches' classes are pooled. One
315+ unrecognised branch leaves the whole annotation unchecked.
316+ """
317+ text = annotation.strip().strip("'\"")
318+ if not text or text in _UNCHECKED:
319+ return None
320+ if _SEQUENCE_FORM.match(text):
321+ return _LEAF_TYPES["list"]
322+ optional = _OPTIONAL_FORM.match(text)
323+ if optional:
324+ inner = accepted_types(optional.group(1), declared)
325+ return None if inner is None else tuple(dict.fromkeys(inner + _NOTHING))
326+ union = _UNION_FORM.match(text)
327+ if union:
328+ branches = _split_outside_brackets(union.group(1), ",")
329+ elif "|" in text:
330+ branches = _split_outside_brackets(text, "|")
331+ else:
332+ branches = [text]
333+ pooled: tuple[type, ...] = ()
334+ for branch in branches:
335+ types = _leaf_types(branch, declared)
336+ if types is None:
337+ return None
338+ pooled += types
339+ return tuple(dict.fromkeys(pooled))
340+ 
341+ 
342+def _scalar_family(scalar_type: ir.ScalarType) -> type:
343+ """Which family an IR scalar's dtype belongs to."""
344+ dtype = scalar_type.dtype
345+ if dtype == ir.DataType.BOOL:
346+ return _BoolScalar
347+ return _IntScalar if dtype.is_int() else _FloatScalar
348+ 
349+ 
350+def value_kind(value: Any) -> type:
351+ """The one class that describes *value*, so it can be matched against a role.
352+ 
353+ An IR expression is described by its IR type, everything else by its own type.
354+ A scalar is described one level deeper, by its dtype family, because that is
355+ the distinction a declaration writing ``int`` or ``float`` is drawing.
356+ """
357+ if isinstance(value, ir.Expr):
358+ value_type = getattr(value, "type", None)
359+ if isinstance(value_type, ir.ScalarType):
360+ return _scalar_family(value_type)
361+ return type(value_type)
362+ return type(value)
363+ 
364+ 
365+def describe_value(value: Any) -> str:
366+ """The value's kind as a user would recognise it, not its Python repr."""
367+ if value is None:
368+ return "None"
369+ if isinstance(value, ir.Expr):
370+ value_type = getattr(value, "type", None)
371+ if isinstance(value_type, ir.ScalarType):
372+ # Naming the class would say ScalarType for every scalar alike; the
373+ # dtype is what tells the caller which one they actually wrote.
374+ return f"a {value_type.dtype} scalar"
375+ return type(value_type).__name__ if value_type is not None else "an expression"
376+ return type(value).__name__
377+ 
378+ 
379+def _written_as(call: ast.Call, name: str, signature: inspect.Signature) -> str | int:
380+ """Where *name* was written: its keyword, or the index of its positional slot."""
381+ if any(keyword.arg == name for keyword in call.keywords):
382+ return name
383+ positional = [
384+ parameter_name
385+ for parameter_name, parameter in signature.parameters.items()
386+ if parameter.kind in (parameter.POSITIONAL_ONLY, parameter.POSITIONAL_OR_KEYWORD)
387+ ]
388+ return positional.index(name) if name in positional else 0
389+ 
390+ 
391+def check_declared_types(
392+ op_name: str,
393+ call: ast.Call,
394+ args: list,
395+ kwargs: dict,
396+ span: ir.Span,
397+ span_tracker: Any,
398+) -> None:
399+ """Check every parsed argument of *call* against the role its declaration names."""
400+ declared = declared_api(op_name)
401+ if declared is None:
402+ return
403+ signature = inspect.signature(declared)
404+ try:
405+ bound = signature.bind(*args, **kwargs)
406+ except TypeError:
407+ return # the first gate already reported this, or the call is not gated
408+ for name, value in bound.arguments.items():
409+ parameter = signature.parameters[name]
410+ if parameter.kind in (parameter.VAR_POSITIONAL, parameter.VAR_KEYWORD):
411+ continue
412+ if parameter.annotation is inspect.Parameter.empty:
413+ continue
414+ allowed = accepted_types(str(parameter.annotation), declared)
415+ if allowed is None or value_kind(value) in allowed:
416+ continue
417+ marked = _written_as(call, name, signature)
418+ raise InvalidType(
419+ f"{spelled(op_name)}: {name} expects {parameter.annotation}, got {describe_value(value)}",
420+ span=span_tracker.call_argument_span(call, marked, span),
421+ )
@@ -153,6 +153,14 @@ class AssignmentParserMixin:
153 reg = vf.add(a, b, preg) → RegTensor reg; vf.add(reg, a, b, preg)153 reg = vf.add(a, b, preg) → RegTensor reg; vf.add(reg, a, b, preg)
154 reg_lo, reg_hi = vf.mull(a, b, preg) → RegTensor reg_lo, reg_hi; vf.mull(reg_lo, reg_hi, a, b, pred)154 reg_lo, reg_hi = vf.mull(a, b, preg) → RegTensor reg_lo, reg_hi; vf.mull(reg_lo, reg_hi, a, b, pred)
155 """155 """
156+ # This form never reaches parse_op_call, so it carries the declaration gate
157+ # itself. It runs on the call as written, before the dst args are inserted
158+ # and before any argument is parsed. The call is the location, not the whole
159+ # statement: the assignment target is not what the gate is rejecting.
160+ self._check_declared_params(
161+ f"vf.{vf_op_name}", stmt.value, self.span_tracker.get_span(stmt.value)
162+ )
163+ 
156 dst_count = self._get_vf_op_dst_count(vf_op_name)164 dst_count = self._get_vf_op_dst_count(vf_op_name)
157 165 
158 call = stmt.value # ast.Call166 call = stmt.value # ast.Call
@@ -21,7 +21,15 @@ from typing import Any
21from pypto.pypto_impl import ir21from pypto.pypto_impl import ir
22from pypto_pro.ir import IRBuilder22from pypto_pro.ir import IRBuilder
23 23 
24-from ..._errors import CommonInner, InvalidArgument, InvalidOperation, InvalidType, NotSupported, PyptoProError24+from ..._errors import (
25+ CommonInner,
26+ InvalidArgument,
27+ InvalidOperation,
28+ InvalidType,
29+ NotSupported,
30+ PyptoProError,
31+ current_span,
32+)
25from ..typing._tiling import get_tiling_fields, get_tiling_tuple_type, is_tiling_class33from ..typing._tiling import get_tiling_fields, get_tiling_tuple_type, is_tiling_class
26from ..typing.shape import _ShapePolicy34from ..typing.shape import _ShapePolicy
27from ._assignment_parser import AssignmentParserMixin35from ._assignment_parser import AssignmentParserMixin
@@ -36,6 +44,10 @@ from ._struct_parser import StructParserMixin
36from ._tuple_type_registry import TupleTypeRegistry44from ._tuple_type_registry import TupleTypeRegistry
37from ._type_resolver import TypeResolver45from ._type_resolver import TypeResolver
38 46 
47+# Statements whose span covers a whole indented suite rather than one line, so
48+# publishing it as the ambient location would underline the entire block.
49+_COMPOUND_STATEMENTS = (ast.For, ast.While, ast.If, ast.With, ast.Try, ast.FunctionDef)
50+ 
39 51 
40def _snake_visit_name(node: ast.AST) -> str:52def _snake_visit_name(node: ast.AST) -> str:
41 """Return the snake_case visitor handler for an AST node type."""53 """Return the snake_case visitor handler for an AST node type."""
@@ -466,7 +478,16 @@ class ASTParser(
466 stmt: AST statement node478 stmt: AST statement node
467 """479 """
468 self._current_node = stmt480 self._current_node = stmt
469- self._dispatch_statement(stmt)481+ # Publish where this statement was written, for anything raised below that
482+ # passed no span of its own. A compound statement is excluded: its span
483+ # covers the whole suite, so an error from deep inside the body would
484+ # underline screenfuls of unrelated code. Their headers already build an
485+ # explicit span, and the statements in their bodies come back through here.
486+ if isinstance(stmt, _COMPOUND_STATEMENTS):
487+ self._dispatch_statement(stmt)
488+ return
489+ with current_span(self.span_tracker.get_span(stmt)):
490+ self._dispatch_statement(stmt)
470 491 
471 @singledispatchmethod492 @singledispatchmethod
472 def _dispatch_statement(self, stmt: ast.stmt) -> None:493 def _dispatch_statement(self, stmt: ast.stmt) -> None:
@@ -29,6 +29,7 @@ from pypto_pro.ir.op.block_ops import block_ir_op
29from ..._errors import BadFd, InvalidArgument, InvalidOperation, InvalidShape, InvalidType, InvalidVal, NotSupported29from ..._errors import BadFd, InvalidArgument, InvalidOperation, InvalidShape, InvalidType, InvalidVal, NotSupported
30from .. import _api as _language_api30from .. import _api as _language_api
31from .._vf_api import Vf31from .._vf_api import Vf
32+from . import _argument_checker
32from ._control_flow_parser import _is_bare_return33from ._control_flow_parser import _is_bare_return
33from ._expr_evaluator import ExprEvaluator34from ._expr_evaluator import ExprEvaluator
34from ._span_tracker import SpanTracker35from ._span_tracker import SpanTracker
@@ -1087,12 +1088,24 @@ class CallParserMixin:
1087 if self._auto_mutex and not op_name.startswith("vf."):1088 if self._auto_mutex and not op_name.startswith("vf."):
1088 self._emit_auto_mutex(op_name, call, span)1089 self._emit_auto_mutex(op_name, call, span)
1089 1090 
1091+ self._check_declared_params(op_name, call, span)
1092+ 
1090 op_func = _OP_REGISTRY.get(op_name)1093 op_func = _OP_REGISTRY.get(op_name)
1091 if op_func is not None:1094 if op_func is not None:
1092 return op_func(self, call)1095 return op_func(self, call)
1093 1096 
1094 return self._default_op_func(op_name, call)1097 return self._default_op_func(op_name, call)
1095 1098 
1099+ def _check_declared_params(self, op_name: str, call: ast.Call, span: ir.Span) -> None:
1100+ """Check which parameters the call names and how many it passes, before evaluation."""
1101+ _argument_checker.check_declared_params(op_name, call, span, self.span_tracker)
1102+ 
1103+ def _check_declared_types(
1104+ self, op_name: str, call: ast.Call, args: list, kwargs: dict, span: ir.Span
1105+ ) -> None:
1106+ """Check the parsed arguments against the roles their declaration names."""
1107+ _argument_checker.check_declared_types(op_name, call, args, kwargs, span, self.span_tracker)
1108+ 
1096 def _validate_op_scope(self, op_name: str, call: ast.Call) -> None:1109 def _validate_op_scope(self, op_name: str, call: ast.Call) -> None:
1097 """Check the execution domain before parsing operands or emitting IR.1110 """Check the execution domain before parsing operands or emitting IR.
1098 1111 
@@ -1874,6 +1887,7 @@ class CallParserMixin:
1874 1887 
1875 args = [self.parse_expression(arg) for arg in call.args]1888 args = [self.parse_expression(arg) for arg in call.args]
1876 kwargs = self.parse_op_kwargs(call)1889 kwargs = self.parse_op_kwargs(call)
1890+ self._check_declared_types(op_name, call, args, kwargs, span)
1877 1891 
1878 # first arg is out; keep out as first arg to match pto-isa convention1892 # first arg is out; keep out as first arg to match pto-isa convention
1879 return ir.create_op_call(block_ir_op(op_name), args, kwargs, span)1893 return ir.create_op_call(block_ir_op(op_name), args, kwargs, span)
@@ -30,6 +30,7 @@ from ..._errors import (
30 NotSupported,30 NotSupported,
31 OutOfRange,31 OutOfRange,
32 PyptoProError,32 PyptoProError,
33+ current_span,
33)34)
34from ._expr_evaluator import ExprEvaluator35from ._expr_evaluator import ExprEvaluator
35from ._tuple_type_registry import TupleTypeInfo36from ._tuple_type_registry import TupleTypeInfo
@@ -202,7 +203,15 @@ class ExpressionParserMixin:
202 return self._parsed_expr_cache[expr]203 return self._parsed_expr_cache[expr]
203 self._current_node = expr204 self._current_node = expr
204 try:205 try:
205- result = self._parse_expression_node(expr)206+ # Publish where this expression was written, so anything raised while
207+ # parsing it reports that location even when it never passed a span of
208+ # its own. The op dispatcher publishes a finer one (per argument) for
209+ # the ops it handles, and an inner expression publishes over an outer
210+ # one, so the innermost location still wins; this only fills the gaps
211+ # the dispatcher does not reach -- hand-written ``@op_impl`` handlers,
212+ # method calls, builtin min/max, subscripts.
213+ with current_span(self.span_tracker.get_span(expr)):
214+ result = self._parse_expression_node(expr)
206 except PyptoProError as rejection:215 except PyptoProError as rejection:
207 # Retry is opt-in: only a rejection raised with ``parser_retry=True``216 # Retry is opt-in: only a rejection raised with ``parser_retry=True``
208 # may be re-evaluated as Python. Everything else — including a217 # may be re-evaluated as Python. Everything else — including a
@@ -91,6 +91,26 @@ class SpanTracker:
91 written = next((kw.value for kw in call.keywords if kw.arg == name), None)91 written = next((kw.value for kw in call.keywords if kw.arg == name), None)
92 return self.get_span(written) if written is not None else fallback92 return self.get_span(written) if written is not None else fallback
93 93 
94+ def call_keyword_name_span(self, call: "ast.Call", name: str, fallback: ir.Span) -> ir.Span:
95+ """Span of the keyword *name* itself in *call*, not of the value it was given.
96+ 
97+ A keyword the callee never declared, or one that repeats a positional
98+ argument, is wrong in its name; the value beside it may be perfectly good.
99+ Pointing at the value would mark the one part of the argument that is not
100+ at fault.
101+ """
102+ written = next((kw for kw in call.keywords if kw.arg == name), None)
103+ if written is None or not hasattr(written, "col_offset"):
104+ return fallback
105+ start = written.col_offset + self.col_offset + 1
106+ return ir.Span(
107+ self.source_file,
108+ written.lineno + self.line_offset,
109+ start,
110+ written.lineno + self.line_offset,
111+ start + len(name) - 1,
112+ )
113+ 
94 def argument_spans(self, call: "ast.Call") -> dict:114 def argument_spans(self, call: "ast.Call") -> dict:
95 """Where each argument of *call* was written, keyed for ``argument_span``.115 """Where each argument of *call* was written, keyed for ``argument_span``.
96 116 
@@ -298,6 +298,7 @@ class TypeResolver:
298 if isinstance(resolved, ir.TupleType):298 if isinstance(resolved, ir.TupleType):
299 raise NotSupported(299 raise NotSupported(
300 "Parameter type cannot be a tuple",300 "Parameter type cannot be a tuple",
301+ span=self._get_span(type_node),
301 hint="Tuple types are only supported as return types",302 hint="Tuple types are only supported as return types",
302 parser_retry=True,303 parser_retry=True,
303 )304 )
@@ -439,6 +440,7 @@ class TypeResolver:
439 440 
440 raise InvalidType(441 raise InvalidType(
441 f"Shape must be a list, tuple, or variable: {ast.unparse(shape_node)}",442 f"Shape must be a list, tuple, or variable: {ast.unparse(shape_node)}",
443+ span=self._get_span(shape_node),
442 hint="Use a list like [64, 128] or a variable holding a list",444 hint="Use a list like [64, 128] or a variable holding a list",
443 parser_retry=True,445 parser_retry=True,
444 )446 )
@@ -495,6 +497,7 @@ class TypeResolver:
495 497 
496 raise InvalidType(498 raise InvalidType(
497 f"Unsupported type annotation: {ast.unparse(type_node)}",499 f"Unsupported type annotation: {ast.unparse(type_node)}",
500+ span=self._get_span(type_node),
498 hint="Use pl.Tensor[[shape], dtype], pl.Ptr[dtype], or a dtype like pl.DT_INT64 for scalars",501 hint="Use pl.Tensor[[shape], dtype], pl.Ptr[dtype], or a dtype like pl.DT_INT64 for scalars",
499 parser_retry=True,502 parser_retry=True,
500 )503 )
@@ -667,6 +670,7 @@ class TypeResolver:
667 if not isinstance(node, ast.Call):670 if not isinstance(node, ast.Call):
668 raise InvalidType(671 raise InvalidType(
669 f"Expected pl.MemRef(...) call, got: {ast.unparse(node)}",672 f"Expected pl.MemRef(...) call, got: {ast.unparse(node)}",
673+ span=self._get_span(node),
670 hint="Use pl.MemRef(pl.MemorySpace.DDR, addr, size)",674 hint="Use pl.MemRef(pl.MemorySpace.DDR, addr, size)",
671 parser_retry=True,675 parser_retry=True,
672 )676 )
@@ -811,6 +815,7 @@ class TypeResolver:
811 if type_name is None:815 if type_name is None:
812 raise InvalidArgument(816 raise InvalidArgument(
813 f"Unknown type in subscript: {ast.unparse(value)}",817 f"Unknown type in subscript: {ast.unparse(value)}",
818+ span=self._get_span(value),
814 hint="Use pl.Tensor for tensor types or pl.Ptr for pointer types",819 hint="Use pl.Tensor for tensor types or pl.Ptr for pointer types",
815 parser_retry=True,820 parser_retry=True,
816 )821 )
@@ -911,6 +916,7 @@ class TypeResolver:
911 if not self._is_memref_node(memref_node):916 if not self._is_memref_node(memref_node):
912 raise InvalidType(917 raise InvalidType(
913 "Tensor 4th argument must be pl.MemRef(...)",918 "Tensor 4th argument must be pl.MemRef(...)",
919+ span=self._get_span(memref_node),
914 hint="Use pl.Tensor[[shape], dtype, layout, pl.MemRef(...)]",920 hint="Use pl.Tensor[[shape], dtype, layout, pl.MemRef(...)]",
915 parser_retry=True,921 parser_retry=True,
916 )922 )
@@ -967,6 +973,7 @@ class TypeResolver:
967 973 
968 raise InvalidType(974 raise InvalidType(
969 f"Unknown type constructor: {ast.unparse(func)}",975 f"Unknown type constructor: {ast.unparse(func)}",
976+ span=self._get_span(func),
970 hint="Use pl.Tensor[[shape], dtype] or a dtype like pl.DT_INT64 for scalars",977 hint="Use pl.Tensor[[shape], dtype] or a dtype like pl.DT_INT64 for scalars",
971 parser_retry=True,978 parser_retry=True,
972 )979 )
@@ -1001,6 +1008,7 @@ class TypeResolver:
1001 raise InvalidType(1008 raise InvalidType(
1002 f"{type_name} type requires shape, dtype, and optional direction arguments, "1009 f"{type_name} type requires shape, dtype, and optional direction arguments, "
1003 f"got {len(call_node.args)}",1010 f"got {len(call_node.args)}",
1011+ span=self._get_span(call_node),
1004 hint=f"Use pl.{type_name}([shape], dtype) or pl.{type_name}([shape], dtype, pl.Input/pl.Output)",1012 hint=f"Use pl.{type_name}([shape], dtype) or pl.{type_name}([shape], dtype, pl.Input/pl.Output)",
1005 parser_retry=True,1013 parser_retry=True,
1006 )1014 )
@@ -1047,6 +1055,7 @@ class TypeResolver:
1047 else:1055 else:
1048 raise InvalidType(1056 raise InvalidType(
1049 f"Dimension must be int literal, variable, or evaluable expression: {ast.unparse(elt)}",1057 f"Dimension must be int literal, variable, or evaluable expression: {ast.unparse(elt)}",
1058+ span=self._get_span(elt),
1050 hint="Use integer literals, variables, or expressions for dimensions",1059 hint="Use integer literals, variables, or expressions for dimensions",
1051 parser_retry=True,1060 parser_retry=True,
1052 )1061 )
@@ -36,7 +36,7 @@ from pypto.pypto_impl import ir
36from pypto.pypto_impl.ir import DataType36from pypto.pypto_impl.ir import DataType
37from pypto_pro.language.parser.diagnostics import check_in_range37from pypto_pro.language.parser.diagnostics import check_in_range
38 38 
39-from ..._errors import InvalidArgument, InvalidOperation, InvalidType, message_of39+from ..._errors import InvalidArgument, InvalidOperation, InvalidType, message_of, source_lines_of
40 40 
41# Largest fixed-size array a tiling class field may declare.41# Largest fixed-size array a tiling class field may declare.
42_MAX_ARRAY_SIZE = 204842_MAX_ARRAY_SIZE = 2048
@@ -131,6 +131,25 @@ def is_tiling_class(cls: object) -> bool:
131 return True131 return True
132 132 
133 133 
134+def _span_of_class_node(node: ast.AST, source_file: str, source_lines_raw: list[str], starting_line: int):
135+ """Span of *node*, parsed out of a dedented class body, back in file coordinates.
136+ 
137+ ``ast.parse`` needs code at column zero, so the class source was dedented and
138+ re-numbered from one; both offsets have to go back on for the span to name a
139+ place in the file. None when the tracker cannot be built.
140+ """
141+ try:
142+ from pypto_pro.language.parser._span_tracker import SpanTracker
143+ from pypto_pro.runtime.kernel import _calculate_col_offset
144+ 
145+ tracker = SpanTracker(
146+ source_file, source_lines_raw, starting_line - 1, _calculate_col_offset(source_lines_raw)
147+ )
148+ return tracker.get_span(node)
149+ except Exception: # noqa: BLE001 - a location is a nicety; never mask the real error
150+ return None
151+ 
152+ 
134def _check_duplicate_annotations(cls: type) -> None:153def _check_duplicate_annotations(cls: type) -> None:
135 """Parse class source AST to detect duplicate annotated field names.154 """Parse class source AST to detect duplicate annotated field names.
136 155 
@@ -138,25 +157,34 @@ def _check_duplicate_annotations(cls: type) -> None:
138 introspection cannot see duplicates. Use AST parsing as a best-effort check.157 introspection cannot see duplicates. Use AST parsing as a best-effort check.
139 """158 """
140 try:159 try:
141- src = textwrap.dedent(inspect.getsource(cls))160+ source_lines_raw, starting_line = inspect.getsourcelines(cls)
161+ source_file = inspect.getfile(cls)
142 except (TypeError, OSError):162 except (TypeError, OSError):
143 return163 return
164+ src = textwrap.dedent("".join(source_lines_raw))
144 tree = ast.parse(src)165 tree = ast.parse(src)
145 for node in ast.walk(tree):166 for node in ast.walk(tree):
146 if isinstance(node, ast.ClassDef) and node.name == cls.__name__:167 if isinstance(node, ast.ClassDef) and node.name == cls.__name__:
147- ann_names = []168+ declared: dict[str, ast.AnnAssign] = {}
148 for stmt in node.body:169 for stmt in node.body:
149- if isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name):170+ if not (isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name)):
150- ann_names.append(stmt.target.id)171+ continue
151- if len(ann_names) != len(set(ann_names)):172+ name = stmt.target.id
152- seen: set[str] = set()173+ if name in declared:
153- for name in ann_names:174+ # The class body is already parsed here, so the repeated field is
154- if name in seen:175+ # a node in hand: point at it rather than leaving the reader to
155- raise InvalidOperation(176+ # find it. The dedent above shifted the columns and the source
156- f"Tiling class '{cls.__name__}' has duplicate field '{name}'. "177+ # starts at the class, so both offsets go back on.
157- f"All field names must be unique."178+ raise InvalidOperation(
158- )179+ f"Tiling class '{cls.__name__}' has duplicate field '{name}'. "
159- seen.add(name)180+ f"All field names must be unique.",
181+ span=_span_of_class_node(stmt, source_file, source_lines_raw, starting_line),
182+ source_lines=source_lines_of(source_file),
183+ previous_span=_span_of_class_node(
184+ declared[name], source_file, source_lines_raw, starting_line
185+ ),
186+ )
187+ declared[name] = stmt
160 return188 return
161 189 
162 190 
@@ -27,6 +27,7 @@ __all__ = [
27 27 
28from collections.abc import Mapping, Sequence28from collections.abc import Mapping, Sequence
29from dataclasses import dataclass, field29from dataclasses import dataclass, field
30+from functools import partial
30import inspect31import inspect
31import re32import re
32from typing import Any, Union33from typing import Any, Union
@@ -42,6 +43,7 @@ from .._errors import (
42 PyptoProError,43 PyptoProError,
43 RuntimeFailure,44 RuntimeFailure,
44 message_of,45 message_of,
46+ source_lines_of,
45)47)
46 48 
47 49 
@@ -57,6 +59,43 @@ def _get_annotations(func, namespace):
57 return annotations59 return annotations
58 60 
59 61 
62+def _written_at(locate) -> dict:
63+ """Keyword arguments pointing an error at the source *locate* resolves to.
64+ 
65+ Empty when there is nothing to resolve, so a check reads the same whether or
66+ not its caller can say where the annotation was written. *locate* runs only
67+ from a raise, which is what keeps the source lookup off the happy path.
68+ """
69+ if locate is None:
70+ return {}
71+ span, source_lines = locate()
72+ if span is None:
73+ return {}
74+ return {"span": span, "source_lines": source_lines}
75+ 
76+ 
77+def _annotation_location(func, parameter_name: str):
78+ """Where *parameter_name*'s annotation is written, as ``(span, source_lines)``.
79+ 
80+ ``(None, None)`` when the source cannot be read -- a kernel defined in a REPL or
81+ an exec'd string, say. The caller then reports without a location rather than
82+ turning a shape complaint into a source-lookup failure.
83+ """
84+ try:
85+ from pypto_pro.language.parser._span_tracker import SpanTracker
86+ from pypto_pro.runtime.kernel import extract_func_source_info
87+ 
88+ source_file, source_lines, _raw, line_offset, col_offset, func_def = extract_func_source_info(func)
89+ arguments = func_def.args
90+ for argument in (*arguments.posonlyargs, *arguments.args, *arguments.kwonlyargs):
91+ if argument.arg == parameter_name and argument.annotation is not None:
92+ tracker = SpanTracker(source_file, source_lines, line_offset, col_offset)
93+ return tracker.get_span(argument.annotation), source_lines_of(source_file)
94+ except Exception: # noqa: BLE001 - a location is a nicety; never mask the real error
95+ return None, None
96+ return None, None
97+ 
98+ 
60def _dynamic_name(parameter_name: str, axis: int) -> str:99def _dynamic_name(parameter_name: str, axis: int) -> str:
61 safe_name = re.sub(r"[^0-9A-Za-z_]", "_", parameter_name)100 safe_name = re.sub(r"[^0-9A-Za-z_]", "_", parameter_name)
62 return f"__pypto_dyn_{safe_name}_{axis}"101 return f"__pypto_dyn_{safe_name}_{axis}"
@@ -182,10 +221,21 @@ class TensorShapeSpec:
182 shape: Sequence[Any],221 shape: Sequence[Any],
183 *,222 *,
184 dtype: Any = None,223 dtype: Any = None,
224+ locate=None,
185 ) -> "TensorShapeSpec":225 ) -> "TensorShapeSpec":
226+ """Validate one parameter's shape annotation.
227+ 
228+ Args:
229+ locate: Optional callable returning ``(span, source_lines)`` for the
230+ annotation being checked, consulted only when a check fails. The
231+ caller that knows where the annotation was written passes it, so a
232+ complaint can point at it -- these checks run before the kernel is
233+ parsed, so there is no ambient location for them to pick up.
234+ """
186 if not isinstance(shape, (list, tuple)):235 if not isinstance(shape, (list, tuple)):
187 raise InvalidType(236 raise InvalidType(
188- f"Tensor parameter '{parameter_name}' shape must be a list or tuple, got {type(shape).__name__}"237+ f"Tensor parameter '{parameter_name}' shape must be a list or tuple, got {type(shape).__name__}",
238+ **_written_at(locate),
189 )239 )
190 240 
191 dimensions: list[DimensionSpec] = []241 dimensions: list[DimensionSpec] = []
@@ -195,7 +245,8 @@ class TensorShapeSpec:
195 if ellipsis_seen or axis != len(shape) - 1:245 if ellipsis_seen or axis != len(shape) - 1:
196 raise InvalidShape(246 raise InvalidShape(
197 f"Tensor parameter '{parameter_name}' ellipsis must appear once "247 f"Tensor parameter '{parameter_name}' ellipsis must appear once "
198- "and only as the final shape item"248+ "and only as the final shape item",
249+ **_written_at(locate),
199 )250 )
200 dimensions.append(StaticTail(parameter_name, axis))251 dimensions.append(StaticTail(parameter_name, axis))
201 ellipsis_seen = True252 ellipsis_seen = True
@@ -204,7 +255,7 @@ class TensorShapeSpec:
204 try:255 try:
205 value = _validate_positive_int(raw_dim, parameter_name, axis, source="annotation")256 value = _validate_positive_int(raw_dim, parameter_name, axis, source="annotation")
206 except PyptoProError as exc:257 except PyptoProError as exc:
207- raise InvalidShape(message_of(exc)) from exc258+ raise InvalidShape(message_of(exc), **_written_at(locate)) from exc
208 dimensions.append(FixedDim(value))259 dimensions.append(FixedDim(value))
209 continue260 continue
210 if raw_dim is DYNAMIC:261 if raw_dim is DYNAMIC:
@@ -216,7 +267,8 @@ class TensorShapeSpec:
216 policy_name = raw_dim.name if isinstance(raw_dim, _ShapePolicy) else type(raw_dim).__name__267 policy_name = raw_dim.name if isinstance(raw_dim, _ShapePolicy) else type(raw_dim).__name__
217 raise InvalidShape(268 raise InvalidShape(
218 f"Tensor parameter '{parameter_name}' axis {axis} annotation must be DYNAMIC, STATIC, "269 f"Tensor parameter '{parameter_name}' axis {axis} annotation must be DYNAMIC, STATIC, "
219- f"a positive integer, or final ellipsis; got {policy_name}"270+ f"a positive integer, or final ellipsis; got {policy_name}",
271+ **_written_at(locate),
220 )272 )
221 return cls(parameter_name, parameter_index, tuple(dimensions), dtype=dtype)273 return cls(parameter_name, parameter_index, tuple(dimensions), dtype=dtype)
222 274 
@@ -332,6 +384,7 @@ class KernelSignatureSpec:
332 parameter_index,384 parameter_index,
333 annotation.shape,385 annotation.shape,
334 dtype=annotation.dtype,386 dtype=annotation.dtype,
387+ locate=partial(_annotation_location, func, name),
335 )388 )
336 )389 )
337 return cls(tuple(tensor_specs), python_signature=signature)390 return cls(tuple(tensor_specs), python_signature=signature)
@@ -576,7 +576,7 @@ def test_move_src_larger_stays_move():
576 576 
577 577 
578def test_make_tile_missing_addr_rejected():578def test_make_tile_missing_addr_rejected():
579- with pytest.raises(InvalidVal, match="missing required keyword 'addr'"):579+ with pytest.raises(InvalidArgument, match="missing a required argument: 'addr'"):
580 580 
581 @pl.jit(auto_mutex=False)581 @pl.jit(auto_mutex=False)
582 def main(582 def main(
@@ -650,9 +650,13 @@ def test_make_tile_addr_after_tile_type():
650 650 
651 651 
652def test_make_tile_builder_form_rejected():652def test_make_tile_builder_form_rejected():
653- """make_tile(shape, dtype, target_memory, ...) is the IR builder, not the DSL op."""653+ """make_tile(shape, dtype, target_memory, ...) is the IR builder, not the DSL op.
654 654 
655- with pytest.raises(InvalidType, match="takes a pl.TileType as its first argument"):655+ The declaration takes one positional argument, so the builder's form is turned
656+ away on its shape before the first argument is ever looked at.
657+ """
658+ 
659+ with pytest.raises(InvalidArgument, match="too many positional arguments"):
656 660 
657 @pl.jit(auto_mutex=False)661 @pl.jit(auto_mutex=False)
658 def main(662 def main(
@@ -707,7 +711,7 @@ def test_make_tile_runtime_addr_rejected_quoting_source():
707def test_make_tile_positional_addr_rejected():711def test_make_tile_positional_addr_rejected():
708 """The tile type is the only positional argument; addr is keyword-only."""712 """The tile type is the only positional argument; addr is keyword-only."""
709 713 
710- with pytest.raises(InvalidArgument, match="takes 1 positional argument .* but 2 were given"):714+ with pytest.raises(InvalidArgument, match="too many positional arguments"):
711 715 
712 @pl.jit(auto_mutex=False)716 @pl.jit(auto_mutex=False)
713 def main(717 def main(
@@ -739,9 +743,9 @@ def test_make_tile_extra_positional_args_rejected_with_addr_keyword_hint():
739 743 
740 main.to_kernel_def().parse_target_program(ir.SectionKind.Vector)744 main.to_kernel_def().parse_target_program(ir.SectionKind.Vector)
741 745 
742- assert "takes 1 positional argument (the tile type) but 3 were given" in str(excinfo.value)746+ assert "too many positional arguments" in str(excinfo.value)
743 # the hint spells out the accepted spelling747 # the hint spells out the accepted spelling
744- assert "addr=" in str(excinfo.value)748+ assert "pl.make_tile(tile_type, addr=...)" in str(excinfo.value)
745 749 
746 750 
747VEC_BASE = 0x1000751VEC_BASE = 0x1000
@@ -290,8 +290,9 @@ def test_size_keyword_is_rejected(size):
290 290 
291 with pytest.raises(InvalidArgument, match="unexpected keyword argument") as excinfo:291 with pytest.raises(InvalidArgument, match="unexpected keyword argument") as excinfo:
292 _parse_kernel(k)292 _parse_kernel(k)
293- assert "['size']" in str(excinfo.value)293+ assert "'size'" in str(excinfo.value)
294- assert "only 'addr' is supported" in str(excinfo.value)294+ # tile_type is positional-only, so only addr can be named
295+ assert "takes addr" in str(excinfo.value)
295 296 
296 297 
297def test_runtime_size_is_rejected_before_evaluating_it():298def test_runtime_size_is_rejected_before_evaluating_it():
@@ -315,7 +316,7 @@ def test_a_shape_in_place_of_a_tile_type_is_rejected():
315 316 
316 @pl.jit317 @pl.jit
317 def k(x: pl.Tensor[[64], pl.DT_FP16]):318 def k(x: pl.Tensor[[64], pl.DT_FP16]):
318- t = pl.make_tile([64], pl.DT_FP16, pl.MemorySpace.Vec, 0, 128)319+ t = pl.make_tile([64], addr=0)
319 pl.load(t, x, [0])320 pl.load(t, x, [0])
320 321 
321 with pytest.raises(InvalidType) as excinfo:322 with pytest.raises(InvalidType) as excinfo:
@@ -341,15 +342,20 @@ def test_tile_type_may_be_built_inline():
341 342 
342 343 
343def test_a_tile_type_is_required_even_when_addr_is_given():344def test_a_tile_type_is_required_even_when_addr_is_given():
344- """The builder's spread-out form is not a DSL spelling of make_tile."""345+ """The builder's spread-out form is not a DSL spelling of make_tile.
346+ 
347+ The declaration takes one positional argument, so the spread-out form is turned
348+ away on its shape before the first argument is ever looked at.
349+ """
345 350 
346 @pl.jit351 @pl.jit
347 def k(x: pl.Tensor[[64], pl.DT_FP16]):352 def k(x: pl.Tensor[[64], pl.DT_FP16]):
348 t = pl.make_tile([64], pl.DT_FP16, pl.MemorySpace.Vec, 0x40)353 t = pl.make_tile([64], pl.DT_FP16, pl.MemorySpace.Vec, 0x40)
349 pl.load(t, x, [0])354 pl.load(t, x, [0])
350 355 
351- with pytest.raises(InvalidType, match="takes a pl.TileType as its first argument"):356+ with pytest.raises(InvalidArgument, match="too many positional arguments") as excinfo:
352 _parse_kernel(k)357 _parse_kernel(k)
358+ assert "pl.make_tile(tile_type, addr=...)" in str(excinfo.value)
353 359 
354 360 
355def test_a_call_with_no_positional_argument_is_rejected():361def test_a_call_with_no_positional_argument_is_rejected():
@@ -358,7 +364,7 @@ def test_a_call_with_no_positional_argument_is_rejected():
358 t = pl.make_tile(addr=0x40)364 t = pl.make_tile(addr=0x40)
359 pl.load(t, x, [0])365 pl.load(t, x, [0])
360 366 
361- with pytest.raises(InvalidType, match="got no positional argument"):367+ with pytest.raises(InvalidArgument, match="missing a required argument: 'tile_type'"):
362 _parse_kernel(k)368 _parse_kernel(k)
363 369 
364 370 
@@ -371,10 +377,9 @@ def test_addr_and_size_given_positionally_are_rejected():
371 t = pl.make_tile(tt, 0, 128)377 t = pl.make_tile(tt, 0, 128)
372 pl.load(t, x, [0, 0])378 pl.load(t, x, [0, 0])
373 379 
374- with pytest.raises(InvalidArgument) as excinfo:380+ with pytest.raises(InvalidArgument, match="too many positional arguments") as excinfo:
375 _parse_kernel(k)381 _parse_kernel(k)
376- assert "takes 1 positional argument (the tile type) but 3 were given" in str(excinfo.value)382+ assert "pl.make_tile(tile_type, addr=...)" in str(excinfo.value)
377- assert "addr=" in str(excinfo.value)
378 383 
379 384 
380def test_a_positional_addr_is_not_silently_shadowed_by_a_keyword_one():385def test_a_positional_addr_is_not_silently_shadowed_by_a_keyword_one():
@@ -387,7 +392,7 @@ def test_a_positional_addr_is_not_silently_shadowed_by_a_keyword_one():
387 pl.load(t, x, [0, 0])392 pl.load(t, x, [0, 0])
388 393 
389 # the keyword does not count toward the arity, exactly as Python reports it394 # the keyword does not count toward the arity, exactly as Python reports it
390- with pytest.raises(InvalidArgument, match=r"takes 1 positional argument .* but 2 were given"):395+ with pytest.raises(InvalidArgument, match="too many positional arguments"):
391 _parse_kernel(k)396 _parse_kernel(k)
392 397 
393 398 
@@ -396,7 +401,7 @@ def test_a_non_tile_type_first_argument_is_rejected():
396 401 
397 @pl.jit402 @pl.jit
398 def k(x: pl.Tensor[[64], pl.DT_FP16]):403 def k(x: pl.Tensor[[64], pl.DT_FP16]):
399- t = pl.make_tile(0x40)404+ t = pl.make_tile(0x40, addr=0)
400 pl.load(t, x, [0])405 pl.load(t, x, [0])
401 406 
402 with pytest.raises(InvalidType, match="takes a pl.TileType as its first argument"):407 with pytest.raises(InvalidType, match="takes a pl.TileType as its first argument"):
@@ -462,7 +467,7 @@ def test_tile_type_field_cannot_be_overridden_at_make_tile_call():
462 467 
463 with pytest.raises(InvalidArgument, match="unexpected keyword argument") as excinfo:468 with pytest.raises(InvalidArgument, match="unexpected keyword argument") as excinfo:
464 _parse_kernel(k)469 _parse_kernel(k)
465- assert "['valid_shape']" in str(excinfo.value)470+ assert "'valid_shape'" in str(excinfo.value)
466 471 
467 472 
468def test_unknown_make_tile_keyword_is_rejected():473def test_unknown_make_tile_keyword_is_rejected():
@@ -474,7 +479,7 @@ def test_unknown_make_tile_keyword_is_rejected():
474 479 
475 with pytest.raises(InvalidArgument, match="unexpected keyword argument") as excinfo:480 with pytest.raises(InvalidArgument, match="unexpected keyword argument") as excinfo:
476 _parse_kernel(k)481 _parse_kernel(k)
477- assert "['unknown']" in str(excinfo.value)482+ assert "'unknown'" in str(excinfo.value)
478 483 
479 484 
480def test_size_is_derived_from_the_shape_not_the_valid_shape():485def test_size_is_derived_from_the_shape_not_the_valid_shape():
@@ -23,13 +23,13 @@ ValueError/TypeError 会被 parse_target_program 包装为 NotSupported,
23"""23"""
24 24 
25from pypto_pro._errors import (25from pypto_pro._errors import (
26+ InvalidArgument,
26 InvalidOperation,27 InvalidOperation,
27 InvalidShape,28 InvalidShape,
28 InvalidTile,29 InvalidTile,
29 InvalidType,30 InvalidType,
30 InvalidVal,31 InvalidVal,
31 NotSupported,32 NotSupported,
32- RuntimeFailure,
33)33)
34import pypto_pro.language as pl34import pypto_pro.language as pl
35from pypto_pro.runtime.platform import get_platform_info35from pypto_pro.runtime.platform import get_platform_info
@@ -176,7 +176,7 @@ def test_err_scale_string():
176 176 
177 q, k = _make_qk()177 q, k = _make_qk()
178 out = torch.zeros(64, 64, dtype=torch.int8)178 out = torch.zeros(64, 64, dtype=torch.int8)
179- with pytest.raises(InvalidType, match="scale must be"):179+ with pytest.raises(InvalidType, match="scale expects"):
180 kernel(q, k, out)180 kernel(q, k, out)
181 181 
182 182 
@@ -195,7 +195,7 @@ def test_err_scale_list():
195 195 
196 q, k = _make_qk()196 q, k = _make_qk()
197 out = torch.zeros(64, 64, dtype=torch.int8)197 out = torch.zeros(64, 64, dtype=torch.int8)
198- with pytest.raises(InvalidType, match="scale must be"):198+ with pytest.raises(InvalidType, match="scale expects"):
199 kernel(q, k, out)199 kernel(q, k, out)
200 200 
201 201 
@@ -385,7 +385,7 @@ def test_err_legacy_pre_quant_scalar():
385 385 
386 q, k = _make_qk()386 q, k = _make_qk()
387 out = torch.zeros(64, 64, dtype=torch.int8)387 out = torch.zeros(64, 64, dtype=torch.int8)
388- with pytest.raises(RuntimeFailure, match="unexpected keyword argument.*pre_quant_scalar"):388+ with pytest.raises(InvalidArgument, match="unexpected keyword argument 'pre_quant_scalar'"):
389 kernel(q, k, out)389 kernel(q, k, out)
390 390 
391 391 
@@ -404,7 +404,7 @@ def test_err_legacy_fp_tile():
404 404 
405 q, k = _make_qk()405 q, k = _make_qk()
406 out = torch.zeros(64, 64, dtype=torch.int8)406 out = torch.zeros(64, 64, dtype=torch.int8)
407- with pytest.raises(RuntimeFailure, match="unexpected keyword argument.*fp_tile"):407+ with pytest.raises(InvalidArgument, match="unexpected keyword argument 'fp_tile'"):
408 kernel(q, k, out)408 kernel(q, k, out)
409 409 
410 410 
@@ -119,7 +119,7 @@ def test_simt_cast_rejects_plain_integer_round_mode():
119 119 
120 120 
121def test_simt_cast_rejects_wrong_positional_arity():121def test_simt_cast_rejects_wrong_positional_arity():
122- with pytest.raises(InvalidArgument, match="requires exactly 2 positional arguments"):122+ with pytest.raises(InvalidArgument, match="missing a required argument: 'dtype'"):
123 123 
124 @pl.vector_function(mode="simt", max_threads=1)124 @pl.vector_function(mode="simt", max_threads=1)
125 def missing_dtype(value: pl.DT_FP32):125 def missing_dtype(value: pl.DT_FP32):
@@ -149,7 +149,7 @@ def test_simt_cast_rejects_non_dtype_target():
149 149 
150 150 
151def test_simt_cast_rejects_unexpected_keyword():151def test_simt_cast_rejects_unexpected_keyword():
152- with pytest.raises(InvalidArgument, match="only accepts one optional keyword argument"):152+ with pytest.raises(InvalidArgument, match="unexpected keyword argument 'saturate'"):
153 153 
154 @pl.vector_function(mode="simt", max_threads=1)154 @pl.vector_function(mode="simt", max_threads=1)
155 def unexpected_keyword(value: pl.DT_FP32):155 def unexpected_keyword(value: pl.DT_FP32):
@@ -234,7 +234,7 @@ def test_scalar_math_rejects_tile_operand():
234 234 
235 235 
236def test_scalar_math_rejects_wrong_arity_and_keywords():236def test_scalar_math_rejects_wrong_arity_and_keywords():
237- with pytest.raises(InvalidArgument, match="requires exactly 3 positional arguments"):237+ with pytest.raises(InvalidArgument, match="missing a required argument: 'addend'"):
238 238 
239 @pl.vector_function(mode="simt", max_threads=1)239 @pl.vector_function(mode="simt", max_threads=1)
240 def missing_addend(value: pl.DT_FP32):240 def missing_addend(value: pl.DT_FP32):
@@ -13,6 +13,7 @@
13import pypto_pro13import pypto_pro
14from pypto_pro import ir14from pypto_pro import ir
15from pypto_pro._errors import InvalidArgument, InvalidOperation, InvalidType, InvalidVal, NotSupported, OutOfRange15from pypto_pro._errors import InvalidArgument, InvalidOperation, InvalidType, InvalidVal, NotSupported, OutOfRange
16+from pypto_pro.ir.op import system_ops
16import pypto_pro.language as pl17import pypto_pro.language as pl
17import pytest18import pytest
18 19 
@@ -117,7 +118,7 @@ def test_sync_dst_pipe_kwarg_rejects_plain_integer():
117 118 
118 119 
119def test_sync_pipe_kwarg_rejects_other_enum_type():120def test_sync_pipe_kwarg_rejects_other_enum_type():
120- with pytest.raises(InvalidType, match="set_pipe must be a PipeType"):121+ with pytest.raises(InvalidType, match="set_pipe expects PipeType, got SyncCoreType"):
121 122 
122 @pl.jit(auto_mutex=False)123 @pl.jit(auto_mutex=False)
123 def func(_jit_entry: pl.DT_INT64):124 def func(_jit_entry: pl.DT_INT64):
@@ -141,7 +142,7 @@ def test_mutex_lock_pipe_kwarg_rejects_plain_integer():
141 func.to_kernel_def().parse_target_program(ir.SectionKind.Vector)142 func.to_kernel_def().parse_target_program(ir.SectionKind.Vector)
142 143 
143 144 
144-@pytest.mark.parametrize("builder", [pl.system.mutex_lock, pl.system.mutex_unlock])145+@pytest.mark.parametrize("builder", [system_ops.mutex_lock, system_ops.mutex_unlock])
145@pytest.mark.parametrize("pipe", [1, pl.SyncCoreType.AIV_ONLY])146@pytest.mark.parametrize("pipe", [1, pl.SyncCoreType.AIV_ONLY])
146def test_mutex_ir_builder_requires_pipe_type(builder, pipe):147def test_mutex_ir_builder_requires_pipe_type(builder, pipe):
147 with pytest.raises(TypeError, match="pipe must be a PipeType"):148 with pytest.raises(TypeError, match="pipe must be a PipeType"):
@@ -197,14 +198,14 @@ def test_sync_parser_normalizes_python_int_id():
197 assert sync_call.args[0].value == 3198 assert sync_call.args[0].value == 3
198 199 
199 200 
200-@pytest.mark.parametrize("builder", [pl.system.mutex_lock, pl.system.mutex_unlock])201+@pytest.mark.parametrize("builder", [system_ops.mutex_lock, system_ops.mutex_unlock])
201@pytest.mark.parametrize("mutex_id", [True, False])202@pytest.mark.parametrize("mutex_id", [True, False])
202def test_mutex_id_rejects_bool(builder, mutex_id):203def test_mutex_id_rejects_bool(builder, mutex_id):
203 with pytest.raises(TypeError, match="mutex_id must be a Python int or an integer scalar expression"):204 with pytest.raises(TypeError, match="mutex_id must be a Python int or an integer scalar expression"):
204 builder(pipe=pl.PipeType.MTE2, mutex_id=mutex_id)205 builder(pipe=pl.PipeType.MTE2, mutex_id=mutex_id)
205 206 
206 207 
207-@pytest.mark.parametrize("builder", [pl.system.mutex_lock, pl.system.mutex_unlock])208+@pytest.mark.parametrize("builder", [system_ops.mutex_lock, system_ops.mutex_unlock])
208def test_mutex_ir_builder_normalizes_python_int_id(builder):209def test_mutex_ir_builder_normalizes_python_int_id(builder):
209 call = builder(pipe=pl.PipeType.MTE2, mutex_id=0)210 call = builder(pipe=pl.PipeType.MTE2, mutex_id=0)
210 211 
@@ -307,20 +308,20 @@ def test_sync_rejects_unsupported_aic_pipe_path():
307 func.to_kernel_def().parse_target_program(ir.SectionKind.Cube)308 func.to_kernel_def().parse_target_program(ir.SectionKind.Cube)
308 309 
309 310 
310-@pytest.mark.parametrize("builder", [pl.system.mutex_lock, pl.system.mutex_unlock])311+@pytest.mark.parametrize("builder", [system_ops.mutex_lock, system_ops.mutex_unlock])
311@pytest.mark.parametrize("mutex_id", [-1, 32])312@pytest.mark.parametrize("mutex_id", [-1, 32])
312def test_mutex_static_id_range_is_validated_by_frontend(builder, mutex_id):313def test_mutex_static_id_range_is_validated_by_frontend(builder, mutex_id):
313 with pytest.raises(OutOfRange, match=r"mutex_id must be in \[0, 31\]"):314 with pytest.raises(OutOfRange, match=r"mutex_id must be in \[0, 31\]"):
314 builder(pipe=pl.PipeType.MTE2, mutex_id=_const_int(mutex_id))315 builder(pipe=pl.PipeType.MTE2, mutex_id=_const_int(mutex_id))
315 316 
316 317 
317-@pytest.mark.parametrize("builder", [pl.system.mutex_lock, pl.system.mutex_unlock])318+@pytest.mark.parametrize("builder", [system_ops.mutex_lock, system_ops.mutex_unlock])
318def test_mutex_rejects_all_pipe_in_frontend(builder):319def test_mutex_rejects_all_pipe_in_frontend(builder):
319 with pytest.raises(ValueError, match="pipe must identify one concrete pipe"):320 with pytest.raises(ValueError, match="pipe must identify one concrete pipe"):
320 builder(pipe=pl.PipeType.ALL, mutex_id=_const_int(0))321 builder(pipe=pl.PipeType.ALL, mutex_id=_const_int(0))
321 322 
322 323 
323-@pytest.mark.parametrize("builder", [pl.system.mutex_lock, pl.system.mutex_unlock])324+@pytest.mark.parametrize("builder", [system_ops.mutex_lock, system_ops.mutex_unlock])
324def test_manual_mutex_has_no_auto_candidate_metadata(builder):325def test_manual_mutex_has_no_auto_candidate_metadata(builder):
325 call = builder(pipe=pl.PipeType.MTE2, mutex_id=_const_int(8))326 call = builder(pipe=pl.PipeType.MTE2, mutex_id=_const_int(8))
326 327 
@@ -446,7 +447,8 @@ def test_bool_mutex_id_expression_is_rejected_by_parser():
446 447 
447 448 
448def test_complex_float_event_id_expression_is_rejected_by_parser():449def test_complex_float_event_id_expression_is_rejected_by_parser():
449- with pytest.raises(InvalidType, match="event_id must be an integer scalar expression"):450+ # the type gate reaches it first now, and marks the expression rather than the call
451+ with pytest.raises(InvalidType, match=r"event_id expects int, got a fp32 scalar"):
450 452 
451 @pl.jit(auto_mutex=False)453 @pl.jit(auto_mutex=False)
452 def func(base: pl.DT_INT64):454 def func(base: pl.DT_INT64):
@@ -462,7 +464,7 @@ def test_complex_float_event_id_expression_is_rejected_by_parser():
462 464 
463 465 
464def test_complex_float_mutex_id_expression_is_rejected_by_parser():466def test_complex_float_mutex_id_expression_is_rejected_by_parser():
465- with pytest.raises(InvalidType, match="mutex_id must be an integer scalar expression"):467+ with pytest.raises(InvalidType, match=r"mutex_id expects int, got a fp32 scalar"):
466 468 
467 @pl.jit(auto_mutex=False)469 @pl.jit(auto_mutex=False)
468 def func(base: pl.DT_INT64):470 def func(base: pl.DT_INT64):
@@ -499,7 +501,7 @@ def test_control_flow_integer_event_id_expression_is_accepted():
499 501 
500 502 
501def test_control_flow_float_event_id_expression_is_rejected_by_parser():503def test_control_flow_float_event_id_expression_is_rejected_by_parser():
502- with pytest.raises(InvalidType, match="event_id must be an integer scalar expression"):504+ with pytest.raises(InvalidType, match=r"event_id expects int, got a fp32 scalar"):
503 505 
504 @pl.jit(auto_mutex=False)506 @pl.jit(auto_mutex=False)
505 def func(base: pl.DT_INT64):507 def func(base: pl.DT_INT64):
@@ -518,7 +520,7 @@ def test_control_flow_float_event_id_expression_is_rejected_by_parser():
518 func.to_kernel_def().parse_target_program(ir.SectionKind.Vector)520 func.to_kernel_def().parse_target_program(ir.SectionKind.Vector)
519 521 
520 522 
521-@pytest.mark.parametrize("builder", [pl.system.mutex_lock, pl.system.mutex_unlock])523+@pytest.mark.parametrize("builder", [system_ops.mutex_lock, system_ops.mutex_unlock])
522@pytest.mark.parametrize(524@pytest.mark.parametrize(
523 ("kwarg", "value"),525 ("kwarg", "value"),
524 [("mode", 0), ("max_mutex_id", 2), ("mutex_ids", [0, 1])],526 [("mode", 0), ("max_mutex_id", 2), ("mutex_ids", [0, 1])],
@@ -548,7 +550,7 @@ def test_dcci_gm_tensor_with_offset_print_style():
548def test_dcci_gm_tensor_rejects_float_scalar_offset():550def test_dcci_gm_tensor_rejects_float_scalar_offset():
549 """Test pl.system.dcci rejects float scalar offset for GM tensor."""551 """Test pl.system.dcci rejects float scalar offset for GM tensor."""
550 552 
551- with pytest.raises(InvalidType, match="scalar integer element offset"):553+ with pytest.raises(InvalidType, match=r"offset expects .*, got a fp32 scalar"):
552 554 
553 @pl.jit(auto_mutex=False)555 @pl.jit(auto_mutex=False)
554 def main(x: pl.Tensor[[16, 16], pl.DT_FP32]):556 def main(x: pl.Tensor[[16, 16], pl.DT_FP32]):
@@ -155,7 +155,7 @@ def test_tile_type_bad_target_memory_rejected():
155 g = pl.make_tile_group(type=tt, addrs=0, mutex_ids=[0])155 g = pl.make_tile_group(type=tt, addrs=0, mutex_ids=[0])
156 pl.load(g.next(), x, [0])156 pl.load(g.next(), x, [0])
157 157 
158- with pytest.raises(InvalidType, match="target_memory must be a pl.MemorySpace"):158+ with pytest.raises(InvalidType, match="target_memory expects MemorySpace"):
159 _parse(k)159 _parse(k)
160 160 
161 161 
@@ -209,6 +209,7 @@ def test_tile_type_bad_fractal_rejected():
209 g = pl.make_tile_group(type=tt, addrs=0, mutex_ids=[0])209 g = pl.make_tile_group(type=tt, addrs=0, mutex_ids=[0])
210 pl.load(g.next(), x, [0])210 pl.load(g.next(), x, [0])
211 211 
212+ # Python counts True as an int, so the gate lets it by and the builder judges it
212 with pytest.raises(InvalidType, match="fractal must be an integer"):213 with pytest.raises(InvalidType, match="fractal must be an integer"):
213 _parse(k)214 _parse(k)
214 215 
@@ -352,7 +353,7 @@ def test_make_tile_group_unknown_kwarg_rejected():
352 g = pl.make_tile_group(type=tt, addrs=0, mutex_ids=[0], foo=1)353 g = pl.make_tile_group(type=tt, addrs=0, mutex_ids=[0], foo=1)
353 pl.load(g.next(), x, [0])354 pl.load(g.next(), x, [0])
354 355 
355- with pytest.raises(InvalidArgument, match="unexpected keyword argument\\(s\\) \\['foo'\\]"):356+ with pytest.raises(InvalidArgument, match="unexpected keyword argument 'foo'"):
356 _parse(k)357 _parse(k)
357 358 
358 359 
@@ -365,8 +366,10 @@ def test_make_tile_group_typo_kwarg_rejected():
365 g = pl.make_tile_group(type=tt, addrs=0, mutex_id=[0])366 g = pl.make_tile_group(type=tt, addrs=0, mutex_id=[0])
366 pl.load(g.next(), x, [0])367 pl.load(g.next(), x, [0])
367 368 
368- with pytest.raises(InvalidArgument, match="unexpected keyword argument\\(s\\) \\['mutex_id'\\]"):369+ with pytest.raises(InvalidArgument, match="unexpected keyword argument 'mutex_id'") as excinfo:
369 _parse(k)370 _parse(k)
371+ # a near miss is named, so the fix does not have to be looked up
372+ assert "did you mean 'mutex_ids'?" in str(excinfo.value)
370 373 
371 374 
372def test_make_tile_group_bwd_fwd_ids_ignored_for_compat():375def test_make_tile_group_bwd_fwd_ids_ignored_for_compat():
@@ -35,6 +35,7 @@ from pypto_pro._errors import (
35 RuntimeFailure,35 RuntimeFailure,
36)36)
37import pypto_pro.language as pl37import pypto_pro.language as pl
38+from pypto_pro.language import Vf as vf # noqa: N813
38import pytest39import pytest
39 40 
40from pypto.pypto_impl import ir41from pypto.pypto_impl import ir