Merged
feat(pypto_pro): Add pypto language module #4725
gravel1997Add on Jul 8
feat(pypto_pro): Add pypto language module #4725
Merged
Merged fromgravel1997/pyptopro_migrationintocann/pyptomaster
Total: 17 files changed+9173-0
| @@ -0,0 +1,43 @@ | |||
| 1 | +# Copyright (c) PyPTO Contributors. | ||
| 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 | +""" | ||
| 11 | +Language Parser module for converting high-level DSL code to IR structures. | ||
| 12 | + | ||
| 13 | +This module (pypto_pro.language.parser) provides a decorator-based system for | ||
| 14 | +parsing Python functions with DSL annotations and converting them to IR | ||
| 15 | +builder programs. | ||
| 16 | + | ||
| 17 | +Part of the pypto_pro.language package - use via: | ||
| 18 | + import pypto_pro.language as pl | ||
| 19 | + | ||
| 20 | + @pl.function | ||
| 21 | + def my_func(...): | ||
| 22 | + ... | ||
| 23 | +""" | ||
| 24 | +from __future__ import annotations | ||
| 25 | + | ||
| 26 | +__all__ = [ | ||
| 27 | + "function", | ||
| 28 | + "inline", | ||
| 29 | + "program", | ||
| 30 | + "parse", | ||
| 31 | + "loads", | ||
| 32 | + "parse_program", | ||
| 33 | + "loads_program", | ||
| 34 | + "Tensor", | ||
| 35 | + "Tile", | ||
| 36 | + "Scalar", | ||
| 37 | +] | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +from ..typing import Scalar, Tensor, Tile | ||
| 41 | +from .decorator import function, inline, program | ||
| 42 | +from .diagnostics import ParserError | ||
| 43 | +from .text_parser import loads, loads_program, parse, parse_program | ||
| @@ -0,0 +1,336 @@ | |||
| 1 | +# Copyright (c) 2025-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 | +"""Assignment parsing helpers for ASTParser.""" | ||
| 11 | + | ||
| 12 | +from __future__ import annotations | ||
| 13 | + | ||
| 14 | +import ast | ||
| 15 | +from typing import Any | ||
| 16 | + | ||
| 17 | +from pypto.pypto_impl import ir | ||
| 18 | +from pypto.pypto_impl.ir import DataType | ||
| 19 | + | ||
| 20 | +from .diagnostics import ParserSyntaxError, ParserTypeError, UnsupportedFeatureError | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +def _as_const_int_list(value_expr: Any) -> "list[int] | None": | ||
| 24 | + """Return the ints of a ``MakeTuple`` of ``ConstInt`` (e.g. ``[1, 3]``), else None.""" | ||
| 25 | + if not isinstance(value_expr, ir.MakeTuple): | ||
| 26 | + return None | ||
| 27 | + ints: list[int] = [] | ||
| 28 | + for elt in value_expr.elements: | ||
| 29 | + if not isinstance(elt, ir.ConstInt): | ||
| 30 | + return None | ||
| 31 | + ints.append(elt.value) | ||
| 32 | + return ints | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +class AssignmentParserMixin: | ||
| 36 | + """Mixin containing assignment parsing methods for ``ASTParser``.""" | ||
| 37 | + | ||
| 38 | + def parse_annotated_assignment(self, stmt: ast.AnnAssign) -> None: | ||
| 39 | + """Parse annotated assignment: var: type = value. | ||
| 40 | + | ||
| 41 | + Args: | ||
| 42 | + stmt: AnnAssign AST node | ||
| 43 | + """ | ||
| 44 | + if not isinstance(stmt.target, ast.Name): | ||
| 45 | + raise ParserSyntaxError( | ||
| 46 | + "Only simple variable assignments supported", | ||
| 47 | + span=self.span_tracker.get_span(stmt.target), | ||
| 48 | + hint="Use a simple variable name for assignment targets", | ||
| 49 | + ) | ||
| 50 | + | ||
| 51 | + var_name = stmt.target.id | ||
| 52 | + span = self.span_tracker.get_span(stmt) | ||
| 53 | + | ||
| 54 | + # Parse value expression | ||
| 55 | + if stmt.value is None: | ||
| 56 | + raise UnsupportedFeatureError( | ||
| 57 | + "Annotated assignment with no value is not supported", | ||
| 58 | + span=self.span_tracker.get_span(stmt), | ||
| 59 | + hint="Provide a value for the assignment", | ||
| 60 | + ) | ||
| 61 | + value_expr = self.parse_expression(stmt.value, nested=False) | ||
| 62 | + | ||
| 63 | + # Use annotation type as override when it carries memref info | ||
| 64 | + annotation_type = self.type_resolver.resolve_type_if_memref(stmt.annotation) | ||
| 65 | + var = self.builder.let(var_name, value_expr, var_type=annotation_type, span=span) | ||
| 66 | + self._consume_nbuf_pending(var, value_expr) | ||
| 67 | + | ||
| 68 | + # Register in scope | ||
| 69 | + self.scope_manager.define_var(var_name, var, span=span) | ||
| 70 | + | ||
| 71 | + def parse_assignment(self, stmt: ast.Assign) -> None: | ||
| 72 | + """Parse regular assignment: var = value or tuple unpacking. | ||
| 73 | + | ||
| 74 | + Args: | ||
| 75 | + stmt: Assign AST node | ||
| 76 | + """ | ||
| 77 | + if len(stmt.targets) != 1: | ||
| 78 | + raise ParserSyntaxError( | ||
| 79 | + f"Unsupported assignment: {ast.unparse(stmt)}", | ||
| 80 | + span=self.span_tracker.get_span(stmt), | ||
| 81 | + hint="Use simple variable assignments or tuple unpacking", | ||
| 82 | + ) | ||
| 83 | + | ||
| 84 | + target = stmt.targets[0] | ||
| 85 | + span = self.span_tracker.get_span(stmt) | ||
| 86 | + | ||
| 87 | + # Intercept VF op assignment form: reg = vf.xxx(...) or reg_lo, reg_hi = vf.xxx(...) | ||
| 88 | + # Only for compute ops that have dst registers (dst_count > 0). | ||
| 89 | + # Declaration ops (create_mask, RegTensor, compare, etc.) use normal return-value | ||
| 90 | + # assignment and must NOT be intercepted. | ||
| 91 | + vf_op = self._is_vf_op_call(stmt.value) | ||
| 92 | + if vf_op is not None: | ||
| 93 | + dst_count = self._get_vf_op_dst_count(vf_op) | ||
| 94 | + if dst_count is not None and dst_count > 0: | ||
| 95 | + self._parse_vf_assignment(target, stmt, vf_op, span) | ||
| 96 | + return | ||
| 97 | + | ||
| 98 | + if isinstance(target, ast.Tuple): | ||
| 99 | + self._parse_tuple_unpacking(target, stmt) | ||
| 100 | + return | ||
| 101 | + | ||
| 102 | + if isinstance(target, ast.Name): | ||
| 103 | + self._parse_name_assignment(target.id, stmt) | ||
| 104 | + return | ||
| 105 | + | ||
| 106 | + if isinstance(target, ast.Attribute): | ||
| 107 | + self._parse_struct_field_assignment(target, stmt, span) | ||
| 108 | + return | ||
| 109 | + | ||
| 110 | + # AssignStmt left-values are restricted to plain Vars. Field writes go through | ||
| 111 | + # struct.set (above); there is no expression-target / subscript assignment. | ||
| 112 | + raise ParserSyntaxError( | ||
| 113 | + f"Unsupported assignment target: {ast.unparse(stmt)}", | ||
| 114 | + span=span, | ||
| 115 | + hint="Only `var = ...`, `a.field = ...` (struct), or tuple unpacking are supported", | ||
| 116 | + ) | ||
| 117 | + | ||
| 118 | + # Ops where dst type differs from src type — dtype kwarg is mandatory. | ||
| 119 | + _TYPE_CHANGING_OPS = frozenset({"astype", "muls_cast", "pack", "unpack"}) | ||
| 120 | + | ||
| 121 | + def _parse_vf_assignment( | ||
| 122 | + self, target: ast.expr, stmt: ast.Assign, vf_op_name: str, span: ir.Span, | ||
| 123 | + ) -> None: | ||
| 124 | + """Handle ``reg = vf.xxx(src, ...)`` assignment form. | ||
| 125 | + | ||
| 126 | + Transparently rewrites to the statement form by: | ||
| 127 | + 1. Emitting a ``vf.reg_tensor(dtype=...)`` declaration for the LHS variable | ||
| 128 | + (if not already declared), so the CCE backend emits ``RegTensor<T> var;``. | ||
| 129 | + 2. Inserting the LHS variable(s) as dst arg(s) at the front of the call. | ||
| 130 | + 3. Emitting the call as an EvalStmt (side-effect). | ||
| 131 | + | ||
| 132 | + The dtype is inferred from the first source-register argument. For ops | ||
| 133 | + with only scalar sources (e.g. ``vf.full(0.0, preg)``), the user | ||
| 134 | + must pass ``dtype=pl.DT_FP32`` as a kwarg on the VF call. | ||
| 135 | + | ||
| 136 | + Supports: | ||
| 137 | + reg = vf.add(a, b, preg) → RegTensor reg; vf.add(reg, a, b, preg) | ||
| 138 | + reg_lo, reg_hi = vf.mull(a, b, preg) → RegTensor reg_lo, reg_hi; vf.mull(reg_lo, reg_hi, a, b, pred) | ||
| 139 | + """ | ||
| 140 | + dst_count = self._get_vf_op_dst_count(vf_op_name) | ||
| 141 | + | ||
| 142 | + call = stmt.value # ast.Call | ||
| 143 | + | ||
| 144 | + # Determine dst variable names. | ||
| 145 | + # Some ops (like load_align with DINTLV mode) can produce 2 outputs even | ||
| 146 | + # though their static dst_count is 1. When the LHS is a tuple and | ||
| 147 | + # dst_count == 1, promote to 2-dst form so the backend receives the | ||
| 148 | + # correct 4-arg call (dst0, dst1, ptr, offset). | ||
| 149 | + actual_dst_count = dst_count | ||
| 150 | + if dst_count == 1 and isinstance(target, ast.Tuple) and len(target.elts) == 2: | ||
| 151 | + actual_dst_count = 2 | ||
| 152 | + | ||
| 153 | + if actual_dst_count == 1: | ||
| 154 | + if not isinstance(target, ast.Name): | ||
| 155 | + raise ParserSyntaxError( | ||
| 156 | + f"vf.{vf_op_name} assignment target must be a variable name, " | ||
| 157 | + f"got {ast.unparse(target)}", | ||
| 158 | + span=span, | ||
| 159 | + ) | ||
| 160 | + dst_names = [target.id] | ||
| 161 | + dst_targets = [target] | ||
| 162 | + elif actual_dst_count == 2: | ||
| 163 | + if not isinstance(target, ast.Tuple) or len(target.elts) != 2: | ||
| 164 | + raise ParserSyntaxError( | ||
| 165 | + f"vf.{vf_op_name} produces 2 outputs, use tuple unpacking: " | ||
| 166 | + f"reg0, reg1 = vf.{vf_op_name}(...)", | ||
| 167 | + span=span, | ||
| 168 | + ) | ||
| 169 | + for elt in target.elts: | ||
| 170 | + if not isinstance(elt, ast.Name): | ||
| 171 | + raise ParserSyntaxError( | ||
| 172 | + f"Tuple unpacking target must be variable names, got {ast.unparse(elt)}", | ||
| 173 | + span=span, | ||
| 174 | + ) | ||
| 175 | + dst_names = [target.elts[0].id, target.elts[1].id] | ||
| 176 | + dst_targets = [target.elts[0], target.elts[1]] | ||
| 177 | + | ||
| 178 | + # Determine dtype: check explicit dtype kwarg first. | ||
| 179 | + # For type-changing ops (vf.astype), dtype kwarg is mandatory because | ||
| 180 | + # the dst type differs from src type. | ||
| 181 | + dtype_val = None | ||
| 182 | + for kw in call.keywords: | ||
| 183 | + if kw.arg == "dtype": | ||
| 184 | + dtype_val = self.resolve_single_kwarg("dtype", kw.value) | ||
| 185 | + break | ||
| 186 | + | ||
| 187 | + if dtype_val is None and vf_op_name in self._TYPE_CHANGING_OPS: | ||
| 188 | + raise ParserTypeError( | ||
| 189 | + f"vf.{vf_op_name} requires explicit dtype kwarg because dst type differs from src. " | ||
| 190 | + f"Example: vf.{vf_op_name}(src, mask, dtype=pl.DT_FP16)", | ||
| 191 | + span=span, | ||
| 192 | + ) | ||
| 193 | + | ||
| 194 | + # Step 1: Parse source args FIRST, before any dst manipulation. | ||
| 195 | + # This is critical for self-referential ops (e.g. max0 = vf.max(max0, src, preg)) | ||
| 196 | + # where the src must resolve to the OLD value, not a newly created register. | ||
| 197 | + # Also use this pass to infer dtype if not already determined. | ||
| 198 | + parsed_src_args = [self.parse_expression(src_arg) for src_arg in call.args] | ||
| 199 | + | ||
| 200 | + if dtype_val is None: | ||
| 201 | + for src_expr in parsed_src_args: | ||
| 202 | + src_type = getattr(src_expr, 'type', None) | ||
| 203 | + if src_type is None: | ||
| 204 | + continue | ||
| 205 | + if hasattr(src_type, 'dtype'): | ||
| 206 | + dtype_val = src_type.dtype | ||
| 207 | + break | ||
| 208 | + if hasattr(src_type, 'element_dtype'): | ||
| 209 | + dtype_val = src_type.element_dtype | ||
| 210 | + break | ||
| 211 | + | ||
| 212 | + if dtype_val is None: | ||
| 213 | + raise ParserTypeError( | ||
| 214 | + f"Cannot infer dtype for vf.{vf_op_name} assignment. " | ||
| 215 | + f"Pass dtype=pl.DT_FP32 (or appropriate type) as a kwarg.", | ||
| 216 | + span=span, | ||
| 217 | + ) | ||
| 218 | + | ||
| 219 | + parsed_kwargs = {k: v for k, v in self.parse_op_kwargs(call).items() if k != "dtype"} | ||
| 220 | + | ||
| 221 | + # Step 2: Declare dst variables via vf.reg_tensor (first definition only). | ||
| 222 | + # For existing variables, reuse them directly — do NOT create a new | ||
| 223 | + # reg_tensor, as that would lose the accumulated value in self-referential ops. | ||
| 224 | + dst_vars = [] | ||
| 225 | + for _, (name, tgt) in enumerate(zip(dst_names, dst_targets)): | ||
| 226 | + existing = self.scope_manager.lookup_var(name) | ||
| 227 | + if existing is None: | ||
| 228 | + self.current_target_name = name | ||
| 229 | + regtensor_call = ir.create_op_call( | ||
| 230 | + "vf.reg_tensor", [], {"dtype": dtype_val}, span, | ||
| 231 | + ) | ||
| 232 | + var = self.builder.let(name, regtensor_call, span=span) | ||
| 233 | + self.scope_manager.define_var(name, var, span=span) | ||
| 234 | + dst_vars.append(var) | ||
| 235 | + else: | ||
| 236 | + dst_vars.append(existing) | ||
| 237 | + | ||
| 238 | + # Step 3: Construct the VF op call with dst vars + parsed src args. | ||
| 239 | + # vf.shift_left / vf.shift_right are unified ops: the backend codegen | ||
| 240 | + # picks the per-lane (vshl/vshr) vs uniform-scalar (vshls/vshrs) form | ||
| 241 | + # from the shift-amount argument type (see EmitVFShiftLeft/Right), so no | ||
| 242 | + # special routing is needed here. | ||
| 243 | + backend_op_name = self._VF_OP_NAME_MAP.get(vf_op_name, vf_op_name) | ||
| 244 | + all_args = dst_vars + parsed_src_args | ||
| 245 | + call_expr = ir.create_op_call(f"vf.{backend_op_name}", all_args, parsed_kwargs, span) | ||
| 246 | + self.builder.emit(ir.EvalStmt(call_expr, span)) | ||
| 247 | + | ||
| 248 | + def _parse_tuple_unpacking(self, target: ast.Tuple, stmt: ast.Assign) -> None: | ||
| 249 | + span = self.span_tracker.get_span(stmt) | ||
| 250 | + value_expr = self.parse_expression(stmt.value, nested=False) | ||
| 251 | + if not isinstance(value_expr, ir.Expr) or not isinstance(value_expr.type, ir.TupleType): | ||
| 252 | + raise ParserTypeError( | ||
| 253 | + f"Cannot unpack non-tuple value: {ast.unparse(stmt.value)}", | ||
| 254 | + span=span, | ||
| 255 | + ) | ||
| 256 | + expected = len(value_expr.type.types) | ||
| 257 | + actual = len(target.elts) | ||
| 258 | + if actual != expected: | ||
| 259 | + raise ParserTypeError( | ||
| 260 | + f"Cannot unpack tuple with {expected} items into {actual} targets", | ||
| 261 | + span=span, | ||
| 262 | + ) | ||
| 263 | + tuple_var = self.builder.let("_tuple_tmp", value_expr, span=span) | ||
| 264 | + for i, elt in enumerate(target.elts): | ||
| 265 | + if not isinstance(elt, ast.Name): | ||
| 266 | + raise ParserSyntaxError( | ||
| 267 | + f"Tuple unpacking target must be a variable name, got {ast.unparse(elt)}", | ||
| 268 | + span=self.span_tracker.get_span(elt), | ||
| 269 | + hint="Use simple variable names in tuple unpacking: a, b, c = func()", | ||
| 270 | + ) | ||
| 271 | + if elt.id == "_": | ||
| 272 | + continue | ||
| 273 | + item_expr = ir.GetItemExpr( | ||
| 274 | + tuple_var, | ||
| 275 | + ir.ConstInt(i, DataType.INDEX, ir.Span.unknown()), | ||
| 276 | + span, | ||
| 277 | + ) | ||
| 278 | + var = self.builder.let(elt.id, item_expr, span=span) | ||
| 279 | + self.scope_manager.define_var(elt.id, var, span=span) | ||
| 280 | + | ||
| 281 | + def _parse_name_assignment(self, var_name: str, stmt: ast.Assign) -> None: | ||
| 282 | + span = self.span_tracker.get_span(stmt) | ||
| 283 | + self.current_target_name = var_name | ||
| 284 | + value_expr = self.parse_expression(stmt.value, nested=False) | ||
| 285 | + if value_expr is None: | ||
| 286 | + raise ParserTypeError( | ||
| 287 | + f"Cannot assign void function result to '{var_name}'", | ||
| 288 | + span=span, | ||
| 289 | + hint="Functions used as expressions must return a value", | ||
| 290 | + ) | ||
| 291 | + if isinstance(value_expr, ir.Expr): | ||
| 292 | + var = self.builder.let(var_name, value_expr, span=span) | ||
| 293 | + self._consume_nbuf_pending(var, value_expr) | ||
| 294 | + self.scope_manager.define_var(var_name, var, span=span) | ||
| 295 | + if self._auto_mutex: | ||
| 296 | + self._emit_auto_mutex_unlocks() | ||
| 297 | + # Track compile-time integer constants so TileType shape/valid_shape can fold them. | ||
| 298 | + if isinstance(value_expr, ir.ConstInt): | ||
| 299 | + self._const_scalars[var_name] = value_expr.value | ||
| 300 | + else: | ||
| 301 | + self._const_scalars.pop(var_name, None) | ||
| 302 | + # Track compile-time constant int lists (e.g. ``qkv_tile_dims = [1, 3]``) so a | ||
| 303 | + # compile-time-only list kwarg such as ``tile_dims`` can fold them, including when the | ||
| 304 | + # list is threaded through an implicit-helper parameter. | ||
| 305 | + const_list = _as_const_int_list(value_expr) | ||
| 306 | + if const_list is not None: | ||
| 307 | + self._const_lists[var_name] = const_list | ||
| 308 | + else: | ||
| 309 | + self._const_lists.pop(var_name, None) | ||
| 310 | + else: | ||
| 311 | + self.scope_manager.define_var(var_name, value_expr, span=span) | ||
| 312 | + | ||
| 313 | + def _parse_struct_field_assignment(self, target: ast.Attribute, stmt: ast.Assign, span: ir.Span) -> None: | ||
| 314 | + """Lower ``base.field = rhs`` to ``EvalStmt(struct.set(base, rhs, field=...))``. | ||
| 315 | + | ||
| 316 | + The field name (not an index) is carried on the call, mirroring struct.create's | ||
| 317 | + ``fields``; codegen emits ``base.field = rhs;``. This keeps the write off the | ||
| 318 | + AssignStmt left-value, which is restricted to plain Vars. | ||
| 319 | + """ | ||
| 320 | + base = self.parse_expression(target.value) | ||
| 321 | + field_name = target.attr | ||
| 322 | + fields = self.named_fields(base) | ||
| 323 | + if not fields or field_name not in fields: | ||
| 324 | + raise ParserTypeError( | ||
| 325 | + f"Cannot assign to '{ast.unparse(target)}': base is not a named struct/tuple " | ||
| 326 | + f"with field '{field_name}'", | ||
| 327 | + span=span, | ||
| 328 | + ) | ||
| 329 | + value_expr = self.parse_expression(stmt.value, nested=False) | ||
| 330 | + if not isinstance(value_expr, ir.Expr): | ||
| 331 | + raise ParserTypeError( | ||
| 332 | + f"Right-hand side of '{ast.unparse(target)}' must be an IR expression", | ||
| 333 | + span=span, | ||
| 334 | + ) | ||
| 335 | + call = ir.create_op_call("struct.set", [base, value_expr], {"field": field_name}, span) | ||
| 336 | + self.builder.emit(ir.EvalStmt(call, span)) | ||
| @@ -0,0 +1,629 @@ | |||
| 1 | +# Copyright (c) PyPTO Contributors. | ||
| 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 | +"""AST parsing for converting Python DSL to IR builder calls.""" | ||
| 11 | +from __future__ import annotations | ||
| 12 | + | ||
| 13 | +__all__ = ["ASTParser"] | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +import ast | ||
| 17 | +from functools import singledispatchmethod | ||
| 18 | +from typing import Any | ||
| 19 | + | ||
| 20 | +from pypto_pro.ir import IRBuilder | ||
| 21 | +from pypto.pypto_impl import ir | ||
| 22 | + | ||
| 23 | +from ._assignment_parser import AssignmentParserMixin | ||
| 24 | +from ._buffer_parser import BufferParserMixin | ||
| 25 | +from ._call_parser import CallParserMixin, _infer_return_types_from_body | ||
| 26 | +from ._control_flow_parser import ControlFlowParserMixin, validate_single_tail_return | ||
| 27 | +from ._expression_parser import ExpressionParserMixin | ||
| 28 | +from ._struct_parser import StructParserMixin | ||
| 29 | +from .diagnostics import ( | ||
| 30 | + ParserSyntaxError, | ||
| 31 | + ParserTypeError, | ||
| 32 | + UnsupportedFeatureError, | ||
| 33 | +) | ||
| 34 | +from ._expr_evaluator import ExprEvaluator | ||
| 35 | +from ._scope_manager import ScopeManager | ||
| 36 | +from ._span_tracker import SpanTracker | ||
| 37 | +from ._type_resolver import TypeResolver | ||
| 38 | +from ..typing._tiling import ArrayFieldInfo, get_tiling_fields, is_tiling_class | ||
| 39 | +from ..typing.shape import _ShapePolicy | ||
| 40 | + | ||
| 41 | + | ||
| 42 | +def _snake_visit_name(node: ast.AST) -> str: | ||
| 43 | + """Return the snake_case visitor handler for an AST node type.""" | ||
| 44 | + chars: list[str] = [] | ||
| 45 | + for char in type(node).__name__: | ||
| 46 | + if char.isupper() and chars: | ||
| 47 | + chars.append("_") | ||
| 48 | + chars.append(char.lower()) | ||
| 49 | + return f"visit_{''.join(chars)}" | ||
| 50 | + | ||
| 51 | + | ||
| 52 | +class ASTParser( | ||
| 53 | + AssignmentParserMixin, | ||
| 54 | + ControlFlowParserMixin, | ||
| 55 | + ExpressionParserMixin, | ||
| 56 | + StructParserMixin, | ||
| 57 | + BufferParserMixin, | ||
| 58 | + CallParserMixin, | ||
| 59 | +): | ||
| 60 | + """Parses Python AST and builds IR using IRBuilder.""" | ||
| 61 | + | ||
| 62 | + def __init__( | ||
| 63 | + self, | ||
| 64 | + source_file: str, | ||
| 65 | + source_lines: list[str], | ||
| 66 | + line_offset: int = 0, | ||
| 67 | + col_offset: int = 0, | ||
| 68 | + global_vars: set[str] | None = None, | ||
| 69 | + gvar_to_func: dict[str, ir.Function] | None = None, | ||
| 70 | + strict_ssa: bool = False, | ||
| 71 | + closure_vars: dict[str, Any] | None = None, | ||
| 72 | + auto_mutex: bool = False, | ||
| 73 | + debug_info: ir.IRDebugInfo | None = None, | ||
| 74 | + tilingkey_consts: dict[str, int] | None = None, | ||
| 75 | + datatype_consts: dict[str, Any] | None = None, | ||
| 76 | + bound_signature=None, | ||
| 77 | + void_return_only: bool = False, | ||
| 78 | + void_return_context: str = "this function", | ||
| 79 | + allow_early_return: bool = False, | ||
| 80 | + ): | ||
| 81 | + """Initialize AST parser. | ||
| 82 | + | ||
| 83 | + Args: | ||
| 84 | + source_file: Path to source file | ||
| 85 | + source_lines: Lines of source code (dedented for parsing) | ||
| 86 | + line_offset: Line number offset to add to AST line numbers (for dedented code) | ||
| 87 | + col_offset: Column offset to add to AST column numbers (for dedented code) | ||
| 88 | + global_vars: Optional set of function names for cross-function calls | ||
| 89 | + gvar_to_func: Optional map of function names to parsed Functions for type inference | ||
| 90 | + strict_ssa: If True, enforce SSA (single assignment). If False (default), allow reassignment. | ||
| 91 | + closure_vars: Optional variables from the enclosing scope for dynamic shape resolution | ||
| 92 | + auto_mutex: If True, automatically insert mutex lock/unlock around buffer-managed tile ops. | ||
| 93 | + void_return_only: If True, reject return values and non-None return annotations. | ||
| 94 | + void_return_context: User-facing name used only in diagnostics | ||
| 95 | + (for example, "@pl.jit/@pl.kernel" or "@pl.vector_function"). | ||
| 96 | + allow_early_return: If True, skip the single-tail-return restriction. | ||
| 97 | + This is intentionally separate from void_return_only: @pl.jit/@pl.kernel | ||
| 98 | + are void-only but allow early/multiple returns, while @pl.vector_function | ||
| 99 | + and @pl.pipeline.stage are void-only and still require a single tail return. | ||
| 100 | + """ | ||
| @@ -0,0 +1,178 @@ | |||
| 1 | +# Copyright (c) PyPTO Contributors. | ||
| 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 | +"""make_tile_group parsing helpers for ASTParser. | ||
| 11 | + | ||
| 12 | +``pl.make_tile_group(type=, addrs=, mutex_ids=)`` declares a rotating group of | ||
| 13 | +tiles inside a kernel. The parser lowers it to an IR named-tuple handle with | ||
| 14 | +fields ``tiles`` (tuple of tile vars), ``mutex_ids`` (tuple of ConstInt) and a | ||
| 15 | +mutable ``cursor`` struct. The handle's ``next()/current()/previous()`` methods | ||
| 16 | +return a bare tile (not a slot); the tile <-> mutex_id mapping is kept as parser | ||
| 17 | +metadata (``_tile_mutex_meta``) and consumed by auto_mutex, so the runtime never | ||
| 18 | +handles mutex ids or manual lock/unlock. | ||
| 19 | +""" | ||
| 20 | + | ||
| 21 | +from __future__ import annotations | ||
| 22 | + | ||
| 23 | +import ast | ||
| 24 | +from functools import reduce | ||
| 25 | + | ||
| 26 | +from pypto.pypto_impl import ir | ||
| 27 | +from pypto.pypto_impl.ir import DataType | ||
| 28 | + | ||
| 29 | +from pypto_pro.ir.op._op_registry import op_impl | ||
| 30 | +from pypto_pro.ir.op.block_ops import make_tile as _ir_make_tile | ||
| 31 | +from pypto_pro.ir.op.block_ops import TileType as _TileType | ||
| 32 | + | ||
| 33 | +from .diagnostics import ParserSyntaxError, ParserTypeError | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +class BufferParserMixin: | ||
| 37 | + """make_tile_group DSL composite: parse pl.make_tile_group(...) into an IR named tuple.""" | ||
| 38 | + | ||
| 39 | + # --- helpers -------------------------------------------------------------- | ||
| 40 | + | ||
| 41 | + @staticmethod | ||
| 42 | + def _validate_mutex_ids(mutex_ids, span: ir.Span) -> None: | ||
| 43 | + if not mutex_ids: | ||
| 44 | + raise ParserTypeError("make_tile_group() mutex_ids must be a non-empty list", span=span) | ||
| 45 | + for m in mutex_ids: | ||
| 46 | + if not isinstance(m, int) or m < 0 or m > 31: | ||
| 47 | + raise ParserTypeError(f"mutex_ids must be ints in [0,31], got {m!r}", span=span) | ||
| 48 | + if len(set(mutex_ids)) != len(mutex_ids): | ||
| 49 | + raise ParserTypeError(f"mutex_ids must be unique, got {mutex_ids}", span=span) | ||
| 50 | + | ||
| 51 | + @staticmethod | ||
| 52 | + def _tile_type_slot_size(tile_type: _TileType) -> int: | ||
| 53 | + """Per-tile byte size derived from the TileType static shape and dtype.""" | ||
| 54 | + shape = tuple(tile_type.shape) | ||
| 55 | + elems = reduce(lambda a, b: a * b, shape, 1) | ||
| 56 | + return int(elems) * max(1, (int(tile_type.dtype.get_bit()) + 7) // 8) | ||
| 57 | + | ||
| 58 | + # --- factory -------------------------------------------------------------- | ||
| 59 | + | ||
| 60 | + @op_impl("make_tile_group") | ||
| 61 | + def _parse_make_tile_group(self, call: ast.Call) -> ir.Expr: | ||
| 62 | + span = self.span_tracker.get_span(call) | ||
| 63 | + if call.args: | ||
| 64 | + raise ParserSyntaxError( | ||
| 65 | + "pl.make_tile_group() takes keyword args only (type=, addrs=, mutex_ids=)", span=span) | ||
| 66 | + kw = {k.arg: k for k in call.keywords if k.arg is not None} | ||
| 67 | + for required in ("type", "addrs", "mutex_ids"): | ||
| 68 | + if required not in kw: | ||
| 69 | + raise ParserTypeError( | ||
| 70 | + f"pl.make_tile_group() missing required keyword '{required}'", span=span) | ||
| 71 | + | ||
| 72 | + tile_type = self.parse_expression(kw["type"].value) | ||
| 73 | + if not isinstance(tile_type, _TileType): | ||
| 74 | + raise ParserTypeError("pl.make_tile_group() 'type' must be a pl.TileType", span=span) | ||
| 75 | + | ||
| 76 | + mutex_ids = tuple(self.expr_evaluator.eval_expr(kw["mutex_ids"].value)) | ||
| 77 | + self._validate_mutex_ids(mutex_ids, span) | ||
| 78 | + num = len(mutex_ids) | ||
| 79 | + | ||
| 80 | + slot_size = self._tile_type_slot_size(tile_type) | ||
| 81 | + # addrs: a single base address -> contiguous tiles (base + i*slot_size); | ||
| 82 | + # a list -> one explicit address per tile (non-contiguous). | ||
| 83 | + addrs = self.expr_evaluator.eval_expr(kw["addrs"].value) | ||
| 84 | + if isinstance(addrs, (list, tuple)): | ||
| 85 | + tile_addrs = list(addrs) | ||
| 86 | + if len(tile_addrs) != num: | ||
| 87 | + raise ParserTypeError( | ||
| 88 | + f"make_tile_group() addrs length {len(tile_addrs)} must equal " | ||
| 89 | + f"mutex_ids length {num}", span=span) | ||
| 90 | + else: | ||
| 91 | + tile_addrs = [addrs + i * slot_size for i in range(num)] | ||
| 92 | + | ||
| 93 | + return self._build_tile_group_ir(tile_type, tile_addrs, mutex_ids, slot_size, span) | ||
| 94 | + | ||
| 95 | + def is_tile_group(self, expr) -> bool: | ||
| 96 | + return "tiles" in self.named_fields(expr) | ||
| 97 | + | ||
| 98 | + def _build_tile_group_ir(self, tile_type, tile_addrs, mutex_ids, slot_size, span: ir.Span) -> ir.Expr: | ||
| 99 | + """Build the IR named-tuple handle for a tile group. | ||
| 100 | + | ||
| 101 | + Multi-tile groups carry a rotating ``cursor`` struct ({tiles, mutex_ids, | ||
| 102 | + cursor}); single-tile groups skip it ({tiles, mutex_ids}) since the only | ||
| 103 | + tile and its mutex id are statically determined. | ||
| 104 | + | ||
| 105 | + Sets pending metadata ``_tile_group_meta_pending`` consumed by | ||
| 106 | + ``_consume_nbuf_pending`` after the caller's builder.let. | ||
| 107 | + """ | ||
| 108 | + var_name = self.current_target_name or "g" | ||
| 109 | + num = len(mutex_ids) | ||
| 110 | + tile_vars = [] | ||
| 111 | + for i, addr in enumerate(tile_addrs): | ||
| 112 | + t = _ir_make_tile( | ||
| 113 | + shape=tile_type.shape, dtype=tile_type.dtype, | ||
| 114 | + target_memory=tile_type.target_memory, | ||
| 115 | + layout=tile_type.layout, | ||
| 116 | + fractal=tile_type.fractal, pad=tile_type.pad, compact=tile_type.compact, | ||
| 117 | + valid_shape=tile_type.valid_shape, | ||
| 118 | + addr=addr, size=slot_size) | ||
| 119 | + tile_vars.append(self.builder.let(f"_tg_{var_name}_tiles_{i}", t, span=span)) | ||
| 120 | + tiles_tuple = self.builder.let(f"_tg_{var_name}_tiles", ir.MakeTuple(tile_vars, span), span=span) | ||
| 121 | + mut_tuple = self.builder.let( | ||
| 122 | + f"_tg_{var_name}_mutex_ids", | ||
| 123 | + ir.MakeTuple([ir.ConstInt(m, DataType.INDEX, span) for m in mutex_ids], span), span=span) | ||
| 124 | + self._tile_group_meta_pending = (num, mutex_ids) | ||
| 125 | + if num == 1: | ||
| 126 | + # Single tile: no cursor needed; accessors short-circuit to tiles[0]. | ||
| 127 | + return self.make_named_tuple([tiles_tuple, mut_tuple], ["tiles", "mutex_ids"], span) | ||
| 128 | + cursor_call = ir.create_op_call( | ||
| 129 | + "struct.create", [ir.ConstInt(num - 1, DataType.INDEX, span)], | ||
| 130 | + {"name": "_TileGroupCursor", "fields": ["cursor"]}, span) | ||
| 131 | + self.register_struct_fields(cursor_call, ["cursor"]) | ||
| 132 | + cursor = self.builder.let(f"_tg_{var_name}_cursor", cursor_call, span=span) | ||
| 133 | + return self.make_named_tuple([tiles_tuple, mut_tuple, cursor], ["tiles", "mutex_ids", "cursor"], span) | ||
| 134 | + | ||
| 135 | + # --- accessors ------------------------------------------------------------ | ||
| 136 | + | ||
| 137 | + def _emit_cursor_advance(self, cursor_struct, new_val, span: ir.Span) -> None: | ||
| 138 | + self.builder.emit(ir.EvalStmt( | ||
| 139 | + ir.create_op_call("struct.set", [cursor_struct, new_val], {"field": "cursor"}, span), span)) | ||
| 140 | + | ||
| 141 | + def _lower_group_accessor(self, group_var, method_name: str, span: ir.Span): | ||
| 142 | + """Lower group.next()/current()/previous() to a bare tile. | ||
| 143 | + | ||
| 144 | + next() advances the cursor (+1) then returns the tile at the new index; | ||
| 145 | + current()/previous() leave the cursor unchanged. Records the selected | ||
| 146 | + tile's mutex id via _tile_mutex_pending for auto_mutex. | ||
| 147 | + """ | ||
| 148 | + n_slots = self.tile_group_meta.get(id(group_var), (1, None))[0] | ||
| 149 | + mutex_values = self.tile_group_meta.get(id(group_var), (1, None))[1] | ||
| 150 | + tiles = self.lower_attr_access(group_var, "tiles", span) | ||
| 151 | + if n_slots == 1: | ||
| 152 | + # Single tile: no cursor, no modulo. Select tiles[0] with a const index | ||
| 153 | + # (folded by ConstFoldAndSimplify) and lock the lone mutex id statically. | ||
| 154 | + tile_ir = ir.GetItemExpr(tiles, ir.ConstInt(0, DataType.INDEX, span), span) | ||
| 155 | + self._tile_mutex_pending = (mutex_values[0], mutex_values) | ||
| 156 | + return tile_ir | ||
| 157 | + n_const = ir.ConstInt(n_slots, DataType.INDEX, span) | ||
| 158 | + mut = self.lower_attr_access(group_var, "mutex_ids", span) | ||
| 159 | + cursor_struct = self.lower_attr_access(group_var, "cursor", span) | ||
| 160 | + cur_read = self.lower_attr_access(cursor_struct, "cursor", span) | ||
| 161 | + if method_name == "next": | ||
| 162 | + new_val = cur_read + ir.ConstInt(1, DataType.INDEX, span) | ||
| 163 | + self._emit_cursor_advance(cursor_struct, new_val, span) | ||
| 164 | + raw = new_val % n_const | ||
| 165 | + elif method_name == "current": | ||
| 166 | + # next() stores ``cursor = old + 1`` and then (its index re-reads the just-advanced | ||
| 167 | + # cursor) returns slot ``(cursor + 1) % n``. current() must return that same slot, so it | ||
| 168 | + # is ``(cursor + 1) % n`` — not ``cursor % n``, which trails next() by one and makes | ||
| 169 | + # current() read a tile that the preceding next() never selected. | ||
| 170 | + raw = (cur_read + ir.ConstInt(1, DataType.INDEX, span)) % n_const | ||
| 171 | + else: # previous | ||
| 172 | + raw = cur_read % n_const | ||
| 173 | + idx = self.builder.let(f"_bufidx_{self._tuple_idx_counter}", raw, span=span) | ||
| 174 | + self._tuple_idx_counter += 1 | ||
| 175 | + tile_ir = ir.GetItemExpr(tiles, idx, span) | ||
| 176 | + buf_id_ir = ir.GetItemExpr(mut, idx, span) | ||
| 177 | + self._tile_mutex_pending = (buf_id_ir, mutex_values) | ||
| 178 | + return tile_ir | ||
| @@ -0,0 +1,386 @@ | |||
| 1 | +# Copyright (c) PyPTO Contributors. | ||
| 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 | +"""Control-flow parsing helpers for ASTParser.""" | ||
| 11 | + | ||
| 12 | +from __future__ import annotations | ||
| 13 | + | ||
| 14 | +import ast | ||
| 15 | +from typing import Any | ||
| 16 | + | ||
| 17 | +from pypto.pypto_impl import ir | ||
| 18 | +from pypto.pypto_impl.ir import DataType | ||
| 19 | + | ||
| 20 | +from .diagnostics import ParserSyntaxError, UnsupportedFeatureError | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +def _body_without_docstring(func_def: ast.FunctionDef) -> list[ast.stmt]: | ||
| 24 | + body = list(func_def.body) | ||
| 25 | + if body and isinstance(body[0], ast.Expr): | ||
| 26 | + value = body[0].value | ||
| 27 | + if isinstance(value, ast.Constant) and isinstance(value.value, str): | ||
| 28 | + return body[1:] | ||
| 29 | + return body | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +def validate_single_tail_return(func_def: ast.FunctionDef, context: str) -> tuple[ast.Return, str, str] | None: | ||
| 33 | + """Require at most one return, and only as the top-level final statement.""" | ||
| 34 | + returns = [node for node in ast.walk(func_def) if isinstance(node, ast.Return)] | ||
| 35 | + if not returns: | ||
| 36 | + return None | ||
| 37 | + | ||
| 38 | + if len(returns) > 1: | ||
| 39 | + return ( | ||
| 40 | + returns[1], | ||
| 41 | + f"{context} only supports a single return statement.", | ||
| 42 | + "Keep one top-level return at the end of the function. " | ||
| 43 | + "Only @pl.jit/@pl.kernel supports early return.", | ||
| 44 | + ) | ||
| 45 | + | ||
| 46 | + body = _body_without_docstring(func_def) | ||
| 47 | + tail_stmt = body[-1] if body else None | ||
| 48 | + if returns[0] is not tail_stmt: | ||
| 49 | + return ( | ||
| 50 | + returns[0], | ||
| 51 | + f"{context} only supports return as the final top-level statement.", | ||
| 52 | + "Move the return to the end of the function body, or use @pl.jit/@pl.kernel " | ||
| 53 | + "when early return is required.", | ||
| 54 | + ) | ||
| 55 | + | ||
| 56 | + return None | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +class ControlFlowParserMixin: | ||
| 60 | + """Mixin containing loop, branch, with-scope, and return parsing.""" | ||
| 61 | + | ||
| 62 | + _VALID_ITERATORS = {"range"} | ||
| 63 | + _ITERATOR_ERROR = "For loop must use pl.range()" | ||
| 64 | + _ITERATOR_HINT = "Use pl.range() as the iterator" | ||
| 65 | + | ||
| 66 | + @staticmethod | ||
| 67 | + def _get_with_context_attr(stmt: ast.With) -> str | None: | ||
| 68 | + """Return the context manager attribute name for supported with calls.""" | ||
| 69 | + context_expr = stmt.items[0].context_expr | ||
| 70 | + if not isinstance(context_expr, ast.Call): | ||
| 71 | + return None | ||
| 72 | + func = context_expr.func | ||
| 73 | + return func.attr if isinstance(func, ast.Attribute) else None | ||
| 74 | + | ||
| 75 | + @staticmethod | ||
| 76 | + def _describe_with_context(stmt: ast.With) -> str: | ||
| 77 | + """Render the offending context manager(s) for a diagnostic message. | ||
| 78 | + | ||
| 79 | + Returns a source-like description (e.g. ``pl.section_vf()``) so the error | ||
| 80 | + names exactly what was written, instead of only listing what is allowed. | ||
| 81 | + """ | ||
| 82 | + try: | ||
| 83 | + return ", ".join(ast.unparse(item.context_expr) for item in stmt.items) | ||
| 84 | + except Exception: | ||
| 85 | + return "<unknown>" | ||
| 86 | + | ||
| 87 | + def parse_for_loop(self, stmt: ast.For) -> None: | ||
| 88 | + """Parse for loop with pl.range().""" | ||
| 89 | + iter_call = self._validate_for_loop_iterator(stmt) | ||
| 90 | + loop_var_name = self._parse_for_loop_target(stmt) | ||
| 91 | + range_args = self._parse_range_call(iter_call) | ||
| 92 | + | ||
| 93 | + loop_var = self.builder.var(loop_var_name, ir.ScalarType(DataType.INDEX)) | ||
| 94 | + span = self.span_tracker.get_span(stmt) | ||
| 95 | + | ||
| 96 | + with self.builder.for_loop( | ||
| 97 | + loop_var, | ||
| 98 | + range_args["start"], | ||
| 99 | + range_args["stop"], | ||
| 100 | + range_args["step"], | ||
| 101 | + span, | ||
| 102 | + ) as loop: | ||
| 103 | + self._parse_for_loop_body(stmt, loop, loop_var, loop_var_name) | ||
| 104 | + | ||
| 105 | + def parse_while_loop(self, stmt: ast.While) -> None: | ||
| 106 | + """Parse natural while loop syntax. | ||
| 107 | + | ||
| 108 | + Natural while syntax: while condition: body | ||
| 109 | + | ||
| 110 | + This creates a WhileStmt without iter_args (non-SSA form). | ||
| 111 | + The C++ ConvertToSSA pass will convert it to SSA form if needed. | ||
| 112 | + | ||
| 113 | + Args: | ||
| 114 | + stmt: While AST node | ||
| 115 | + """ | ||
| 116 | + condition = self.parse_expression(stmt.test) | ||
| 117 | + span = self.span_tracker.get_span(stmt) | ||
| 118 | + | ||
| 119 | + prev_loop_builder = self.current_loop_builder | ||
| 120 | + prev_in_while_loop = self.in_while_loop | ||
| 121 | + with self.builder.while_loop(condition, span) as loop: | ||
| 122 | + self.current_loop_builder = loop | ||
| 123 | + self.in_while_loop = True | ||
| 124 | + self.scope_manager.enter_scope("while") | ||
| 125 | + | ||
| 126 | + for body_stmt in stmt.body: | ||
| 127 | + self.parse_statement(body_stmt) | ||
| 128 | + | ||
| 129 | + # Variables leak to outer scope (ConvertToSSA will handle) | ||
| 130 | + self.scope_manager.exit_scope(leak_vars=True) | ||
| 131 | + self.in_while_loop = prev_in_while_loop | ||
| 132 | + self.current_loop_builder = prev_loop_builder | ||
| 133 | + | ||
| 134 | + def parse_if_statement(self, stmt: ast.If) -> None: | ||
| 135 | + """Parse if statement. | ||
| 136 | + | ||
| 137 | + Variables from both branches leak to the outer scope, and the | ||
| 138 | + C++ ConvertToSSA pass handles creating phi nodes. | ||
| 139 | + | ||
| 140 | + Args: | ||
| 141 | + stmt: If AST node | ||
| 142 | + """ | ||
| 143 | + test_node, is_constexpr = self._unwrap_constexpr(stmt.test) | ||
| 144 | + condition = self.parse_expression(test_node) | ||
| 145 | + span = self.span_tracker.get_span(stmt) | ||
| 146 | + | ||
| 147 | + condition = self._resolve_constexpr_condition(test_node, condition, is_constexpr, span) | ||
| 148 | + | ||
| 149 | + with self.builder.if_stmt(condition, span) as if_builder: | ||
| 150 | + self.current_if_builder = if_builder | ||
| 151 | + self.in_if_stmt = True | ||
| 152 | + | ||
| 153 | + self.scope_manager.enter_scope("if") | ||
| 154 | + for then_stmt in stmt.body: | ||
| 155 | + self.parse_statement(then_stmt) | ||
| 156 | + self.scope_manager.exit_scope(leak_vars=True) | ||
| 157 | + | ||
| 158 | + if stmt.orelse: | ||
| 159 | + if_builder.else_() | ||
| 160 | + self.scope_manager.enter_scope("else") | ||
| 161 | + for else_stmt in stmt.orelse: | ||
| 162 | + self.parse_statement(else_stmt) | ||
| 163 | + self.scope_manager.exit_scope(leak_vars=True) | ||
| 164 | + | ||
| 165 | + self.in_if_stmt = False | ||
| 166 | + self.current_if_builder = None | ||
| 167 | + | ||
| 168 | + def parse_with_statement(self, stmt: ast.With) -> None: | ||
| 169 | + """Parse with statement for scope contexts. | ||
| 170 | + | ||
| 171 | + Currently supports: | ||
| 172 | + - with pl.section_vector(): ... (creates SectionStmt with Vector section) | ||
| 173 | + - with pl.section_cube(): ... (creates SectionStmt with Cube section) | ||
| 174 | + | ||
| 175 | + Args: | ||
| 176 | + stmt: With AST node | ||
| 177 | + """ | ||
| 178 | + # Check that we have exactly one context manager | ||
| 179 | + if len(stmt.items) != 1: | ||
| 180 | + raise ParserSyntaxError( | ||
| 181 | + f"Only a single context manager is supported in a 'with' statement, " | ||
| 182 | + f"but got {len(stmt.items)}: 'with {self._describe_with_context(stmt)}:'", | ||
| 183 | + span=self.span_tracker.get_span(stmt), | ||
| 184 | + hint="Use 'with pl.section_vector():' or 'with pl.section_cube():'", | ||
| 185 | + ) | ||
| 186 | + | ||
| 187 | + attr = self._get_with_context_attr(stmt) | ||
| 188 | + span = self.span_tracker.get_span(stmt) | ||
| 189 | + | ||
| 190 | + # Check if this is pl.section_vector() or pl.section_cube() | ||
| 191 | + if attr == "section_vector": | ||
| 192 | + self._parse_section_with_body(stmt.body, ir.SectionKind.Vector, span, "vec") | ||
| 193 | + return | ||
| 194 | + if attr == "section_cube": | ||
| 195 | + self._parse_section_with_body(stmt.body, ir.SectionKind.Cube, span, "cube") | ||
| 196 | + return | ||
| 197 | + | ||
| 198 | + # Unsupported context manager | ||
| 199 | + raise UnsupportedFeatureError( | ||
| 200 | + f"Unsupported context manager 'with {self._describe_with_context(stmt)}:'" | ||
| 201 | + + (f" (pl.{attr}() is not a valid section here)" if attr else ""), | ||
| 202 | + span=self.span_tracker.get_span(stmt), | ||
| 203 | + hint=( | ||
| 204 | + "Only 'with pl.section_vector():' or 'with pl.section_cube():' " | ||
| 205 | + "are currently supported. VF code must be placed in a @pl.vector_function " | ||
| 206 | + "decorated function." | ||
| 207 | + ), | ||
| 208 | + ) | ||
| 209 | + | ||
| 210 | + def parse_return(self, stmt: ast.Return) -> None: | ||
| 211 | + """Parse return statement. | ||
| 212 | + | ||
| 213 | + Args: | ||
| 214 | + stmt: Return AST node | ||
| 215 | + """ | ||
| 216 | + span = self.span_tracker.get_span(stmt) | ||
| 217 | + | ||
| 218 | + if stmt.value is None or ( | ||
| 219 | + isinstance(stmt.value, ast.Constant) and stmt.value.value is None | ||
| 220 | + ): | ||
| 221 | + # `return None` is identical to a bare `return`; treat it as a void | ||
| 222 | + # return so a helper can early-exit on a compile-time-dead branch | ||
| 223 | + # (e.g. `if constInfo.is_tnd: return None`) that inlining later drops. | ||
| 224 | + self.builder.return_stmt(None, span) | ||
| 225 | + return | ||
| 226 | + | ||
| 227 | + if self._void_return_only: | ||
| 228 | + raise ParserSyntaxError( | ||
| 229 | + f"{self._void_return_context} only supports bare return or return None; " | ||
| 230 | + "returning values is not supported.", | ||
| 231 | + span=span, | ||
| 232 | + hint=( | ||
| 233 | + "Do not write `return <value>`; only use `return` or `return None`. " | ||
| 234 | + "Pass output Tensor/Tile/buffer parameters for data results." | ||
| 235 | + ), | ||
| 236 | + ) | ||
| 237 | + | ||
| 238 | + # A tuple return (`return a, b`) is parsed as a single MakeTuple | ||
| 239 | + # expression via parse_tuple_literal, so the ReturnStmt always carries | ||
| 240 | + # exactly one value. Downstream inlining lowers it to `target = MakeTuple(...)` | ||
| 241 | + # and backend codegen resolves the tuple via tuple_var_to_make_tuple_. | ||
| 242 | + return_expr = self.parse_expression(stmt.value) | ||
| 243 | + self.builder.return_stmt([return_expr], span) | ||
| 244 | + | ||
| 245 | + def parse_break(self, stmt: ast.Break) -> None: | ||
| 246 | + """Parse break statement. | ||
| 247 | + | ||
| 248 | + Args: | ||
| 249 | + stmt: Break AST node | ||
| 250 | + """ | ||
| 251 | + if not self.in_for_loop and not self.in_while_loop: | ||
| 252 | + raise ParserSyntaxError( | ||
| 253 | + "'break' statement outside of a loop", | ||
| 254 | + span=self.span_tracker.get_span(stmt), | ||
| 255 | + hint="break can only be used inside a for or while loop", | ||
| 256 | + ) | ||
| 257 | + span = self.span_tracker.get_span(stmt) | ||
| 258 | + self.builder.break_stmt(span) | ||
| 259 | + | ||
| 260 | + def parse_continue(self, stmt: ast.Continue) -> None: | ||
| 261 | + """Parse continue statement. | ||
| 262 | + | ||
| 263 | + Args: | ||
| 264 | + stmt: Continue AST node | ||
| 265 | + """ | ||
| 266 | + if not self.in_for_loop and not self.in_while_loop: | ||
| 267 | + raise ParserSyntaxError( | ||
| 268 | + "'continue' statement outside of a loop", | ||
| 269 | + span=self.span_tracker.get_span(stmt), | ||
| 270 | + hint="continue can only be used inside a for or while loop", | ||
| 271 | + ) | ||
| 272 | + span = self.span_tracker.get_span(stmt) | ||
| 273 | + self.builder.continue_stmt(span) | ||
| 274 | + | ||
| 275 | + def _parse_section_with_body( | ||
| 276 | + self, | ||
| 277 | + body: list[ast.stmt], | ||
| 278 | + kind: ir.SectionKind, | ||
| 279 | + span, | ||
| 280 | + saved_key: str | None = None, | ||
| 281 | + ) -> None: | ||
| 282 | + """Parse a section body and optionally persist its local variables.""" | ||
| 283 | + with self.builder.section(kind, span): | ||
| 284 | + self.scope_manager.enter_scope("section") | ||
| 285 | + if saved_key is not None and self._section_saved_vars.get(saved_key): | ||
| 286 | + for name, value in self._section_saved_vars[saved_key].items(): | ||
| 287 | + self.scope_manager.define_var(name, value, allow_redef=True) | ||
| 288 | + for body_stmt in body: | ||
| 289 | + self.parse_statement(body_stmt) | ||
| 290 | + saved_vars = self.scope_manager.exit_scope(leak_vars=False) | ||
| 291 | + if saved_key is not None: | ||
| 292 | + self._section_saved_vars[saved_key] = saved_vars | ||
| 293 | + | ||
| 294 | + def _validate_for_loop_iterator(self, stmt: ast.For) -> ast.Call: | ||
| 295 | + """Validate that for loop uses pl.range(). | ||
| 296 | + | ||
| 297 | + Returns: | ||
| 298 | + The call node for pl.range() | ||
| 299 | + """ | ||
| 300 | + if not isinstance(stmt.iter, ast.Call): | ||
| 301 | + raise ParserSyntaxError( | ||
| 302 | + self._ITERATOR_ERROR, | ||
| 303 | + span=self.span_tracker.get_span(stmt.iter), | ||
| 304 | + hint=self._ITERATOR_HINT, | ||
| 305 | + ) | ||
| 306 | + | ||
| 307 | + iter_call = stmt.iter | ||
| 308 | + func = iter_call.func | ||
| 309 | + if isinstance(func, ast.Attribute) and func.attr in self._VALID_ITERATORS: | ||
| 310 | + return iter_call | ||
| 311 | + | ||
| 312 | + raise ParserSyntaxError( | ||
| 313 | + self._ITERATOR_ERROR, | ||
| 314 | + span=self.span_tracker.get_span(stmt.iter), | ||
| 315 | + hint=self._ITERATOR_HINT, | ||
| 316 | + ) | ||
| 317 | + | ||
| 318 | + def _parse_for_loop_target(self, stmt: ast.For) -> str: | ||
| 319 | + """Parse for loop target, returning the loop variable name.""" | ||
| 320 | + if not isinstance(stmt.target, ast.Name): | ||
| 321 | + raise ParserSyntaxError( | ||
| 322 | + "For loop target must be a simple name", | ||
| 323 | + span=self.span_tracker.get_span(stmt.target), | ||
| 324 | + hint="Use: for i in pl.range(n)", | ||
| 325 | + ) | ||
| 326 | + return stmt.target.id | ||
| 327 | + | ||
| 328 | + def _parse_for_loop_body( | ||
| 329 | + self, | ||
| 330 | + stmt: ast.For, | ||
| 331 | + loop: Any, | ||
| 332 | + loop_var: ir.Var, | ||
| 333 | + loop_var_name: str, | ||
| 334 | + ) -> None: | ||
| 335 | + """Parse the body of a for loop inside the loop context.""" | ||
| 336 | + prev_loop_builder = self.current_loop_builder | ||
| 337 | + prev_in_for_loop = self.in_for_loop | ||
| 338 | + self.current_loop_builder = loop | ||
| 339 | + self.in_for_loop = True | ||
| 340 | + self.scope_manager.enter_scope("for") | ||
| 341 | + self.scope_manager.define_var(loop_var_name, loop_var, allow_redef=True) | ||
| 342 | + | ||
| 343 | + for body_stmt in stmt.body: | ||
| 344 | + self.parse_statement(body_stmt) | ||
| 345 | + | ||
| 346 | + self.scope_manager.exit_scope(leak_vars=True) | ||
| 347 | + self.in_for_loop = prev_in_for_loop | ||
| 348 | + self.current_loop_builder = prev_loop_builder | ||
| 349 | + | ||
| 350 | + def _parse_range_call(self, call: ast.Call) -> dict[str, Any]: | ||
| 351 | + """Parse pl.range() call arguments. | ||
| 352 | + | ||
| 353 | + Args: | ||
| 354 | + call: AST Call node for pl.range() | ||
| 355 | + | ||
| 356 | + Returns: | ||
| 357 | + Dictionary with start, stop, step | ||
| 358 | + """ | ||
| 359 | + if call.keywords: | ||
| 360 | + raise ParserSyntaxError( | ||
| 361 | + "pl.range() does not support keyword arguments", | ||
| 362 | + span=self.span_tracker.get_span(call), | ||
| 363 | + hint="Use: pl.range(stop), pl.range(start, stop), or pl.range(start, stop, step)", | ||
| 364 | + ) | ||
| 365 | + | ||
| 366 | + if len(call.args) < 1: | ||
| 367 | + raise ParserSyntaxError( | ||
| 368 | + "pl.range() requires at least 1 argument (stop)", | ||
| 369 | + span=self.span_tracker.get_span(call), | ||
| 370 | + hint="Provide at least the stop value: pl.range(10) or pl.range(0, 10)", | ||
| 371 | + ) | ||
| 372 | + | ||
| 373 | + start = 0 | ||
| 374 | + step = 1 | ||
| 375 | + | ||
| 376 | + if len(call.args) == 1: | ||
| 377 | + stop = self.parse_expression(call.args[0]) | ||
| 378 | + elif len(call.args) == 2: | ||
| 379 | + start = self.parse_expression(call.args[0]) | ||
| 380 | + stop = self.parse_expression(call.args[1]) | ||
| 381 | + else: | ||
| 382 | + start = self.parse_expression(call.args[0]) | ||
| 383 | + stop = self.parse_expression(call.args[1]) | ||
| 384 | + step = self.parse_expression(call.args[2]) | ||
| 385 | + | ||
| 386 | + return {"start": start, "stop": stop, "step": step} | ||
| @@ -0,0 +1,181 @@ | |||
| 1 | +# Copyright (c) PyPTO Contributors. | ||
| 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 | +"""Centralized expression evaluator for resolving Python expressions against closure variables.""" | ||
| 11 | +from __future__ import annotations | ||
| 12 | + | ||
| 13 | +__all__ = ["ExprEvaluator"] | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +import ast | ||
| 17 | +from typing import TYPE_CHECKING, Any | ||
| 18 | + | ||
| 19 | +from pypto.pypto_impl import ir | ||
| 20 | +from pypto.pypto_impl.ir import DataType | ||
| 21 | + | ||
| 22 | +from .diagnostics import ParserTypeError | ||
| 23 | + | ||
| 24 | +if TYPE_CHECKING: | ||
| 25 | + from ._span_tracker import SpanTracker | ||
| 26 | + | ||
| 27 | +# Safe subset of builtins allowed during expression evaluation | ||
| 28 | +_SAFE_BUILTINS: dict[str, Any] = { | ||
| 29 | + "len": len, | ||
| 30 | + "max": max, | ||
| 31 | + "min": min, | ||
| 32 | + "abs": abs, | ||
| 33 | + "sum": sum, | ||
| 34 | + "round": round, | ||
| 35 | + "int": int, | ||
| 36 | + "float": float, | ||
| 37 | + "bool": bool, | ||
| 38 | + "list": list, | ||
| 39 | + "tuple": tuple, | ||
| 40 | + "range": range, | ||
| 41 | + "isinstance": isinstance, | ||
| 42 | + "type": type, | ||
| 43 | + "True": True, | ||
| 44 | + "False": False, | ||
| 45 | + "None": None, | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | + | ||
| 49 | +class ExprEvaluator: | ||
| 50 | + """Evaluates Python AST expressions against closure variables. | ||
| 51 | + | ||
| 52 | + Uses Python's eval() with a restricted builtins whitelist for safety. | ||
| 53 | + Can return raw Python values or convert them to IR expressions. | ||
| 54 | + """ | ||
| 55 | + | ||
| 56 | + def __init__( | ||
| 57 | + self, | ||
| 58 | + closure_vars: dict[str, Any], | ||
| 59 | + span_tracker: "SpanTracker | None" = None, | ||
| 60 | + ): | ||
| 61 | + """Initialize expression evaluator. | ||
| 62 | + | ||
| 63 | + Args: | ||
| 64 | + closure_vars: Variables from the enclosing scope | ||
| 65 | + span_tracker: Optional span tracker for source locations in errors | ||
| 66 | + """ | ||
| 67 | + self.closure_vars = closure_vars | ||
| 68 | + self.span_tracker = span_tracker | ||
| 69 | + | ||
| 70 | + def eval_expr(self, node: ast.expr) -> Any: | ||
| 71 | + """Evaluate an AST expression node against closure variables. | ||
| 72 | + | ||
| 73 | + Args: | ||
| 74 | + node: AST expression node to evaluate | ||
| 75 | + | ||
| 76 | + Returns: | ||
| 77 | + The Python value resulting from evaluation | ||
| 78 | + | ||
| 79 | + Raises: | ||
| 80 | + ParserTypeError: If expression cannot be evaluated | ||
| 81 | + """ | ||
| 82 | + span = self._get_span(node) | ||
| 83 | + expr_str = ast.unparse(node) | ||
| 84 | + | ||
| 85 | + try: | ||
| 86 | + code = compile(ast.Expression(body=node), "<pypto-eval>", "eval") | ||
| 87 | + # Security note: closure_vars come from the user's own enclosing Python scope. | ||
| 88 | + # The DSL parser is not a sandbox — users already have full control of the | ||
| 89 | + # Python process. The builtins whitelist prevents accidental access to dangerous | ||
| 90 | + # builtins (open, __import__, exec) but does not prevent calling methods on | ||
| 91 | + # objects the user placed in scope, which is by design. | ||
| 92 | + return eval(code, {"__builtins__": _SAFE_BUILTINS}, dict(self.closure_vars)) | ||
| 93 | + except NameError as e: | ||
| 94 | + raise ParserTypeError( | ||
| 95 | + f"Cannot resolve expression '{expr_str}': {e}", | ||
| 96 | + span=span, | ||
| 97 | + hint="Make sure the variable is defined in the enclosing scope", | ||
| 98 | + ) from e | ||
| 99 | + except Exception as e: | ||
| 100 | + raise ParserTypeError( | ||
| 101 | + f"Failed to evaluate expression '{expr_str}': {e}", | ||
| 102 | + span=span, | ||
| 103 | + ) from e | ||
| 104 | + | ||
| 105 | + def try_eval_expr(self, node: ast.expr) -> tuple[bool, Any]: | ||
| 106 | + """Try to evaluate an AST expression, returning success status. | ||
| 107 | + | ||
| 108 | + Non-throwing variant of eval_expr for cases where evaluation failure | ||
| 109 | + should fall through to other resolution strategies. | ||
| 110 | + | ||
| 111 | + Args: | ||
| 112 | + node: AST expression node to evaluate | ||
| 113 | + | ||
| 114 | + Returns: | ||
| 115 | + Tuple of (success, value). On failure, value is None. | ||
| 116 | + """ | ||
| 117 | + try: | ||
| 118 | + return (True, self.eval_expr(node)) | ||
| 119 | + except ParserTypeError: | ||
| 120 | + return (False, None) | ||
| 121 | + | ||
| 122 | + def python_value_to_ir(self, value: Any, span: ir.Span) -> ir.Expr: | ||
| 123 | + """Convert a Python value to an IR expression. | ||
| 124 | + | ||
| 125 | + Args: | ||
| 126 | + value: Python value (bool, int, float, ir.Expr, list, or tuple) | ||
| 127 | + span: Source span for the expression | ||
| 128 | + | ||
| 129 | + Returns: | ||
| 130 | + IR expression representing the value | ||
| 131 | + """ | ||
| 132 | + # bool before int because isinstance(True, int) is True | ||
| 133 | + if isinstance(value, bool): | ||
| 134 | + return ir.ConstBool(value, span) | ||
| 135 | + if isinstance(value, int): | ||
| 136 | + return ir.ConstInt(value, DataType.INDEX, span) | ||
| 137 | + if isinstance(value, float): | ||
| 138 | + return ir.ConstFloat(value, DataType.DEFAULT_CONST_FLOAT, span) | ||
| 139 | + if isinstance(value, DataType): | ||
| 140 | + return ir.ConstInt(int(value), DataType.INDEX, span) | ||
| 141 | + if isinstance(value, ir.Expr): | ||
| 142 | + return value | ||
| 143 | + # Tile wrapper — unwrap to the underlying IR Call expression. | ||
| 144 | + if hasattr(value, "unwrap") and callable(value.unwrap): | ||
| 145 | + inner = value.unwrap() | ||
| 146 | + if isinstance(inner, ir.Expr): | ||
| 147 | + return inner | ||
| 148 | + if isinstance(value, (list, tuple)): | ||
| 149 | + return ir.MakeTuple([self.python_value_to_ir(elt, span) for elt in value], span) | ||
| 150 | + raise ParserTypeError( | ||
| 151 | + f"Unsupported closure variable type: {type(value).__name__}", | ||
| 152 | + span=span, | ||
| 153 | + hint="Closure variables must be int, float, bool, list, tuple, or IR expressions", | ||
| 154 | + ) | ||
| 155 | + | ||
| 156 | + def try_eval_as_ir(self, node: ast.expr) -> ir.Expr | None: | ||
| 157 | + """Try to evaluate an AST node and convert to an IR expression. | ||
| 158 | + | ||
| 159 | + Combines try_eval_expr + python_value_to_ir. Returns None when the | ||
| 160 | + name cannot be resolved from closure variables. | ||
| 161 | + | ||
| 162 | + Args: | ||
| 163 | + node: AST expression node to evaluate | ||
| 164 | + | ||
| 165 | + Returns: | ||
| 166 | + IR expression, or None if the name cannot be resolved. | ||
| 167 | + | ||
| 168 | + Raises: | ||
| 169 | + ParserTypeError: If the value is resolved but has an unsupported type. | ||
| 170 | + """ | ||
| 171 | + success, value = self.try_eval_expr(node) | ||
| 172 | + if not success: | ||
| 173 | + return None | ||
| 174 | + return self.python_value_to_ir(value, self._get_span(node)) | ||
| 175 | + | ||
| 176 | + def _get_span(self, node: ast.AST) -> "ir.Span": | ||
| 177 | + """Get span for an AST node, falling back to unknown.""" | ||
| 178 | + if self.span_tracker is not None: | ||
| 179 | + return self.span_tracker.get_span(node) | ||
| 180 | + | ||
| 181 | + return ir.Span.unknown() | ||
| @@ -0,0 +1,231 @@ | |||
| 1 | +# Copyright (c) PyPTO Contributors. | ||
| 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 | +"""Block-op pipeline metadata used by parser features that need pipe IDs.""" | ||
| 11 | + | ||
| 12 | +from __future__ import annotations | ||
| 13 | + | ||
| 14 | +from pypto.pypto_impl.backend import BackendCCE | ||
| 15 | +from pypto.pypto_impl.ir import MemorySpace, PipeType | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +_BLOCK_OP_ALIASES: dict[str, str] = { | ||
| 19 | + "and_": "and", | ||
| 20 | + "eq": "cmp", | ||
| 21 | + "ne": "cmp", | ||
| 22 | + "lt": "cmp", | ||
| 23 | + "le": "cmp", | ||
| 24 | + "gt": "cmp", | ||
| 25 | + "ge": "cmp", | ||
| 26 | + "select": "sel", | ||
| 27 | + "load_tile": "load", | ||
| 28 | + "not_": "not", | ||
| 29 | + "or_": "or", | ||
| 30 | + "sum": "row_sum", | ||
| 31 | + "argmax": "row_argmax", | ||
| 32 | + "argmin": "row_argmin", | ||
| 33 | + "expand_max": "row_expand_max", | ||
| 34 | + "expand_min": "row_expand_min", | ||
| 35 | + "expand_mul": "row_expand_mul", | ||
| 36 | + "expand_sub": "row_expand_sub", | ||
| 37 | + "expand_div": "row_expand_div", | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +def get_op_pipe(op_name: str) -> PipeType | None: | ||
| 42 | + """Return the pipe registered by the CCE backend for a block op.""" | ||
| 43 | + backend_op_name = _BLOCK_OP_ALIASES.get(op_name, op_name) | ||
| 44 | + return BackendCCE.instance().get_op_pipe(f"block.{backend_op_name}") | ||
| 45 | + | ||
| 46 | + | ||
| 47 | +# ---------------------------------------------------------------------------- | ||
| 48 | +# Descriptor-only (metadata) ops | ||
| 49 | +# ---------------------------------------------------------------------------- | ||
| 50 | +# These ops only rewrite a tile's *descriptor* (e.g. its valid (row, col) | ||
| 51 | +# window); they never read or write the tile's buffer *data*. Accesses to | ||
| 52 | +# their tiles therefore cannot race, so they need neither a buffer mutex | ||
| 53 | +# (auto_mutex) nor cross-core / cross-pipe synchronisation. This mirrors the | ||
| 54 | +# tile-graph sync pass, which likewise excludes the metadata opcodes | ||
| 55 | +# OP_VIEW / OP_VIEW_TYPE / OP_RESHAPE / OP_ASSEMBLE from synchronisation. | ||
| 56 | +_DESCRIPTOR_ONLY_OPS: frozenset[str] = frozenset( | ||
| 57 | + { | ||
| 58 | + "set_validshape", | ||
| 59 | + "set_stride", | ||
| 60 | + } | ||
| 61 | +) | ||
| 62 | + | ||
| 63 | + | ||
| 64 | +def op_accesses_buffer(op_name: str) -> bool: | ||
| 65 | + """Whether a block op reads or writes its tiles' buffer data. | ||
| 66 | + | ||
| 67 | + False for descriptor-only ops (they only touch tile metadata), which is the | ||
| 68 | + signal that auto_mutex / sync insertion can skip them. | ||
| 69 | + """ | ||
| 70 | + return _BLOCK_OP_ALIASES.get(op_name, op_name) not in _DESCRIPTOR_ONLY_OPS | ||
| 71 | + | ||
| 72 | + | ||
| 73 | +def get_move_pipe( | ||
| 74 | + src_memory: MemorySpace | None, | ||
| 75 | + target_memory: MemorySpace | None, | ||
| 76 | +) -> PipeType: | ||
| 77 | + """Determine the hardware pipe for a block ``move`` operation.""" | ||
| 78 | + if src_memory == MemorySpace.Acc and target_memory == MemorySpace.Vec: | ||
| 79 | + return PipeType.FIX | ||
| 80 | + if src_memory == MemorySpace.Mat: | ||
| 81 | + if target_memory in (MemorySpace.Left, MemorySpace.Right): | ||
| 82 | + return PipeType.MTE1 | ||
| 83 | + if target_memory == MemorySpace.Vec: | ||
| 84 | + return PipeType.V | ||
| 85 | + return PipeType.FIX | ||
| 86 | + if src_memory == MemorySpace.Vec and target_memory == MemorySpace.Mat: | ||
| 87 | + return PipeType.MTE3 | ||
| 88 | + return PipeType.V | ||
| 89 | + | ||
| 90 | + | ||
| 91 | +def get_store_pipe(src_memory: MemorySpace | None) -> PipeType: | ||
| 92 | + """Determine the hardware pipe for a block ``store`` / ``store_tile`` operation.""" | ||
| 93 | + if src_memory == MemorySpace.Acc: | ||
| 94 | + return PipeType.FIX | ||
| 95 | + return PipeType.MTE3 | ||
| 96 | + | ||
| 97 | + | ||
| 98 | +# ---------------------------------------------------------------------------- | ||
| 99 | +# Per-op tile-argument role table (for cross-core sync direction inference) | ||
| 100 | +# ---------------------------------------------------------------------------- | ||
| 101 | +# | ||
| 102 | +# Each entry is a list of role strings, one per Python-call positional arg: | ||
| 103 | +# "W" - written (producer of cross-core data) | ||
| 104 | +# "R" - read (consumer of cross-core data) | ||
| 105 | +# "RW" - both read and written (e.g. matmul_acc accumulator) | ||
| 106 | +# None - not a tile arg (skip cross-core sync check at this position) | ||
| 107 | +# | ||
| 108 | +# Used by the pipeline cross-core scanner to determine for each tile argument | ||
| 109 | +# the access role (W/R), which drives auto cross-core wait/set generation. | ||
| 110 | +# | ||
| 111 | +# Note: cross-core sync MUST distinguish read vs write because the sync | ||
| 112 | +# direction depends on it. | ||
| 113 | + | ||
| 114 | +_BLOCK_OP_TILE_ROLES: dict[str, list] = { | ||
| 115 | + # ===== Data movement ===== | ||
| 116 | + "load": ["W"], # load(out, tensor, offsets, ...) | ||
| 117 | + "load_tile": ["W"], | ||
| 118 | + "store": ["W", "R"], # store(out, tile, offsets, ...) | ||
| 119 | + "store_fp": ["W", "R", "R"], # store_fp(out, tile, fp_tile, offsets) | ||
| 120 | + "store_tile": ["W", "R"], | ||
| 121 | + "move": ["W", "R"], # move(out, src, ...) | ||
| 122 | + "move_fp": ["W", "R", "R"], # move_fp(out, src, fp_tile) | ||
| 123 | + "insert": ["W", "R"], # insert(out, src, ...) | ||
| 124 | + | ||
| 125 | + # ===== Matmul ===== | ||
| 126 | + "matmul": ["W", "R", "R"], # matmul(out, lhs, rhs) | ||
| 127 | + "matmul_acc": ["W", "RW", "R", "R"], # matmul_acc(out, acc, lhs, rhs) | ||
| 128 | + "matmul_bias": ["W", "R", "R", "R"], # matmul_bias(out, lhs, rhs, bias) | ||
| 129 | + "gemv": ["W", "R", "R"], | ||
| 130 | + "gemv_acc": ["W", "RW", "R", "R"], | ||
| 131 | + "gemv_bias": ["W", "R", "R", "R"], | ||
| 132 | + | ||
| 133 | + # ===== Binary element-wise ===== | ||
| 134 | + "add": ["W", "R", "R"], | ||
| 135 | + "sub": ["W", "R", "R"], | ||
| 136 | + "mul": ["W", "R", "R"], | ||
| 137 | + "div": ["W", "R", "R"], | ||
| 138 | + "rem": ["W", "R", "R"], | ||
| 139 | + "maximum": ["W", "R", "R"], | ||
| 140 | + "minimum": ["W", "R", "R"], | ||
| 141 | + "and_": ["W", "R", "R"], | ||
| 142 | + "or_": ["W", "R", "R"], | ||
| 143 | + "xor": ["W", "R", "R", None], | ||
| 144 | + "shl": ["W", "R", "R"], | ||
| 145 | + "shr": ["W", "R", "R"], | ||
| 146 | + "lrelu": ["W", "R", "R"], | ||
| 147 | + "prelu": ["W", "R", "R", None], | ||
| 148 | + | ||
| 149 | + # ===== Tile-scalar (rhs is scalar, not tile) ===== | ||
| 150 | + "adds": ["W", "R", None], | ||
| 151 | + "subs": ["W", "R", None], | ||
| 152 | + "muls": ["W", "R", None], | ||
| 153 | + "divs": ["W", "R", None], | ||
| 154 | + "rems": ["W", "R", None], | ||
| 155 | + "ands": ["W", "R", None], | ||
| 156 | + "ors": ["W", "R", None], | ||
| 157 | + "xors": ["W", "R", None, None], | ||
| 158 | + "shls": ["W", "R", None], | ||
| 159 | + "shrs": ["W", "R", None], | ||
| 160 | + "maxs": ["W", "R", None], | ||
| 161 | + "mins": ["W", "R", None], | ||
| 162 | + | ||
| 163 | + # ===== Unary ===== | ||
| 164 | + "neg": ["W", "R"], | ||
| 165 | + "exp": ["W", "R"], | ||
| 166 | + "log": ["W", "R"], | ||
| 167 | + "sqrt": ["W", "R"], | ||
| 168 | + "rsqrt": ["W", "R"], | ||
| 169 | + "recip": ["W", "R"], | ||
| 170 | + "abs": ["W", "R"], | ||
| 171 | + "relu": ["W", "R"], | ||
| 172 | + "not_": ["W", "R"], | ||
| 173 | + | ||
| 174 | + # ===== Type cast ===== | ||
| 175 | + "cast": ["W", "R"], # cast(out, src, *, mode) | ||
| 176 | + | ||
| 177 | + # ===== Ternary ===== | ||
| 178 | + "addc": ["W", "R", "R", "R"], | ||
| 179 | + "subc": ["W", "R", "R", "R"], | ||
| 180 | + "addsc": ["W", "R", None, "R"], | ||
| 181 | + "subsc": ["W", "R", None, "R"], | ||
| 182 | + | ||
| 183 | + # ===== Select / compare ===== | ||
| 184 | + "select": ["W", "R", "R", "R", None], | ||
| 185 | + "eq": ["W", "R", "R"], | ||
| 186 | + "ne": ["W", "R", "R"], | ||
| 187 | + "lt": ["W", "R", "R"], | ||
| 188 | + "le": ["W", "R", "R"], | ||
| 189 | + "gt": ["W", "R", "R"], | ||
| 190 | + "ge": ["W", "R", "R"], | ||
| 191 | + | ||
| 192 | + # ===== Reduce (unified: dim=0 → row, dim=1 → col) ===== | ||
| 193 | + "sum": ["W", "R", None], | ||
| 194 | + "argmax": ["W", "R", None], | ||
| 195 | + "argmin": ["W", "R", None], | ||
| 196 | + "row_prod": ["W", "R", None], | ||
| 197 | + "col_prod": ["W", "R", None], | ||
| 198 | + "row_expand": ["W", "R"], | ||
| 199 | + "col_expand": ["W", "R"], | ||
| 200 | + "row_expand_add": ["W", "R", "R"], | ||
| 201 | + "expand_sub": ["W", "R", "R"], | ||
| 202 | + "expand_mul": ["W", "R", "R"], | ||
| 203 | + "expand_div": ["W", "R", "R"], | ||
| 204 | + "expand_max": ["W", "R", "R"], | ||
| 205 | + "expand_min": ["W", "R", "R"], | ||
| 206 | + "row_expand_binop": ["W", "R", "R"], | ||
| 207 | + "col_expand_binop": ["W", "R", "R"], | ||
| 208 | + "expands": ["W", None], | ||
| 209 | + | ||
| 210 | + # ===== Layout ===== | ||
| 211 | + "reshape": ["W", "R", None], | ||
| 212 | + "transpose": ["W", "R"], | ||
| 213 | + "ub_copy": ["W", "R"], | ||
| 214 | + | ||
| 215 | + # ===== Fill ===== | ||
| 216 | + "full": ["W", None], | ||
| 217 | + "fillpad": ["W", "R"], | ||
| 218 | + "fillpad_expand": ["W", "R"], | ||
| 219 | + "fillpad_inplace": ["RW", "R"], | ||
| 220 | +} | ||
| 221 | + | ||
| 222 | + | ||
| 223 | +def get_op_tile_roles(op_name: str) -> list | None: | ||
| 224 | + """Return the per-arg tile role list for the given op, or None if unknown. | ||
| 225 | + | ||
| 226 | + Returns: | ||
| 227 | + List of role strings ("W"/"R"/"RW") or None for non-tile arg positions. | ||
| 228 | + Returns None if op_name is not in the table (caller should skip cross-core | ||
| 229 | + sync emission for unknown ops to be safe). | ||
| 230 | + """ | ||
| 231 | + return _BLOCK_OP_TILE_ROLES.get(op_name) | ||
| @@ -0,0 +1,170 @@ | |||
| 1 | +# Copyright (c) PyPTO Contributors. | ||
| 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 | +"""Scope management and SSA verification for IR parsing.""" | ||
| 11 | +from __future__ import annotations | ||
| 12 | + | ||
| 13 | +__all__ = ["ScopeManager", "SSAViolationError", "ScopeIsolationError"] | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +from typing import Any | ||
| 17 | + | ||
| 18 | +from pypto_pro.ir import Span | ||
| 19 | + | ||
| 20 | +from .diagnostics import ScopeIsolationError, SSAViolationError | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +class ScopeManager: | ||
| 24 | + """Manages variable scopes and optionally enforces SSA properties.""" | ||
| 25 | + | ||
| 26 | + def __init__(self, strict_ssa: bool = False): | ||
| 27 | + """Initialize scope manager. | ||
| 28 | + | ||
| 29 | + Args: | ||
| 30 | + strict_ssa: If True, enforce SSA (single assignment per variable). | ||
| 31 | + If False (default), allow variable reassignment. | ||
| 32 | + """ | ||
| 33 | + self.strict_ssa = strict_ssa | ||
| 34 | + self.scopes: list[dict[str, Any]] = [{}] # Stack of scope dictionaries | ||
| 35 | + self.assignments: dict[str, int] = {} # Track assignment count per variable | ||
| 36 | + self.scope_types: list[str] = ["global"] # Track type of each scope | ||
| 37 | + self.var_spans: list[dict[str, Span]] = [{}] # Track span for each variable definition | ||
| 38 | + | ||
| 39 | + def enter_scope(self, scope_type: str) -> None: | ||
| 40 | + """Enter a new scope. | ||
| 41 | + | ||
| 42 | + Args: | ||
| 43 | + scope_type: Type of scope ('function', 'for', 'if') | ||
| 44 | + """ | ||
| 45 | + self.scopes.append({}) | ||
| 46 | + self.var_spans.append({}) | ||
| 47 | + self.scope_types.append(scope_type) | ||
| 48 | + | ||
| 49 | + def exit_scope(self, leak_vars: bool = False) -> dict[str, Any]: | ||
| 50 | + """Exit current scope and return defined variables. | ||
| 51 | + | ||
| 52 | + Args: | ||
| 53 | + leak_vars: If True, copy all variables from exiting scope to parent scope. | ||
| 54 | + Used for plain syntax where variables should be visible after for/if. | ||
| 55 | + | ||
| 56 | + Returns: | ||
| 57 | + Dictionary of variables defined in the exited scope | ||
| 58 | + """ | ||
| 59 | + if len(self.scopes) <= 1: | ||
| 60 | + raise RuntimeError("Cannot exit global scope") | ||
| 61 | + | ||
| 62 | + scope_vars = self.scopes.pop() | ||
| 63 | + self.var_spans.pop() | ||
| 64 | + self.scope_types.pop() | ||
| 65 | + | ||
| 66 | + # Leak variables to parent scope if requested | ||
| 67 | + if leak_vars and self.scopes: | ||
| 68 | + parent_scope = self.scopes[-1] | ||
| 69 | + for name, value in scope_vars.items(): | ||
| 70 | + parent_scope[name] = value | ||
| 71 | + | ||
| 72 | + return scope_vars | ||
| 73 | + | ||
| 74 | + def define_var(self, name: str, value: Any, allow_redef: bool = False, span: Any | None = None) -> None: | ||
| 75 | + """Define a variable in the current scope. | ||
| 76 | + | ||
| 77 | + Args: | ||
| 78 | + name: Variable name | ||
| 79 | + value: Variable value/node | ||
| 80 | + allow_redef: If True, allow redefinition (for iter_args and parameters) | ||
| 81 | + span: Optional source location span for error reporting | ||
| 82 | + | ||
| 83 | + Raises: | ||
| 84 | + SSAViolationError: If strict_ssa=True and variable is already defined in current scope | ||
| 85 | + """ | ||
| 86 | + current_scope = self.scopes[-1] | ||
| 87 | + current_spans = self.var_spans[-1] | ||
| 88 | + | ||
| 89 | + # Check SSA: variable should not already be defined in current scope | ||
| 90 | + if name in current_scope and not allow_redef: | ||
| 91 | + if self.strict_ssa: | ||
| 92 | + # Get the previous definition span | ||
| 93 | + previous_span = current_spans.get(name) | ||
| 94 | + | ||
| 95 | + raise SSAViolationError( | ||
| 96 | + f"Variable '{name}' is already defined", | ||
| 97 | + span=span, | ||
| 98 | + previous_span=previous_span, | ||
| 99 | + hint="Use a different variable name for each assignment (SSA form requires unique names)", | ||
| 100 | + note="Each variable can only be assigned once per scope", | ||
| 101 | + ) | ||
| 102 | + # In non-SSA mode: just update the variable (no error) | ||
| 103 | + | ||
| 104 | + current_scope[name] = value | ||
| 105 | + if span is not None: | ||
| 106 | + current_spans[name] = span | ||
| 107 | + | ||
| 108 | + # Track assignment count globally | ||
| 109 | + if name not in self.assignments: | ||
| 110 | + self.assignments[name] = 0 | ||
| 111 | + self.assignments[name] += 1 | ||
| 112 | + | ||
| 113 | + def lookup_var(self, name: str) -> Any | None: | ||
| 114 | + """Lookup variable in scope chain. | ||
| 115 | + | ||
| 116 | + Args: | ||
| 117 | + name: Variable name to look up | ||
| 118 | + | ||
| 119 | + Returns: | ||
| 120 | + Variable value/node if found, None otherwise | ||
| 121 | + """ | ||
| 122 | + # Search from innermost to outermost scope | ||
| 123 | + for scope in reversed(self.scopes): | ||
| 124 | + if name in scope: | ||
| 125 | + return scope[name] | ||
| 126 | + return None | ||
| 127 | + | ||
| 128 | + def lookup_var_bounded(self, name: str, barrier: str = "inline") -> Any | None: | ||
| 129 | + """Lookup variable, stopping at the nearest scope of type ``barrier``. | ||
| 130 | + | ||
| 131 | + Used to prevent inline functions from capturing IR variables from the | ||
| 132 | + caller's scope. Variables defined within the inline scope (params, | ||
| 133 | + locals) are found; variables in outer scopes beyond the barrier are not. | ||
| 134 | + """ | ||
| 135 | + for i in range(len(self.scopes) - 1, -1, -1): | ||
| 136 | + if name in self.scopes[i]: | ||
| 137 | + return self.scopes[i][name] | ||
| 138 | + if self.scope_types[i] == barrier: | ||
| 139 | + return None | ||
| 140 | + return None | ||
| 141 | + | ||
| 142 | + def is_defined(self, name: str) -> bool: | ||
| 143 | + """Check if variable is defined in any accessible scope. | ||
| 144 | + | ||
| 145 | + Args: | ||
| 146 | + name: Variable name | ||
| 147 | + | ||
| 148 | + Returns: | ||
| 149 | + True if variable is defined, False otherwise | ||
| 150 | + """ | ||
| 151 | + return self.lookup_var(name) is not None | ||
| 152 | + | ||
| 153 | + def current_scope_type(self) -> str: | ||
| 154 | + """Get the type of the current scope. | ||
| 155 | + | ||
| 156 | + Returns: | ||
| 157 | + Scope type string ('global', 'function', 'for', 'if') | ||
| 158 | + """ | ||
| 159 | + return self.scope_types[-1] | ||
| 160 | + | ||
| 161 | + def in_scope_type(self, scope_type: str) -> bool: | ||
| 162 | + """Check if currently in a specific scope type. | ||
| 163 | + | ||
| 164 | + Args: | ||
| 165 | + scope_type: Type to check for | ||
| 166 | + | ||
| 167 | + Returns: | ||
| 168 | + True if in the specified scope type | ||
| 169 | + """ | ||
| 170 | + return scope_type in self.scope_types | ||
| @@ -0,0 +1,98 @@ | |||
| 1 | +# Copyright (c) PyPTO Contributors. | ||
| 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 | +"""Span tracking for preserving source location information during parsing.""" | ||
| 11 | +from __future__ import annotations | ||
| 12 | + | ||
| 13 | +__all__ = ["SpanTracker"] | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +import ast | ||
| 17 | +from collections.abc import Sequence | ||
| 18 | + | ||
| 19 | +from pypto.pypto_impl import ir | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +class SpanTracker: | ||
| 23 | + """Tracks source locations from AST nodes to IR spans.""" | ||
| 24 | + | ||
| 25 | + def __init__( | ||
| 26 | + self, source_file: str, source_lines: Sequence[str], line_offset: int = 0, col_offset: int = 0 | ||
| 27 | + ): | ||
| 28 | + """Initialize span tracker. | ||
| 29 | + | ||
| 30 | + Args: | ||
| 31 | + source_file: Path to the source file | ||
| 32 | + source_lines: List of source code lines (dedented for parsing) | ||
| 33 | + line_offset: Line number offset to add to AST line numbers (for dedented code) | ||
| 34 | + col_offset: Column offset to add to AST column numbers (for dedented code) | ||
| 35 | + """ | ||
| 36 | + self.source_file = source_file | ||
| 37 | + self.source_lines = source_lines | ||
| 38 | + self.line_offset = line_offset | ||
| 39 | + self.col_offset = col_offset | ||
| 40 | + | ||
| 41 | + def get_span(self, ast_node: ast.AST | None) -> ir.Span: | ||
| 42 | + """Extract span from AST node. | ||
| 43 | + | ||
| 44 | + Args: | ||
| 45 | + ast_node: AST node with line/column information | ||
| 46 | + | ||
| 47 | + Returns: | ||
| 48 | + IR span corresponding to the AST node location | ||
| 49 | + """ | ||
| 50 | + if ast_node is None or not hasattr(ast_node, "lineno"): | ||
| 51 | + return ir.Span.unknown() | ||
| 52 | + | ||
| 53 | + return ir.Span( | ||
| 54 | + self.source_file, | ||
| 55 | + getattr(ast_node, "lineno", 0) + self.line_offset, | ||
| 56 | + getattr(ast_node, "col_offset", 0) + self.col_offset, | ||
| 57 | + getattr(ast_node, "end_lineno", 0) + self.line_offset, | ||
| 58 | + getattr(ast_node, "end_col_offset", 0) + self.col_offset, | ||
| 59 | + ) | ||
| 60 | + | ||
| 61 | + def get_multiline_span(self, start_node: ast.AST, end_node: ast.AST) -> ir.Span: | ||
| 62 | + """Get span covering multiple lines. | ||
| 63 | + | ||
| 64 | + Args: | ||
| 65 | + start_node: AST node at the start | ||
| 66 | + end_node: AST node at the end | ||
| 67 | + | ||
| 68 | + Returns: | ||
| 69 | + IR span covering the range from start to end | ||
| 70 | + """ | ||
| 71 | + if not hasattr(start_node, "lineno") or not hasattr(end_node, "lineno"): | ||
| 72 | + return ir.Span.unknown() | ||
| 73 | + | ||
| 74 | + return ir.Span( | ||
| 75 | + self.source_file, | ||
| 76 | + getattr(start_node, "lineno", 0) + self.line_offset, | ||
| 77 | + getattr(start_node, "col_offset", 0) + self.col_offset, | ||
| 78 | + getattr(end_node, "end_lineno", 0) + self.line_offset, | ||
| 79 | + getattr(end_node, "end_col_offset", 0) + self.col_offset, | ||
| 80 | + ) | ||
| 81 | + | ||
| 82 | + def get_source_text(self, ast_node: ast.AST | None) -> str: | ||
| 83 | + """Recover the original source text for an AST node when available.""" | ||
| 84 | + if ast_node is None: | ||
| 85 | + return "" | ||
| 86 | + | ||
| 87 | + source = "\n".join(self.source_lines) | ||
| 88 | + try: | ||
| 89 | + text = ast.get_source_segment(source, ast_node) | ||
| 90 | + except Exception: | ||
| 91 | + text = None | ||
| 92 | + if text is not None: | ||
| 93 | + return text | ||
| 94 | + | ||
| 95 | + try: | ||
| 96 | + return ast.unparse(ast_node) | ||
| 97 | + except Exception: | ||
| 98 | + return "" | ||
| @@ -0,0 +1,122 @@ | |||
| 1 | +# Copyright (c) PyPTO Contributors. | ||
| 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 | +"""Struct parsing helpers for ASTParser (pl.struct / pl.struct_array / pl.make_tuple).""" | ||
| 11 | + | ||
| 12 | +from __future__ import annotations | ||
| 13 | + | ||
| 14 | +import ast | ||
| 15 | + | ||
| 16 | +from pypto.pypto_impl import ir | ||
| 17 | +from pypto_pro.ir.op._op_registry import op_impl | ||
| 18 | + | ||
| 19 | +from .diagnostics import ParserSyntaxError | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +class StructParserMixin: | ||
| 23 | + """Mixin containing ``pl.struct`` / ``pl.struct_array`` / ``pl.make_tuple`` helpers.""" | ||
| 24 | + | ||
| 25 | + @op_impl("make_tuple") | ||
| 26 | + def _parse_pl_make_tuple_expr(self, call: ast.Call) -> ir.Expr: | ||
| 27 | + span = self.span_tracker.get_span(call) | ||
| 28 | + if call.args: | ||
| 29 | + raise ParserSyntaxError( | ||
| 30 | + "pl.make_tuple() does not accept positional arguments; use keyword args", | ||
| 31 | + span=span, | ||
| 32 | + ) | ||
| 33 | + if not call.keywords: | ||
| 34 | + raise ParserSyntaxError( | ||
| 35 | + "pl.make_tuple() requires at least one keyword argument (field=value)", | ||
| 36 | + span=span, | ||
| 37 | + ) | ||
| 38 | + field_names: list[str] = [] | ||
| 39 | + elements: list[ir.Expr] = [] | ||
| 40 | + for kw in call.keywords: | ||
| 41 | + if kw.arg is None: | ||
| 42 | + raise ParserSyntaxError("pl.make_tuple() does not support **kwargs", span=span) | ||
| 43 | + field_names.append(kw.arg) | ||
| 44 | + elements.append(self.parse_expression(kw.value, nested=True)) | ||
| 45 | + return self.make_named_tuple(elements, field_names, span) | ||
| 46 | + | ||
| 47 | + @op_impl("struct") | ||
| 48 | + def _parse_pl_struct_expr(self, call: ast.Call) -> ir.Expr: | ||
| 49 | + span = self.span_tracker.get_span(call) | ||
| 50 | + struct_name = call.args[0].value | ||
| 51 | + if not call.keywords: | ||
| 52 | + raise ParserSyntaxError( | ||
| 53 | + 'pl.struct("Name", ...) requires at least one keyword field', | ||
| 54 | + span=span, | ||
| 55 | + ) | ||
| 56 | + field_names: list[str] = [] | ||
| 57 | + elements: list[ir.Expr] = [] | ||
| 58 | + for kw in call.keywords: | ||
| 59 | + if kw.arg is None: | ||
| 60 | + raise ParserSyntaxError("pl.struct() does not support **kwargs", span=span) | ||
| 61 | + field_names.append(kw.arg) | ||
| 62 | + elements.append(self.parse_expression(kw.value, nested=True)) | ||
| 63 | + call = ir.create_op_call( | ||
| 64 | + "struct.create", | ||
| 65 | + elements, | ||
| 66 | + {"name": struct_name, "fields": field_names}, | ||
| 67 | + span, | ||
| 68 | + ) | ||
| 69 | + return self.register_struct_fields(call, field_names) | ||
| 70 | + | ||
| 71 | + @op_impl("struct_array") | ||
| 72 | + def _parse_struct_array_expr(self, call: ast.Call) -> ir.Expr: | ||
| 73 | + """Handle ``var = pl.struct_array(N, "StructName", field1=val1, ...)``. | ||
| 74 | + | ||
| 75 | + Lowers to N ``struct.create`` slots wrapped in a MakeTuple. | ||
| 76 | + The caller (_parse_name_assignment) emits the final let-binding. | ||
| 77 | + """ | ||
| 78 | + span = self.span_tracker.get_span(call) | ||
| 79 | + if not call.args or not isinstance(call.args[0], ast.Constant): | ||
| 80 | + raise ParserSyntaxError( | ||
| 81 | + "pl.struct_array() requires an integer size as first argument", | ||
| 82 | + span=span, | ||
| 83 | + hint='Use pl.struct_array(N, "Name", field1=0, field2=0, ...)', | ||
| 84 | + ) | ||
| 85 | + arr_size = call.args[0].value | ||
| 86 | + if not isinstance(arr_size, int) or arr_size < 1: | ||
| 87 | + raise ParserSyntaxError( | ||
| 88 | + f"pl.struct_array() size must be a positive integer, got {arr_size}", | ||
| 89 | + span=span, | ||
| 90 | + ) | ||
| 91 | + if not (len(call.args) >= 2 and isinstance(call.args[1], ast.Constant) | ||
| 92 | + and isinstance(call.args[1].value, str)): | ||
| 93 | + raise ParserSyntaxError( | ||
| 94 | + 'pl.struct_array(N, "Name", ...) requires a string struct name as second arg', | ||
| 95 | + span=span, | ||
| 96 | + ) | ||
| 97 | + struct_name = call.args[1].value | ||
| 98 | + if not call.keywords: | ||
| 99 | + raise ParserSyntaxError( | ||
| 100 | + 'pl.struct_array(N, "Name", ...) requires at least one keyword field', | ||
| 101 | + span=span, | ||
| 102 | + ) | ||
| 103 | + var_name = self.current_target_name | ||
| 104 | + field_names: list[str] = [] | ||
| 105 | + field_inits: list[ir.Expr] = [] | ||
| 106 | + for kw in call.keywords: | ||
| 107 | + if kw.arg is None: | ||
| 108 | + raise ParserSyntaxError("pl.struct_array() does not support **kwargs", span=span) | ||
| 109 | + field_names.append(kw.arg) | ||
| 110 | + field_inits.append(self.parse_expression(kw.value, nested=True)) | ||
| 111 | + slot_vars: list[ir.Expr] = [] | ||
| 112 | + for i in range(arr_size): | ||
| 113 | + slot_call = ir.create_op_call( | ||
| 114 | + "struct.create", | ||
| 115 | + field_inits, | ||
| 116 | + {"name": struct_name, "fields": field_names}, | ||
| 117 | + span, | ||
| 118 | + ) | ||
| 119 | + self.register_struct_fields(slot_call, field_names) | ||
| 120 | + slot_var = self.builder.let(f"{var_name}_{i}", slot_call, span=span) | ||
| 121 | + slot_vars.append(slot_var) | ||
| 122 | + return ir.MakeTuple(slot_vars, span) | ||
| @@ -0,0 +1,34 @@ | |||
| 1 | +# Copyright (c) PyPTO Contributors. | ||
| 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 | +"""Small shared parser utilities.""" | ||
| 11 | +from __future__ import annotations | ||
| 12 | + | ||
| 13 | +__all__ = ["_const_int_value", "_is_const_int"] | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +from pypto.pypto_impl import ir | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +def _is_const_int(value: object) -> bool: | ||
| 20 | + """Check if a value is a compile-time constant integer.""" | ||
| 21 | + if isinstance(value, (int, ir.ConstInt)): | ||
| 22 | + return True | ||
| 23 | + return isinstance(value, ir.Neg) and isinstance(value.operand, ir.ConstInt) | ||
| 24 | + | ||
| 25 | + | ||
| 26 | +def _const_int_value(value: object) -> int | None: | ||
| 27 | + """Extract integer value from a compile-time constant, or None.""" | ||
| 28 | + if isinstance(value, int): | ||
| 29 | + return value | ||
| 30 | + if isinstance(value, ir.ConstInt): | ||
| 31 | + return value.value | ||
| 32 | + if isinstance(value, ir.Neg) and isinstance(value.operand, ir.ConstInt): | ||
| 33 | + return -value.operand.value | ||
| 34 | + return None | ||
| @@ -0,0 +1,252 @@ | |||
| 1 | +# Copyright (c) PyPTO Contributors. | ||
| 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 | +"""Parse DSL functions from text or files without requiring decorator syntax.""" | ||
| 11 | +from __future__ import annotations | ||
| 12 | + | ||
| 13 | +__all__ = ["parse", "loads", "parse_program", "loads_program"] | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +import linecache | ||
| 17 | +import sys | ||
| 18 | +import types | ||
| 19 | + | ||
| 20 | +from pypto.pypto_impl import ir | ||
| 21 | + | ||
| 22 | +from .diagnostics._exceptions import ParserError | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +def parse(code: str, filename: str = "<string>") -> ir.Function | ir.Program: | ||
| 26 | + """Parse a DSL function or program from a string. | ||
| 27 | + | ||
| 28 | + This function takes Python source code containing a @pl.function decorated | ||
| 29 | + function or @pl.program decorated class and parses it into an IR Function | ||
| 30 | + or Program object. The code is executed dynamically, automatically importing | ||
| 31 | + pypto_pro.language as pl if not already present. | ||
| 32 | + | ||
| 33 | + Args: | ||
| 34 | + code: Python source code containing @pl.function or @pl.program | ||
| 35 | + filename: Optional filename for error reporting (default: "<string>") | ||
| 36 | + | ||
| 37 | + Returns: | ||
| 38 | + Parsed ir.Function or ir.Program object (auto-detected) | ||
| 39 | + | ||
| 40 | + Raises: | ||
| 41 | + ValueError: If the code contains nothing to parse or multiple items | ||
| 42 | + ParserError: If parsing fails (syntax errors, type errors, etc.) | ||
| 43 | + | ||
| 44 | + Warning: | ||
| 45 | + This function uses `exec()` to execute the provided code string. | ||
| 46 | + It should only be used with trusted input, as executing untrusted | ||
| 47 | + code can lead to arbitrary code execution vulnerabilities. | ||
| 48 | + | ||
| 49 | + Examples: | ||
| 50 | + >>> import pypto_pro.language as pl | ||
| 51 | + | ||
| 52 | + >>> # Parse a function | ||
| 53 | + >>> func_code = ''' | ||
| 54 | + ... @pl.function | ||
| 55 | + ... def add(x: pl.Tensor[[64], pl.DT_FP32]) -> pl.Tensor[[64], pl.DT_FP32]: | ||
| 56 | + ... result: pl.Tensor[[64], pl.DT_FP32] = pl.add(x, 1.0) | ||
| 57 | + ... return result | ||
| 58 | + ... ''' | ||
| 59 | + >>> func = pl.parse(func_code) | ||
| 60 | + >>> print(func.name) | ||
| 61 | + add | ||
| 62 | + | ||
| 63 | + >>> # Parse a program | ||
| 64 | + >>> prog_code = ''' | ||
| 65 | + ... @pl.program | ||
| 66 | + ... class MyProgram: | ||
| 67 | + ... @pl.function | ||
| 68 | + ... def add(self, x: pl.Tensor[[64], pl.DT_FP32]) -> pl.Tensor[[64], pl.DT_FP32]: | ||
| 69 | + ... return pl.add(x, 1.0) | ||
| 70 | + ... ''' | ||
| 71 | + >>> prog = pl.parse(prog_code) | ||
| 72 | + >>> print(prog.name) | ||
| 73 | + MyProgram | ||
| 74 | + """ | ||
| 75 | + # Import pypto_pro.language here to avoid circular imports | ||
| 76 | + import pypto_pro.language as pl | ||
| 77 | + | ||
| 78 | + # Make the source code available to inspect.getsourcelines() via linecache | ||
| 79 | + # Store ORIGINAL code (not modified) for accurate line numbers | ||
| 80 | + code_lines = code.splitlines(keepends=True) | ||
| 81 | + linecache.cache[filename] = ( | ||
| 82 | + len(code), | ||
| 83 | + None, # mtime | ||
| 84 | + code_lines, | ||
| 85 | + filename, | ||
| 86 | + ) | ||
| 87 | + | ||
| 88 | + # Compile the code with the specified filename for proper error reporting | ||
| 89 | + try: | ||
| 90 | + compiled_code = compile(code, filename, "exec") | ||
| 91 | + except SyntaxError as e: | ||
| 92 | + raise SyntaxError(f"Failed to compile code from {filename}: {e}") from e | ||
| 93 | + | ||
| 94 | + # Create a temporary module for execution | ||
| 95 | + # This ensures inspect.getfile() works correctly for @pl.program | ||
| 96 | + module_name = f"__pypto_parse_{id(code)}__" | ||
| 97 | + temp_module = types.ModuleType(module_name) | ||
| 98 | + temp_module.__file__ = filename | ||
| 99 | + temp_module.__setattr__("pl", pl) | ||
| 100 | + | ||
| 101 | + # Add module to sys.modules so inspect can find it | ||
| 102 | + sys.modules[module_name] = temp_module | ||
| 103 | + | ||
| 104 | + # Execute the code in the module's namespace | ||
| 105 | + try: | ||
| 106 | + exec(compiled_code, temp_module.__dict__) | ||
| 107 | + except ParserError as e: | ||
| 108 | + # Re-raise ParserError as-is, it already has source lines | ||
| 109 | + raise e | ||
| 110 | + except Exception as e: | ||
| 111 | + # Re-raise with context about where the error occurred | ||
| 112 | + raise RuntimeError(f"Error executing code from {filename}: {e}") from e | ||
| 113 | + finally: | ||
| 114 | + # Clean up linecache entry | ||
| 115 | + if filename in linecache.cache: | ||
| 116 | + del linecache.cache[filename] | ||
| 117 | + # Clean up temporary module | ||
| 118 | + if module_name in sys.modules: | ||
| 119 | + del sys.modules[module_name] | ||
| 120 | + | ||
| 121 | + # Get namespace from executed module | ||
| 122 | + namespace = temp_module.__dict__ | ||
| 123 | + | ||
| 124 | + # Scan namespace for ir.Function and ir.Program instances | ||
| 125 | + functions = [] | ||
| 126 | + programs = [] | ||
| 127 | + for name, value in namespace.items(): | ||
| 128 | + if isinstance(value, ir.Function): | ||
| 129 | + functions.append(value) | ||
| 130 | + elif isinstance(value, ir.Program): | ||
| 131 | + programs.append((name, value)) | ||
| 132 | + | ||
| 133 | + # Determine what we found and return appropriate type | ||
| 134 | + total_items = len(functions) + len(programs) | ||
| 135 | + | ||
| 136 | + if total_items == 0: | ||
| 137 | + raise ValueError( | ||
| 138 | + f"No @pl.function or @pl.program found in {filename}. " | ||
| 139 | + "Make sure your code contains a function decorated with @pl.function " | ||
| 140 | + "or a class decorated with @pl.program." | ||
| 141 | + ) | ||
| 142 | + elif total_items > 1: | ||
| 143 | + item_names = [f.name for f in functions] + [name for name, _ in programs] | ||
| 144 | + raise ValueError( | ||
| 145 | + f"Multiple functions/programs found in {filename}: {item_names}. " | ||
| 146 | + f"pl.parse() can only parse code containing a single function or program. " | ||
| 147 | + f"Consider using separate calls or parsing from separate files." | ||
| 148 | + ) | ||
| 149 | + | ||
| 150 | + # Return the single item we found | ||
| 151 | + if functions: | ||
| 152 | + return functions[0] | ||
| 153 | + else: | ||
| 154 | + return programs[0][1] | ||
| 155 | + | ||
| 156 | + | ||
| 157 | +def loads(filepath: str) -> ir.Function | ir.Program: | ||
| 158 | + """Load a DSL function or program from a file. | ||
| 159 | + | ||
| 160 | + This function reads a Python file containing a @pl.function decorated | ||
| 161 | + function or @pl.program decorated class and parses it into an IR Function | ||
| 162 | + or Program object (auto-detected). | ||
| 163 | + | ||
| 164 | + Args: | ||
| 165 | + filepath: Path to Python file containing @pl.function or @pl.program | ||
| 166 | + | ||
| 167 | + Returns: | ||
| 168 | + Parsed ir.Function or ir.Program object (auto-detected) | ||
| 169 | + | ||
| 170 | + Raises: | ||
| 171 | + FileNotFoundError: If the file does not exist | ||
| 172 | + ValueError: If the file contains nothing to parse or multiple items | ||
| 173 | + ParserError: If parsing fails (syntax errors, type errors, etc.) | ||
| 174 | + | ||
| 175 | + Warning: | ||
| 176 | + This function reads a file and executes its contents. It should only | ||
| 177 | + be used with trusted files, as executing code from untrusted sources | ||
| 178 | + can lead to arbitrary code execution vulnerabilities. | ||
| 179 | + | ||
| 180 | + Examples: | ||
| 181 | + >>> import pypto_pro.language as pl | ||
| 182 | + | ||
| 183 | + >>> # Load a function | ||
| 184 | + >>> func = pl.loads('my_kernel.py') | ||
| 185 | + >>> print(func.name) | ||
| 186 | + | ||
| 187 | + >>> # Load a program | ||
| 188 | + >>> prog = pl.loads('my_program.py') | ||
| 189 | + >>> print(prog.name) | ||
| 190 | + """ | ||
| 191 | + # Read file content | ||
| 192 | + with open(filepath, encoding="utf-8") as f: | ||
| 193 | + code = f.read() | ||
| 194 | + | ||
| 195 | + # Parse using parse() with the filepath for proper error reporting | ||
| 196 | + return parse(code, filename=filepath) | ||
| 197 | + | ||
| 198 | + | ||
| 199 | +def parse_program(code: str, filename: str = "<string>") -> ir.Program: | ||
| 200 | + """Parse a DSL program from a string. | ||
| 201 | + | ||
| 202 | + .. deprecated:: | ||
| 203 | + Use :func:`parse` instead, which auto-detects functions and programs. | ||
| 204 | + | ||
| 205 | + This is now an alias for :func:`parse` that validates the result is a Program. | ||
| 206 | + | ||
| 207 | + Args: | ||
| 208 | + code: Python source code containing a @pl.program decorated class | ||
| 209 | + filename: Optional filename for error reporting (default: "<string>") | ||
| 210 | + | ||
| 211 | + Returns: | ||
| 212 | + Parsed ir.Program object | ||
| 213 | + | ||
| 214 | + Raises: | ||
| 215 | + ValueError: If the code contains a function instead of a program | ||
| 216 | + ParserError: If parsing fails (syntax errors, type errors, etc.) | ||
| 217 | + """ | ||
| 218 | + result = parse(code, filename) | ||
| 219 | + if not isinstance(result, ir.Program): | ||
| 220 | + raise ValueError( | ||
| 221 | + f"Expected @pl.program but found @pl.function in {filename}. " | ||
| 222 | + f"Use pl.parse() for auto-detection or ensure your code contains @pl.program." | ||
| 223 | + ) | ||
| 224 | + return result | ||
| 225 | + | ||
| 226 | + | ||
| 227 | +def loads_program(filepath: str) -> ir.Program: | ||
| 228 | + """Load a DSL program from a file. | ||
| 229 | + | ||
| 230 | + .. deprecated:: | ||
| 231 | + Use :func:`loads` instead, which auto-detects functions and programs. | ||
| 232 | + | ||
| 233 | + This is now an alias for :func:`loads` that validates the result is a Program. | ||
| 234 | + | ||
| 235 | + Args: | ||
| 236 | + filepath: Path to Python file containing @pl.program decorated class | ||
| 237 | + | ||
| 238 | + Returns: | ||
| 239 | + Parsed ir.Program object | ||
| 240 | + | ||
| 241 | + Raises: | ||
| 242 | + FileNotFoundError: If the file does not exist | ||
| 243 | + ValueError: If the file contains a function instead of a program | ||
| 244 | + ParserError: If parsing fails (syntax errors, type errors, etc.) | ||
| 245 | + """ | ||
| 246 | + result = loads(filepath) | ||
| 247 | + if not isinstance(result, ir.Program): | ||
| 248 | + raise ValueError( | ||
| 249 | + f"Expected @pl.program but found @pl.function in {filepath}. " | ||
| 250 | + f"Use pl.loads() for auto-detection or ensure your file contains @pl.program." | ||
| 251 | + ) | ||
| 252 | + return result | ||