Merged
feat(IR): Add basic assert #5348
Jie YinAdd on Aug 7
feat(IR): Add basic assert #5348
Merged
Jie YinAdd on Aug 7
Total: 31 files changed+22462-4463
@@ -139,6 +139,7 @@ class PILContext:
139 self._continue_stack = []139 self._continue_stack = []
140 self._temp_count = 0140 self._temp_count = 0
141 self._prefix = prefix141 self._prefix = prefix
142+ self._ann_assign_in_function = False
142 143 
143 @property144 @property
144 def continue_stack(self) -> list[Optional[tuple[ast.expr, str]]]:145 def continue_stack(self) -> list[Optional[tuple[ast.expr, str]]]:
@@ -149,6 +150,15 @@ class PILContext:
149 self._temp_count += 1150 self._temp_count += 1
150 return name151 return name
151 152 
153+ def ann_assign_in_function_switch(self, switch: bool) -> bool:
154+ curr = self._ann_assign_in_function
155+ self._ann_assign_in_function = switch
156+ return curr
157+ 
158+ @property
159+ def ann_assign_in_function(self):
160+ return self._ann_assign_in_function
161+ 
152 162 
153class PILAttr(Mapping):163class PILAttr(Mapping):
154 ATTR_LIST = [164 ATTR_LIST = [
@@ -1005,7 +1015,11 @@ class PythonParser(PILBuilder, ast.NodeVisitor):
1005 dec_stmts, dec_name = self.visit(dec)1015 dec_stmts, dec_name = self.visit(dec)
1006 decorator_stmts.extend(dec_stmts)1016 decorator_stmts.extend(dec_stmts)
1007 decorator_names.append(dec_name)1017 decorator_names.append(dec_name)
1018+ 
1019+ curr = self._ctx.ann_assign_in_function_switch(True)
1008 body_stmt_list, _ = self.visit_stmts(body)1020 body_stmt_list, _ = self.visit_stmts(body)
1021+ self._ctx.ann_assign_in_function_switch(curr)
1022+ 
1009 func_def = self.create_pil_function_def(1023 func_def = self.create_pil_function_def(
1010 name, args, body_stmt_list, decorator_names, returns, type_comment, node_attr=node_attr1024 name, args, body_stmt_list, decorator_names, returns, type_comment, node_attr=node_attr
1011 )1025 )
@@ -1296,7 +1310,12 @@ class PythonParser(PILBuilder, ast.NodeVisitor):
1296 value_stmts, value_expr = self.visit(value)1310 value_stmts, value_expr = self.visit(value)
1297 else:1311 else:
1298 value_stmts, value_expr = [], None1312 value_stmts, value_expr = [], None
1299- ann_stmts, _ = self.visit(annotation)1313+ if self._ctx.ann_assign_in_function:
1314+ # In function, annotation is not computed. However, local class level annotations
1315+ # are still computed for side effects. So we only compute annotation if we are not in a function.
1316+ ann_stmts = []
1317+ else:
1318+ ann_stmts, _ = self.visit(annotation)
1300 return value_stmts + self.visit_lhs(target, value_expr) + ann_stmts, None1319 return value_stmts + self.visit_lhs(target, value_expr) + ann_stmts, None
1301 1320 
1302 def visit_for(1321 def visit_for(
@@ -0,0 +1,138 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 CANN community contributors.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""Check every ``test_*.py.pil`` is a faithful render of its ``test_*.py``.
12+ 
13+``render.py`` produces a ``.py.pil`` from a ``.py`` (raw) via
14+``ast.parse`` -> ``pil.parse_stmts`` -> ``ast.unparse`` (prefixed with a license
15+header). This test re-applies the same transform to the raw file and compares it
16+against the committed ``.py.pil`` after normalising both sides through
17+``ast.parse`` -> ``ast.unparse``. The round-trip strips comments (the license
18+header) and collapses formatting, so the comparison is purely on the code
19+structure. It deliberately does not execute anything -- the behavioural
20+equivalence of the raw and pil forms is validated separately by running them
21+under pytest.
22+"""
23+ 
24+import ast
25+import glob
26+import importlib.machinery
27+import importlib.util
28+import os
29+import sys
30+import types
31+import unittest
32+ 
33+import pypto.frontend.parser.pil as pil
34+ 
35+DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_pil_builder_data")
36+ 
37+_NON_DATA_FILES = {"test_pil_builder_utils.py"}
38+ 
39+ 
40+def _render(src):
41+ """Apply the pil transform directly: ast.parse -> pil.parse_stmts -> ast.unparse."""
42+ tree = ast.parse(src)
43+ transformed = pil.parse_stmts(tree.body)
44+ return ast.unparse(ast.Module(body=transformed, type_ignores=[]))
45+ 
46+ 
47+def _normalize(src):
48+ """Round-trip source through ast.parse -> ast.unparse to drop comments/format."""
49+ return ast.unparse(ast.parse(src))
50+ 
51+ 
52+class TestPilBuilderRenderSync(unittest.TestCase):
53+ """Each committed ``test_*.py.pil`` must equal the pil transform of ``test_*.py``."""
54+ 
55+ def test_pil_files_in_sync_with_raw(self):
56+ raw_paths = sorted(
57+ p for p in glob.glob(os.path.join(DATA_DIR, "test_*.py"))
58+ if os.path.basename(p) not in _NON_DATA_FILES
59+ )
60+ self.assertTrue(raw_paths, f"no test_*.py found under {DATA_DIR}")
61+ for raw_path in raw_paths:
62+ pil_path = raw_path + ".pil"
63+ stem = os.path.basename(raw_path)
64+ with self.subTest(file=stem):
65+ self.assertTrue(
66+ os.path.exists(pil_path),
67+ f"missing pil render for {stem}; run render.py",
68+ )
69+ with open(raw_path, encoding="utf-8") as f:
70+ raw_src = f.read()
71+ with open(pil_path, encoding="utf-8") as f:
72+ pil_src = f.read()
73+ self.assertEqual(
74+ _normalize(_render(raw_src)),
75+ _normalize(pil_src),
76+ f"{stem}.pil is out of sync with {stem}; run render.py",
77+ )
78+ 
79+ 
80+_PIL_PARENT_PKG = "_pypto_pil_data_pkg"
81+_PIL_CHILD_PKG = _PIL_PARENT_PKG + ".test_pil_builder_data"
82+ 
83+ 
84+def _ensure_pil_package_context():
85+ """Register synthetic packages so ``.py.pil`` relative imports resolve.
86+ 
87+ Each ``test_*.py.pil`` opens with ``from .test_pil_builder_utils import ...``.
88+ To make that relative import work the module must live in a package whose
89+ ``__path__`` is the ``test_pil_builder_data`` directory (where
90+ ``test_pil_builder_utils`` resides). We register two synthetic packages for
91+ that purpose: a parent anchor and a child pointing at
92+ ``test_pil_builder_data``.
93+ """
94+ if _PIL_PARENT_PKG not in sys.modules:
95+ parent = types.ModuleType(_PIL_PARENT_PKG)
96+ parent.__path__ = [os.path.dirname(DATA_DIR)]
97+ sys.modules[_PIL_PARENT_PKG] = parent
98+ if _PIL_CHILD_PKG not in sys.modules:
99+ child = types.ModuleType(_PIL_CHILD_PKG)
100+ child.__path__ = [DATA_DIR]
101+ child.__package__ = _PIL_CHILD_PKG
102+ sys.modules[_PIL_CHILD_PKG] = child
103+ 
104+ 
105+def _load_pil_module(pil_path):
106+ """Load a single ``.py.pil`` file as a Python module via the import API."""
107+ _ensure_pil_package_context()
108+ stem = os.path.basename(pil_path)[:-len(".py.pil")]
109+ mod_name = f"{_PIL_CHILD_PKG}.{stem}"
110+ sys.modules.pop(mod_name, None)
111+ loader = importlib.machinery.SourceFileLoader(mod_name, pil_path)
112+ spec = importlib.util.spec_from_file_location(mod_name, pil_path, loader=loader)
113+ module = importlib.util.module_from_spec(spec)
114+ sys.modules[mod_name] = module
115+ spec.loader.exec_module(module)
116+ return module
117+ 
118+ 
119+class TestPilBuilderRunPil(unittest.TestCase):
120+ """Load every committed ``test_*.py.pil`` via the import API and run its cases."""
121+ 
122+ def test_run_pil_files(self):
123+ pil_paths = sorted(glob.glob(os.path.join(DATA_DIR, "test_*.py.pil")))
124+ self.assertTrue(pil_paths, f"no test_*.py.pil found under {DATA_DIR}")
125+ for pil_path in pil_paths:
126+ stem = os.path.basename(pil_path)
127+ with self.subTest(file=stem):
128+ module = _load_pil_module(pil_path)
129+ suite = unittest.TestLoader().loadTestsFromModule(module)
130+ result = unittest.TestResult()
131+ suite.run(result)
132+ self.assertFalse(result.errors, f"{stem} had errors:\n{result.errors}")
133+ self.assertFalse(result.failures, f"{stem} had failures:\n{result.failures}")
134+ self.assertTrue(result.wasSuccessful(), f"{stem} was not successful")
135+ 
136+ 
137+if __name__ == "__main__":
138+ unittest.main()
@@ -1,680 +0,0 @@
1-#!/usr/bin/env python3
2-# coding: utf-8
3-# Copyright (c) 2026 CANN community contributors.
4-# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5-# CANN Open Software License Agreement Version 2.0 (the "License").
6-# Please refer to the License for details. You may not use this file except in compliance with the License.
7-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8-# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9-# See LICENSE in the root of the software repository for the full text of the License.
10-# -----------------------------------------------------------------------------------------------------------
11- 
12-from test_pil_builder_utils import Expr, TestParser
13- 
14- 
15-def test_pil_builder_expr():
16- with TestParser():
17- # --- expr statement: binop (result discarded) ---
18- 
19- @TestParser.test
20- def expr_binop():
21- Expr.int(0) + Expr.int(1)
22- 
23- # --- expr statement: named expr (side-effectful, target assigned) ---
24- 
25- @TestParser.test
26- def expr_named_expr():
27- (var_a := Expr.int(0))
28- Expr.str(var_a)
29- 
30- 
31-def test_pil_builder_named_expr():
32- with TestParser():
33- # --- named expr in binop ---
34- 
35- @TestParser.test
36- def named_expr_binop():
37- var_x = (var_a := Expr.int(0)) + (var_b := Expr.int(1))
38- Expr.str(var_x)
39- Expr.str(var_a)
40- Expr.str(var_b)
41- 
42- # --- named expr in unary op ---
43- 
44- @TestParser.test
45- def named_expr_unary():
46- var_x = -(var_a := Expr.int(5))
47- Expr.str(var_x)
48- Expr.str(var_a)
49- 
50- # --- named expr as if test ---
51- 
52- @TestParser.test
53- def named_expr_if_true():
54- if var_a := Expr.true(0):
55- Expr.str(1)
56- else:
57- Expr.str(2)
58- Expr.str(var_a)
59- 
60- @TestParser.test
61- def named_expr_if_false():
62- if var_a := Expr.false(0):
63- Expr.str(1)
64- else:
65- Expr.str(2)
66- Expr.str(var_a)
67- 
68- # --- named expr as for iter ---
69- 
70- @TestParser.test
71- def named_expr_for_iter():
72- for var_x in (var_it := [Expr.int(0), Expr.int(1)]):
73- Expr.str(var_x)
74- Expr.str(len(var_it))
75- 
76- # --- named expr as while test ---
77- 
78- @TestParser.test
79- def named_expr_while():
80- var_items = [Expr.int(0), Expr.int(1), Expr.int(2)]
81- var_i = [0]
82- while var_n := (var_i[0] < len(var_items)):
83- Expr.str(var_items[var_i[0]])
84- var_i[0] = var_i[0] + 1
85- Expr.str(var_n)
86- 
87- # --- named expr as call positional arg ---
88- 
89- @TestParser.test
90- def named_expr_call_pos_arg():
91- Expr.str(var_a := Expr.int(0))
92- Expr.str(var_a)
93- 
94- # --- named expr as call keyword arg ---
95- 
96- @TestParser.test
97- def named_expr_call_kw_arg():
98- def func(x):
99- Expr.str(x)
100- 
@@ -1,140 +0,0 @@
1-#!/usr/bin/env python3
2-# coding: utf-8
3-# Copyright (c) 2026 CANN community contributors.
4-# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5-# CANN Open Software License Agreement Version 2.0 (the "License").
6-# Please refer to the License for details. You may not use this file except in compliance with the License.
7-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8-# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9-# See LICENSE in the root of the software repository for the full text of the License.
10-# -----------------------------------------------------------------------------------------------------------
11- 
12-from test_pil_builder_utils import Expr, TestParser
13- 
14- 
15-def test_pil_builder_class():
16- with TestParser():
17- # ================================================================
18- # Part 1: single-op comparisons with each operator
19- # ================================================================
20- 
21- @TestParser.test
22- def cls_basic():
23- class Cls:
24- a = Expr.int(20) + Expr.int(30)
25- b = a + Expr.int(20)
26- c = b + a
27- 
28- _var_a = Cls.a
29- _var_b = Cls.b
30- _var_c = Cls.c
31- 
32- @TestParser.test
33- def cls_decorate():
34- var_e = Expr(0)
35- 
36- @var_e.decorate(1)
37- @var_e.decorate(2)
38- class Cls:
39- a = Expr.int(20) + Expr.int(30)
40- b = a + Expr.int(20)
41- c = b + a
42- 
43- _var_a = Cls.a
44- _var_b = Cls.b
45- _var_c = Cls.c
46- 
47- @TestParser.test
48- def cls_inherit():
49- var_e = Expr(0)
50- 
51- class Base:
52- d = Expr.int(20) + Expr.int(30)
53- 
54- e = [Base]
55- 
56- @var_e.decorate(1)
57- @var_e.decorate(2)
58- class Cls(e[0]):
59- a = Expr.int(20) + Expr.int(30)
60- b = a + Expr.int(20)
61- c = b + a
62- 
63- _var_a = Cls.a
64- _var_b = Cls.b
65- _var_c = Cls.c
66- _var_d = Cls.d
67- 
68- @TestParser.test
69- def cls_inherit_list():
70- var_e = Expr(0)
71- 
72- class Base:
73- d = Expr.int(20) + Expr.int(30)
74- 
75- class Base2:
76- d = Expr.int(100) + Expr.int(110)
77- 
78- e = [Base, Base2]
79- 
80- @var_e.decorate(1)
81- @var_e.decorate(2)
82- class Cls(*e):
83- a = Expr.int(320) + Expr.int(330)
84- b = a + Expr.int(420)
85- c = b + a
86- 
87- _var_a = Cls.a
88- _var_b = Cls.b
89- _var_c = Cls.c
90- _var_d = Cls.d
91- 
92- 
93-def test_pil_builder_with():
94- with TestParser():
95- # ================================================================
96- # Part 1: single-op comparisons with each operator
97- # ================================================================
98- 
99- @TestParser.test
100- def with_basic():
101- class Cls:
102- @classmethod
103- def __enter__(cls):
104- return Expr.str(20) + Expr.str(30)
105- 
106- @classmethod
107- def __exit__(cls, exc_type, exc_value, traceback):
108- Expr.int(40)
109- 
110- with Cls():
111- _var_g = Expr.int(20)
112- 
113- @TestParser.test
114- def with_target():
115- class Cls:
116- @classmethod
117- def __enter__(cls):
118- return Expr.str(20) + Expr.str(30)
119- 
120- @classmethod
121- def __exit__(cls, exc_type, exc_value, traceback):
122- Expr.int(40)
123- 
124- with Cls() as var_f:
125- _var_g = var_f[0]
126- 
127- @TestParser.test
128- def with_multiple_target():
129- class Cls:
130- @classmethod
131- def __enter__(cls):
132- return Expr.str(20) + Expr.str(30)
133- 
134- @classmethod
135- def __exit__(cls, exc_type, exc_value, traceback):
136- Expr.int(40)
137- 
138- with Cls() as var_f0, Cls() as var_f1:
139- _var_g0 = var_f0[0]
140- _var_g1 = var_f1[1]
@@ -1,332 +0,0 @@
1-#!/usr/bin/env python3
2-# coding: utf-8
3-# Copyright (c) 2026 CANN community contributors.
4-# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5-# CANN Open Software License Agreement Version 2.0 (the "License").
6-# Please refer to the License for details. You may not use this file except in compliance with the License.
7-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8-# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9-# See LICENSE in the root of the software repository for the full text of the License.
10-# -----------------------------------------------------------------------------------------------------------
11- 
12-from test_pil_builder_utils import Expr, TestParser
13- 
14- 
15-def test_pil_builder_boolop():
16- with TestParser():
17- 
18- @TestParser.test
19- def true_and_true_and_true():
20- if Expr.true(0) and Expr.true(1) and Expr.true(2):
21- Expr.str(3)
22- else:
23- Expr.str(4)
24- 
25- @TestParser.test
26- def true_and_false_and_true():
27- if Expr.true(0) and Expr.false(1) and Expr.true(2):
28- Expr.str(3)
29- else:
30- Expr.str(4)
31- 
32- @TestParser.test
33- def false_and_true_and_true():
34- if Expr.false(0) and Expr.true(1) and Expr.true(2):
35- Expr.str(3)
36- else:
37- Expr.str(4)
38- 
39- @TestParser.test
40- def false_or_false_or_false():
41- if Expr.true(0) and Expr.true(1) and Expr.true(2):
42- Expr.str(3)
43- else:
44- Expr.str(4)
45- 
46- @TestParser.test
47- def false_or_true_or_false():
48- if Expr.true(0) and Expr.false(1) and Expr.true(2):
49- Expr.str(3)
50- else:
51- Expr.str(4)
52- 
53- @TestParser.test
54- def true_or_false_or_false():
55- if Expr.false(0) and Expr.true(1) and Expr.true(2):
56- Expr.str(3)
57- else:
58- Expr.str(4)
59- 
60- 
61-def test_pil_builder_ifexp():
62- with TestParser():
63- 
64- @TestParser.test
65- def true_test_body_selected():
66- _var_x = Expr.str(0) if Expr.true(1) else Expr.str(2)
67- 
68- @TestParser.test
69- def false_test_orelse_selected():
70- _var_x = Expr.str(0) if Expr.false(1) else Expr.str(2)
71- 
72- @TestParser.test
73- def nested_ifexp_in_body():
74- _var_x = (Expr.str(0) if Expr.true(1) else Expr.str(2)) if Expr.true(3) else Expr.str(4)
75- 
76- @TestParser.test
77- def nested_ifexp_in_orelse():
78- _var_x = Expr.str(0) if Expr.false(1) else (Expr.str(2) if Expr.true(3) else Expr.str(4))
79- 
80- @TestParser.test
81- def nested_ifexp_in_orelse_false():
82- _var_x = Expr.str(0) if Expr.false(1) else (Expr.str(2) if Expr.false(3) else Expr.str(4))
83- 
84- @TestParser.test
85- def ifexp_as_if_test():
86- if Expr.str(0) if Expr.true(1) else Expr.str(2):
87- Expr.str(3)
88- else:
89- Expr.str(4)
90- 
91- 
92-def test_pil_builder_bin_op():
93- with TestParser():
94- 
95- @TestParser.test
96- def add():
97- _var_x = Expr.int(0) + Expr.int(1) * Expr.int(2)
98- _var_y = Expr.int(0) - Expr.int(1) // Expr.int(2)
99- 
100- 
101-def test_pil_builder_unary_op():
102- with TestParser():
103- 
104- @TestParser.test
105- def add():
106- _var_x = -Expr.int(0) + Expr.int(1) * Expr.int(2)
107- _var_y = -Expr.int(0) - Expr.int(1) // Expr.int(2)
108- 
109- 
110-def test_pil_builder_compare():
111- with TestParser():
112- # ================================================================
113- # Part 1: single-op comparisons with each operator
114- # ================================================================
115- 
116- @TestParser.test
117- def cmp_lt_true():
118- var_x = Expr.int(1) < Expr.int(2)
119- Expr.str(var_x)
120- 
121- @TestParser.test
122- def cmp_lt_false():
123- var_x = Expr.int(2) < Expr.int(1)
124- Expr.str(var_x)
125- 
126- @TestParser.test
127- def cmp_lte():
128- var_x = Expr.int(1) <= Expr.int(1)
129- Expr.str(var_x)
130- 
131- @TestParser.test
132- def cmp_gt():
133- var_x = Expr.int(2) > Expr.int(1)
134- Expr.str(var_x)
135- 
136- @TestParser.test
137- def cmp_gte():
138- var_x = Expr.int(2) >= Expr.int(2)
139- Expr.str(var_x)
140- 
141- @TestParser.test
142- def cmp_eq_true():
143- var_x = Expr.int(1) == Expr.int(1)
144- Expr.str(var_x)
145- 
146- @TestParser.test
147- def cmp_eq_false():
148- var_x = Expr.int(1) == Expr.int(2)
149- Expr.str(var_x)
150- 
151- @TestParser.test
152- def cmp_neq():
153- var_x = Expr.int(1) != Expr.int(2)
154- Expr.str(var_x)
155- 
156- @TestParser.test
157- def cmp_is():
158- var_a = Expr.int(0)
159- var_x = var_a is var_a
160- Expr.str(var_x)
161- 
162- @TestParser.test
163- def cmp_is_not():
164- var_a = Expr.int(0)
165- var_b = Expr.int(1)
166- var_x = var_a is not var_b
167- Expr.str(var_x)
168- 
169- @TestParser.test
170- def cmp_in():
171- var_l = [Expr.int(0), Expr.int(1)]
172- var_x = Expr.int(0) in var_l
173- Expr.str(var_x)
174- 
175- @TestParser.test
176- def cmp_not_in():
177- var_l = [Expr.int(0), Expr.int(1)]
178- var_x = Expr.int(2) not in var_l
179- Expr.str(var_x)
180- 
181- # ================================================================
182- # Part 2: chained comparisons (PIL short-circuits via if)
183- # ================================================================
184- 
185- @TestParser.test
186- def cmp_chain_lt_lt_all_true():
187- # e.g. 1 < 2 < 3 — both sub-comparisons true, b evaluated once
188- var_x = Expr.int(1) < Expr.int(2) < Expr.int(3)
189- Expr.str(var_x)
190- 
191- @TestParser.test
192- def cmp_chain_lt_lt_first_false():
193- # e.g. 3 < 2 < 4 — first false, third operand not evaluated
194- var_x = Expr.int(3) < Expr.int(2) < Expr.int(4)
195- Expr.str(var_x)
196- 
197- @TestParser.test
198- def cmp_chain_lt_eq():
199- # e.g. 1 < 2 == 2
200- var_x = Expr.int(1) < Expr.int(2) == Expr.int(2)
201- Expr.str(var_x)
202- 
203- @TestParser.test
204- def cmp_chain_three_ops():
205- # e.g. 1 < 2 <= 3 < 4
206- var_x = Expr.int(1) < Expr.int(2) <= Expr.int(3) < Expr.int(4)
207- Expr.str(var_x)
208- 
209- # ================================================================
210- # Part 3: compare result used in various expression contexts
211- # ================================================================
212- 
213- # --- compare result in binop ---
214- 
215- @TestParser.test
216- def cmp_in_binop():
217- var_x = (Expr.int(1) < Expr.int(2)) + 0
218- Expr.str(var_x)
219- 
220- # --- compare result in unary op ---
221- 
222- @TestParser.test
223- def cmp_in_unary():
224- var_x = not (Expr.int(1) == Expr.int(2))
225- Expr.str(var_x)
226- 
227- # --- compare result as if test ---
228- 
229- @TestParser.test
230- def cmp_if_true():
231- if Expr.int(1) < Expr.int(2):
232- Expr.str(0)
233- else:
234- Expr.str(1)
235- 
236- @TestParser.test
237- def cmp_if_false():
238- if Expr.int(2) < Expr.int(1):
239- Expr.str(0)
240- else:
241- Expr.str(1)
242- 
243- # --- compare result as for iter ---
244- 
245- @TestParser.test
246- def cmp_for_iter():
247- for var_x in [Expr.int(0) < Expr.int(1), Expr.int(2) < Expr.int(1)]:
248- Expr.str(var_x)
249- 
250- # --- compare result as while test ---
251- 
252- @TestParser.test
253- def cmp_while_test():
254- var_n = [0]
255- while var_n[0] < 3:
256- Expr.str(var_n[0])
257- var_n[0] = var_n[0] + 1
258- 
259- # --- compare result as call positional arg ---
260- 
261- @TestParser.test
262- def cmp_call_pos_arg():
263- Expr.str(Expr.int(1) < Expr.int(2))
264- 
265- # --- compare result as call keyword arg ---
266- 
267- @TestParser.test
268- def cmp_call_kw_arg():
269- def func(x):
270- Expr.str(x)
271- 
272- func(x=Expr.int(1) == Expr.int(1))
273- 
274- # --- compare result in tuple literal ---
275- 
276- @TestParser.test
277- def cmp_in_tuple():
278- var_t = (Expr.int(1) < Expr.int(2), Expr.int(3) > Expr.int(4))
279- Expr.str(var_t[0])
280- Expr.str(var_t[1])
281- 
282- # --- compare result in list literal ---
283- 
284- @TestParser.test
285- def cmp_in_list():
286- var_l = [Expr.int(1) < Expr.int(2), Expr.int(3) > Expr.int(4)]
287- Expr.str(var_l[0])
288- Expr.str(var_l[1])
289- 
290- # --- compare result as dict key and value ---
291- 
292- @TestParser.test
293- def cmp_dict_value():
294- var_d = {0: Expr.int(1) < Expr.int(2)}
295- Expr.str(var_d[0])
296- 
297- @TestParser.test
298- def cmp_dict_key():
299- var_d = {Expr.int(1) == Expr.int(1): Expr.int(0)}
300- Expr.str(var_d[True])
301- 
302- # --- compare result in set literal ---
303- 
304- @TestParser.test
305- def cmp_in_set():
306- var_s = {Expr.int(1) < Expr.int(2), Expr.int(3) > Expr.int(4)}
307- Expr.str(True in var_s)
308- 
309- # --- compare result as subscript index ---
310- 
311- @TestParser.test
312- def cmp_as_subscript_index():
313- var_arr = Expr(0)
314- var_arr[True] = Expr.int(99)
315- var_x = var_arr[Expr.int(1) == Expr.int(1)]
316- Expr.str(var_x)
317- 
318- # --- compare result as slice bound ---
319- 
320- @TestParser.test
321- def cmp_as_slice_bound():
322- var_l = [Expr.int(0), Expr.int(1), Expr.int(2)]
323- # True == 1, so slice [True:3] == [1:3]
324- var_s = var_l[Expr.int(1) == Expr.int(1):]
325- Expr.str(var_s[0])
326- 
327- # --- compare result as type annotation ---
328- 
329- @TestParser.test
330- def cmp_annotation_with_value():
331- var_x: bool = Expr.int(1) < Expr.int(2)
332- Expr.str(var_x)
@@ -0,0 +1,9 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+# -----------------------------------------------------------------------------------------------------------
@@ -0,0 +1,24 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 CANN community contributors.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+ 
12+import unittest
13+ 
14+from .test_pil_builder_utils import Expr
15+ 
16+ 
17+class PILTestCase(unittest.TestCase):
18+ 
19+ def setUp(self):
20+ Expr.clear()
21+ 
22+ def get_var(self, data_dict: dict) -> dict:
23+ var_dict = {k: v for k, v in data_dict.items() if k.startswith('var_')}
24+ return var_dict
@@ -0,0 +1,67 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 CANN community contributors.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""Render pil-transformed test sources.
12+ 
13+Reads every ``test_*.raw.py`` in this directory, transforms it through the pil
14+frontend (``ast.parse`` -> ``pil.parse_stmts`` -> ``ast.unparse``) and writes the
15+result to the matching ``test_*.pil.py``. The pil form is semantically
16+equivalent to the raw form (it is a 3-address normalisation), so both should
17+behave identically when executed.
18+"""
19+ 
20+import ast
21+import glob
22+import os
23+ 
24+import pypto.frontend.parser.pil as pil
25+ 
26+_DATA_DIR = os.path.dirname(os.path.abspath(__file__))
27+ 
28+with open(os.path.join(_DATA_DIR, "render_data.txt"), encoding="utf-8") as _f:
29+ _LICENSE = _f.read()
30+ 
31+ 
32+def render(src):
33+ """Transform python source string into its pil-normalised form.
34+ 
35+ The generated source is prefixed with the license header from
36+ ``render_data.txt``.
37+ """
38+ tree = ast.parse(src)
39+ transformed = pil.parse_stmts(tree.body)
40+ code = ast.unparse(ast.Module(body=transformed, type_ignores=[]))
41+ return _LICENSE + "\n" + code + "\n"
42+ 
43+ 
44+def render_file(raw_path):
45+ """Render a single ``test_*.py`` file and return its ``test_*.py.pil`` path."""
46+ with open(raw_path, encoding="utf-8") as f:
47+ src = f.read()
48+ out = render(src)
49+ pil_path = raw_path + ".pil"
50+ with open(pil_path, "w", encoding="utf-8") as f:
51+ f.write(out)
52+ return pil_path
53+ 
54+ 
55+_EXCLUDED = {"test_pil_builder_utils.py"}
56+ 
57+ 
58+def main():
59+ for raw_path in sorted(glob.glob(os.path.join(_DATA_DIR, "test_*.py"))):
60+ if os.path.basename(raw_path) in _EXCLUDED:
61+ continue
62+ pil_path = render_file(raw_path)
63+ print("wrote", os.path.relpath(pil_path))
64+ 
65+ 
66+if __name__ == "__main__":
67+ main()
@@ -0,0 +1,10 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 CANN community contributors.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
@@ -0,0 +1,188 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 CANN community contributors.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+ 
12+from .test_pil_builder_utils import Expr, PILTestCase
13+ 
14+ 
15+class ClassTest(PILTestCase):
16+ 
17+ def test_cls_basic(self):
18+ class Cls:
19+ a = Expr.int(20) + Expr.int(30)
20+ b = a + Expr.int(20)
21+ c = b + a
22+ 
23+ _var_a = Cls.a
24+ _var_b = Cls.b
25+ _var_c = Cls.c
26+ 
27+ self.assertEqual(Expr.trace, [('int', 20), ('int', 30), ('int', 20)])
28+ self.assertEqual(self.get_var(locals()), {})
29+ 
30+ def test_cls_decorate(self):
31+ var_e = Expr(0)
32+ 
33+ @var_e.decorate(1)
34+ @var_e.decorate(2)
35+ class Cls:
36+ a = Expr.int(20) + Expr.int(30)
37+ b = a + Expr.int(20)
38+ c = b + a
39+ 
40+ _var_a = Cls.a
41+ _var_b = Cls.b
42+ _var_c = Cls.c
43+ 
44+ self.assertEqual(
45+ Expr.trace,
46+ [
47+ ('init', 0),
48+ ('decorate', 1),
49+ ('decorate', 2),
50+ ('int', 20),
51+ ('int', 30),
52+ ('int', 20),
53+ ('decorate.wrapper', 2),
54+ ('decorate.wrapper', 1),
55+ ],
56+ )
57+ self.assertEqual(self.get_var(locals()), {'var_e': Expr(0, {}, {})})
58+ 
59+ def test_cls_inherit(self):
60+ var_e = Expr(0)
61+ 
62+ class Base:
63+ d = Expr.int(20) + Expr.int(30)
64+ 
65+ e = [Base]
66+ 
67+ @var_e.decorate(1)
68+ @var_e.decorate(2)
69+ class Cls(e[0]):
70+ a = Expr.int(20) + Expr.int(30)
71+ b = a + Expr.int(20)
72+ c = b + a
73+ 
74+ _var_a = Cls.a
75+ _var_b = Cls.b
76+ _var_c = Cls.c
77+ _var_d = Cls.d
78+ 
79+ self.assertEqual(
80+ Expr.trace,
81+ [
82+ ('init', 0),
83+ ('int', 20),
84+ ('int', 30),
85+ ('decorate', 1),
86+ ('decorate', 2),
87+ ('int', 20),
88+ ('int', 30),
89+ ('int', 20),
90+ ('decorate.wrapper', 2),
91+ ('decorate.wrapper', 1),
92+ ],
93+ )
94+ self.assertEqual(self.get_var(locals()), {'var_e': Expr(0, {}, {})})
95+ 
96+ def test_cls_inherit_list(self):
97+ var_e = Expr(0)
98+ 
99+ class Base:
100+ d = Expr.int(20) + Expr.int(30)
101+ 
102+ class Base2:
103+ d = Expr.int(100) + Expr.int(110)
104+ 
105+ e = [Base, Base2]
106+ 
107+ @var_e.decorate(1)
108+ @var_e.decorate(2)
109+ class Cls(*e):
110+ a = Expr.int(320) + Expr.int(330)
111+ b = a + Expr.int(420)
112+ c = b + a
113+ 
114+ _var_a = Cls.a
115+ _var_b = Cls.b
116+ _var_c = Cls.c
117+ _var_d = Cls.d
118+ 
119+ self.assertEqual(
120+ Expr.trace,
121+ [
122+ ('init', 0),
123+ ('int', 20),
124+ ('int', 30),
125+ ('int', 100),
126+ ('int', 110),
127+ ('decorate', 1),
128+ ('decorate', 2),
129+ ('int', 320),
130+ ('int', 330),
131+ ('int', 420),
132+ ('decorate.wrapper', 2),
133+ ('decorate.wrapper', 1),
134+ ],
135+ )
136+ self.assertEqual(self.get_var(locals()), {'var_e': Expr(0, {}, {})})
137+ 
138+ 
139+class WithTest(PILTestCase):
140+ 
141+ def test_with_basic(self):
142+ class Cls:
143+ @classmethod
144+ def __enter__(cls):
145+ return Expr.str(20) + Expr.str(30)
146+ 
147+ @classmethod
148+ def __exit__(cls, exc_type, exc_value, traceback):
149+ Expr.int(40)
150+ 
151+ with Cls():
152+ _var_g = Expr.int(20)
153+ 
154+ self.assertEqual(Expr.trace, [('str', 20), ('str', 30), ('int', 20), ('int', 40)])
155+ self.assertEqual(self.get_var(locals()), {})
156+ 
157+ def test_with_target(self):
158+ class Cls:
159+ @classmethod
160+ def __enter__(cls):
161+ return Expr.str(20) + Expr.str(30)
162+ 
163+ @classmethod
164+ def __exit__(cls, exc_type, exc_value, traceback):
165+ Expr.int(40)
166+ 
167+ with Cls() as var_f:
168+ _var_g = var_f[0]
169+ 
170+ self.assertEqual(Expr.trace, [('str', 20), ('str', 30), ('int', 40)])
171+ self.assertEqual(self.get_var(locals()), {'var_f': 'str(20)str(30)'})
172+ 
173+ def test_with_multiple_target(self):
174+ class Cls:
175+ @classmethod
176+ def __enter__(cls):
177+ return Expr.str(20) + Expr.str(30)
178+ 
179+ @classmethod
180+ def __exit__(cls, exc_type, exc_value, traceback):
181+ Expr.int(40)
182+ 
183+ with Cls() as var_f0, Cls() as var_f1:
184+ _var_g0 = var_f0[0]
185+ _var_g1 = var_f1[1]
186+ 
187+ self.assertEqual(Expr.trace, [('str', 20), ('str', 30), ('str', 20), ('str', 30), ('int', 40), ('int', 40)])
188+ self.assertEqual(self.get_var(locals()), {'var_f0': 'str(20)str(30)', 'var_f1': 'str(20)str(30)'})
@@ -0,0 +1,360 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 CANN community contributors.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+ 
12+from .test_pil_builder_utils import Expr, PILTestCase
13+ 
14+class ClassTest(PILTestCase):
15+ 
16+ def test_cls_basic(self):
17+ 
18+ class Cls:
19+ _pil_0 = Expr.int
20+ _pil_1 = _pil_0(20)
21+ _pil_2 = Expr.int
22+ _pil_3 = _pil_2(30)
23+ _pil_4 = _pil_1 + _pil_3
24+ a = _pil_4
25+ _pil_5 = Expr.int
26+ _pil_6 = _pil_5(20)
27+ _pil_7 = a + _pil_6
28+ b = _pil_7
29+ _pil_8 = b + a
30+ c = _pil_8
31+ _pil_9 = Cls.a
32+ _var_a = _pil_9
33+ _pil_10 = Cls.b
34+ _var_b = _pil_10
35+ _pil_11 = Cls.c
36+ _var_c = _pil_11
37+ _pil_12 = self.assertEqual
38+ _pil_13 = Expr.trace
39+ _pil_15 = ('int', 20)
40+ _pil_16 = ('int', 30)
41+ _pil_17 = ('int', 20)
42+ _pil_14 = [_pil_15, _pil_16, _pil_17]
43+ _pil_18 = _pil_12(_pil_13, _pil_14)
44+ _pil_19 = self.assertEqual
45+ _pil_20 = self.get_var
46+ _pil_21 = locals()
47+ _pil_22 = _pil_20(_pil_21)
48+ _pil_23 = {}
49+ _pil_24 = _pil_19(_pil_22, _pil_23)
50+ 
51+ def test_cls_decorate(self):
52+ _pil_25 = Expr(0)
53+ var_e = _pil_25
54+ _pil_26 = var_e.decorate
55+ _pil_27 = _pil_26(1)
56+ _pil_28 = var_e.decorate
57+ _pil_29 = _pil_28(2)
58+ 
59+ @_pil_27
60+ @_pil_29
61+ class Cls:
62+ _pil_30 = Expr.int
63+ _pil_31 = _pil_30(20)
64+ _pil_32 = Expr.int
65+ _pil_33 = _pil_32(30)
66+ _pil_34 = _pil_31 + _pil_33
67+ a = _pil_34
68+ _pil_35 = Expr.int
69+ _pil_36 = _pil_35(20)
70+ _pil_37 = a + _pil_36
71+ b = _pil_37
72+ _pil_38 = b + a
73+ c = _pil_38
74+ _pil_39 = Cls.a
75+ _var_a = _pil_39
76+ _pil_40 = Cls.b
77+ _var_b = _pil_40
78+ _pil_41 = Cls.c
79+ _var_c = _pil_41
80+ _pil_42 = self.assertEqual
81+ _pil_43 = Expr.trace
82+ _pil_45 = ('init', 0)
83+ _pil_46 = ('decorate', 1)
84+ _pil_47 = ('decorate', 2)
85+ _pil_48 = ('int', 20)
86+ _pil_49 = ('int', 30)
87+ _pil_50 = ('int', 20)
88+ _pil_51 = ('decorate.wrapper', 2)
89+ _pil_52 = ('decorate.wrapper', 1)
90+ _pil_44 = [_pil_45, _pil_46, _pil_47, _pil_48, _pil_49, _pil_50, _pil_51, _pil_52]
91+ _pil_53 = _pil_42(_pil_43, _pil_44)
92+ _pil_54 = self.assertEqual
93+ _pil_55 = self.get_var
94+ _pil_56 = locals()
95+ _pil_57 = _pil_55(_pil_56)
96+ _pil_58 = {}
97+ _pil_59 = {}
98+ _pil_60 = Expr(0, _pil_58, _pil_59)
99+ _pil_61 = {'var_e': _pil_60}
100+ _pil_62 = _pil_54(_pil_57, _pil_61)
101+ 
102+ def test_cls_inherit(self):
103+ _pil_63 = Expr(0)
104+ var_e = _pil_63
105+ 
106+ class Base:
107+ _pil_64 = Expr.int
108+ _pil_65 = _pil_64(20)
109+ _pil_66 = Expr.int
110+ _pil_67 = _pil_66(30)
111+ _pil_68 = _pil_65 + _pil_67
112+ d = _pil_68
113+ _pil_69 = [Base]
114+ e = _pil_69
115+ _pil_70 = var_e.decorate
116+ _pil_71 = _pil_70(1)
117+ _pil_72 = var_e.decorate
118+ _pil_73 = _pil_72(2)
119+ _pil_83 = e[0]
120+ 
121+ @_pil_71
122+ @_pil_73
123+ class Cls(_pil_83):
124+ _pil_74 = Expr.int
125+ _pil_75 = _pil_74(20)
126+ _pil_76 = Expr.int
127+ _pil_77 = _pil_76(30)
128+ _pil_78 = _pil_75 + _pil_77
129+ a = _pil_78
130+ _pil_79 = Expr.int
131+ _pil_80 = _pil_79(20)
132+ _pil_81 = a + _pil_80
133+ b = _pil_81
134+ _pil_82 = b + a
135+ c = _pil_82
136+ _pil_84 = Cls.a
137+ _var_a = _pil_84
138+ _pil_85 = Cls.b
139+ _var_b = _pil_85
140+ _pil_86 = Cls.c
141+ _var_c = _pil_86
142+ _pil_87 = Cls.d
143+ _var_d = _pil_87
144+ _pil_88 = self.assertEqual
145+ _pil_89 = Expr.trace
146+ _pil_91 = ('init', 0)
147+ _pil_92 = ('int', 20)
148+ _pil_93 = ('int', 30)
149+ _pil_94 = ('decorate', 1)
150+ _pil_95 = ('decorate', 2)
151+ _pil_96 = ('int', 20)
152+ _pil_97 = ('int', 30)
153+ _pil_98 = ('int', 20)
154+ _pil_99 = ('decorate.wrapper', 2)
155+ _pil_100 = ('decorate.wrapper', 1)
156+ _pil_90 = [_pil_91, _pil_92, _pil_93, _pil_94, _pil_95, _pil_96, _pil_97, _pil_98, _pil_99, _pil_100]
157+ _pil_101 = _pil_88(_pil_89, _pil_90)
158+ _pil_102 = self.assertEqual
159+ _pil_103 = self.get_var
160+ _pil_104 = locals()
161+ _pil_105 = _pil_103(_pil_104)
162+ _pil_106 = {}
163+ _pil_107 = {}
164+ _pil_108 = Expr(0, _pil_106, _pil_107)
165+ _pil_109 = {'var_e': _pil_108}
166+ _pil_110 = _pil_102(_pil_105, _pil_109)
167+ 
168+ def test_cls_inherit_list(self):
169+ _pil_111 = Expr(0)
170+ var_e = _pil_111
171+ 
172+ class Base:
173+ _pil_112 = Expr.int
174+ _pil_113 = _pil_112(20)
175+ _pil_114 = Expr.int
176+ _pil_115 = _pil_114(30)
177+ _pil_116 = _pil_113 + _pil_115
178+ d = _pil_116
179+ 
180+ class Base2:
181+ _pil_117 = Expr.int
182+ _pil_118 = _pil_117(100)
183+ _pil_119 = Expr.int
184+ _pil_120 = _pil_119(110)
185+ _pil_121 = _pil_118 + _pil_120
186+ d = _pil_121
187+ _pil_122 = [Base, Base2]
188+ e = _pil_122
189+ _pil_123 = var_e.decorate
190+ _pil_124 = _pil_123(1)
191+ _pil_125 = var_e.decorate
192+ _pil_126 = _pil_125(2)
193+ 
194+ @_pil_124
195+ @_pil_126
196+ class Cls(*e):
197+ _pil_127 = Expr.int
198+ _pil_128 = _pil_127(320)
199+ _pil_129 = Expr.int
200+ _pil_130 = _pil_129(330)
201+ _pil_131 = _pil_128 + _pil_130
202+ a = _pil_131
203+ _pil_132 = Expr.int
204+ _pil_133 = _pil_132(420)
205+ _pil_134 = a + _pil_133
206+ b = _pil_134
207+ _pil_135 = b + a
208+ c = _pil_135
209+ _pil_136 = Cls.a
210+ _var_a = _pil_136
211+ _pil_137 = Cls.b
212+ _var_b = _pil_137
213+ _pil_138 = Cls.c
214+ _var_c = _pil_138
215+ _pil_139 = Cls.d
216+ _var_d = _pil_139
217+ _pil_140 = self.assertEqual
218+ _pil_141 = Expr.trace
219+ _pil_143 = ('init', 0)
220+ _pil_144 = ('int', 20)
221+ _pil_145 = ('int', 30)
222+ _pil_146 = ('int', 100)
223+ _pil_147 = ('int', 110)
224+ _pil_148 = ('decorate', 1)
225+ _pil_149 = ('decorate', 2)
226+ _pil_150 = ('int', 320)
227+ _pil_151 = ('int', 330)
228+ _pil_152 = ('int', 420)
229+ _pil_153 = ('decorate.wrapper', 2)
230+ _pil_154 = ('decorate.wrapper', 1)
231+ _pil_142 = [_pil_143, _pil_144, _pil_145, _pil_146, _pil_147, _pil_148, _pil_149, _pil_150, _pil_151, _pil_152, _pil_153, _pil_154]
232+ _pil_155 = _pil_140(_pil_141, _pil_142)
233+ _pil_156 = self.assertEqual
234+ _pil_157 = self.get_var
235+ _pil_158 = locals()
236+ _pil_159 = _pil_157(_pil_158)
237+ _pil_160 = {}
238+ _pil_161 = {}
239+ _pil_162 = Expr(0, _pil_160, _pil_161)
240+ _pil_163 = {'var_e': _pil_162}
241+ _pil_164 = _pil_156(_pil_159, _pil_163)
242+ 
243+class WithTest(PILTestCase):
244+ 
245+ def test_with_basic(self):
246+ 
247+ class Cls:
248+ 
249+ @classmethod
250+ def __enter__(cls):
251+ _pil_165 = Expr.str
252+ _pil_166 = _pil_165(20)
253+ _pil_167 = Expr.str
254+ _pil_168 = _pil_167(30)
255+ _pil_169 = _pil_166 + _pil_168
256+ return _pil_169
257+ 
258+ @classmethod
259+ def __exit__(cls, exc_type, exc_value, traceback):
260+ _pil_170 = Expr.int
261+ _pil_171 = _pil_170(40)
262+ _pil_174 = Cls()
263+ with _pil_174:
264+ _pil_172 = Expr.int
265+ _pil_173 = _pil_172(20)
266+ _var_g = _pil_173
267+ _pil_175 = self.assertEqual
268+ _pil_176 = Expr.trace
269+ _pil_178 = ('str', 20)
270+ _pil_179 = ('str', 30)
271+ _pil_180 = ('int', 20)
272+ _pil_181 = ('int', 40)
273+ _pil_177 = [_pil_178, _pil_179, _pil_180, _pil_181]
274+ _pil_182 = _pil_175(_pil_176, _pil_177)
275+ _pil_183 = self.assertEqual
276+ _pil_184 = self.get_var
277+ _pil_185 = locals()
278+ _pil_186 = _pil_184(_pil_185)
279+ _pil_187 = {}
280+ _pil_188 = _pil_183(_pil_186, _pil_187)
281+ 
282+ def test_with_target(self):
283+ 
284+ class Cls:
285+ 
286+ @classmethod
287+ def __enter__(cls):
288+ _pil_189 = Expr.str
289+ _pil_190 = _pil_189(20)
290+ _pil_191 = Expr.str
291+ _pil_192 = _pil_191(30)
292+ _pil_193 = _pil_190 + _pil_192
293+ return _pil_193
294+ 
295+ @classmethod
296+ def __exit__(cls, exc_type, exc_value, traceback):
297+ _pil_194 = Expr.int
298+ _pil_195 = _pil_194(40)
299+ _pil_197 = Cls()
300+ with _pil_197 as _pil_198:
301+ var_f = _pil_198
302+ _pil_196 = var_f[0]
303+ _var_g = _pil_196
304+ _pil_199 = self.assertEqual
305+ _pil_200 = Expr.trace
306+ _pil_202 = ('str', 20)
307+ _pil_203 = ('str', 30)
308+ _pil_204 = ('int', 40)
309+ _pil_201 = [_pil_202, _pil_203, _pil_204]
310+ _pil_205 = _pil_199(_pil_200, _pil_201)
311+ _pil_206 = self.assertEqual
312+ _pil_207 = self.get_var
313+ _pil_208 = locals()
314+ _pil_209 = _pil_207(_pil_208)
315+ _pil_210 = {'var_f': 'str(20)str(30)'}
316+ _pil_211 = _pil_206(_pil_209, _pil_210)
317+ 
318+ def test_with_multiple_target(self):
319+ 
320+ class Cls:
321+ 
322+ @classmethod
323+ def __enter__(cls):
324+ _pil_212 = Expr.str
325+ _pil_213 = _pil_212(20)
326+ _pil_214 = Expr.str
327+ _pil_215 = _pil_214(30)
328+ _pil_216 = _pil_213 + _pil_215
329+ return _pil_216
330+ 
331+ @classmethod
332+ def __exit__(cls, exc_type, exc_value, traceback):
333+ _pil_217 = Expr.int
334+ _pil_218 = _pil_217(40)
335+ _pil_223 = Cls()
336+ with _pil_223 as _pil_224:
337+ var_f0 = _pil_224
338+ _pil_221 = Cls()
339+ with _pil_221 as _pil_222:
340+ var_f1 = _pil_222
341+ _pil_219 = var_f0[0]
342+ _var_g0 = _pil_219
343+ _pil_220 = var_f1[1]
344+ _var_g1 = _pil_220
345+ _pil_225 = self.assertEqual
346+ _pil_226 = Expr.trace
347+ _pil_228 = ('str', 20)
348+ _pil_229 = ('str', 30)
349+ _pil_230 = ('str', 20)
350+ _pil_231 = ('str', 30)
351+ _pil_232 = ('int', 40)
352+ _pil_233 = ('int', 40)
353+ _pil_227 = [_pil_228, _pil_229, _pil_230, _pil_231, _pil_232, _pil_233]
354+ _pil_234 = _pil_225(_pil_226, _pil_227)
355+ _pil_235 = self.assertEqual
356+ _pil_236 = self.get_var
357+ _pil_237 = locals()
358+ _pil_238 = _pil_236(_pil_237)
359+ _pil_239 = {'var_f0': 'str(20)str(30)', 'var_f1': 'str(20)str(30)'}
360+ _pil_240 = _pil_235(_pil_238, _pil_239)
@@ -0,0 +1,391 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 CANN community contributors.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+ 
12+from .test_pil_builder_utils import Expr, PILTestCase
13+ 
14+ 
15+class BoolopTest(PILTestCase):
16+ 
17+ def test_true_and_true_and_true(self):
18+ if Expr.true(0) and Expr.true(1) and Expr.true(2):
19+ Expr.str(3)
20+ else:
21+ Expr.str(4)
22+ 
23+ self.assertEqual(Expr.trace, [('true', 0), ('true', 1), ('true', 2), ('str', 3)])
24+ self.assertEqual(self.get_var(locals()), {})
25+ 
26+ def test_true_and_false_and_true(self):
27+ if Expr.true(0) and Expr.false(1) and Expr.true(2):
28+ Expr.str(3)
29+ else:
30+ Expr.str(4)
31+ 
32+ self.assertEqual(Expr.trace, [('true', 0), ('false', 1), ('str', 4)])
33+ self.assertEqual(self.get_var(locals()), {})
34+ 
35+ def test_false_and_true_and_true(self):
36+ if Expr.false(0) and Expr.true(1) and Expr.true(2):
37+ Expr.str(3)
38+ else:
39+ Expr.str(4)
40+ 
41+ self.assertEqual(Expr.trace, [('false', 0), ('str', 4)])
42+ self.assertEqual(self.get_var(locals()), {})
43+ 
44+ def test_false_or_false_or_false(self):
45+ if Expr.true(0) and Expr.true(1) and Expr.true(2):
46+ Expr.str(3)
47+ else:
48+ Expr.str(4)
49+ 
50+ self.assertEqual(Expr.trace, [('true', 0), ('true', 1), ('true', 2), ('str', 3)])
51+ self.assertEqual(self.get_var(locals()), {})
52+ 
53+ def test_false_or_true_or_false(self):
54+ if Expr.true(0) and Expr.false(1) and Expr.true(2):
55+ Expr.str(3)
56+ else:
57+ Expr.str(4)
58+ 
59+ self.assertEqual(Expr.trace, [('true', 0), ('false', 1), ('str', 4)])
60+ self.assertEqual(self.get_var(locals()), {})
61+ 
62+ def test_true_or_false_or_false(self):
63+ if Expr.false(0) and Expr.true(1) and Expr.true(2):
64+ Expr.str(3)
65+ else:
66+ Expr.str(4)
67+ 
68+ self.assertEqual(Expr.trace, [('false', 0), ('str', 4)])
69+ self.assertEqual(self.get_var(locals()), {})
70+ 
71+ 
72+class IfexpTest(PILTestCase):
73+ 
74+ def test_true_test_body_selected(self):
75+ _var_x = Expr.str(0) if Expr.true(1) else Expr.str(2)
76+ 
77+ self.assertEqual(Expr.trace, [('true', 1), ('str', 0)])
78+ self.assertEqual(self.get_var(locals()), {})
79+ 
80+ def test_false_test_orelse_selected(self):
81+ _var_x = Expr.str(0) if Expr.false(1) else Expr.str(2)
82+ 
83+ self.assertEqual(Expr.trace, [('false', 1), ('str', 2)])
84+ self.assertEqual(self.get_var(locals()), {})
85+ 
86+ def test_nested_ifexp_in_body(self):
87+ _var_x = (Expr.str(0) if Expr.true(1) else Expr.str(2)) if Expr.true(3) else Expr.str(4)
88+ 
89+ self.assertEqual(Expr.trace, [('true', 3), ('true', 1), ('str', 0)])
90+ self.assertEqual(self.get_var(locals()), {})
91+ 
92+ def test_nested_ifexp_in_orelse(self):
93+ _var_x = Expr.str(0) if Expr.false(1) else (Expr.str(2) if Expr.true(3) else Expr.str(4))
94+ 
95+ self.assertEqual(Expr.trace, [('false', 1), ('true', 3), ('str', 2)])
96+ self.assertEqual(self.get_var(locals()), {})
97+ 
98+ def test_nested_ifexp_in_orelse_false(self):
99+ _var_x = Expr.str(0) if Expr.false(1) else (Expr.str(2) if Expr.false(3) else Expr.str(4))
100+ 
101+ self.assertEqual(Expr.trace, [('false', 1), ('false', 3), ('str', 4)])
102+ self.assertEqual(self.get_var(locals()), {})
103+ 
104+ def test_ifexp_as_if_test(self):
105+ if Expr.str(0) if Expr.true(1) else Expr.str(2):
106+ Expr.str(3)
107+ else:
108+ Expr.str(4)
109+ 
110+ self.assertEqual(Expr.trace, [('true', 1), ('str', 0), ('str', 3)])
111+ self.assertEqual(self.get_var(locals()), {})
112+ 
113+ 
114+class BinOpTest(PILTestCase):
115+ 
116+ def test_add(self):
117+ _var_x = Expr.int(0) + Expr.int(1) * Expr.int(2)
118+ _var_y = Expr.int(0) - Expr.int(1) // Expr.int(2)
119+ 
120+ self.assertEqual(Expr.trace, [('int', 0), ('int', 1), ('int', 2), ('int', 0), ('int', 1), ('int', 2)])
121+ self.assertEqual(self.get_var(locals()), {})
122+ 
123+ 
124+class UnaryOpTest(PILTestCase):
125+ 
126+ def test_add(self):
127+ _var_x = -Expr.int(0) + Expr.int(1) * Expr.int(2)
128+ _var_y = -Expr.int(0) - Expr.int(1) // Expr.int(2)
129+ 
130+ self.assertEqual(Expr.trace, [('int', 0), ('int', 1), ('int', 2), ('int', 0), ('int', 1), ('int', 2)])
131+ self.assertEqual(self.get_var(locals()), {})
132+ 
133+ 
134+class CompareTest(PILTestCase):
135+ 
136+ def test_cmp_lt_true(self):
137+ var_x = Expr.int(1) < Expr.int(2)
138+ Expr.str(var_x)
139+ 
140+ self.assertEqual(Expr.trace, [('int', 1), ('int', 2), ('str', True)])
141+ self.assertEqual(self.get_var(locals()), {'var_x': True})
142+ 
143+ def test_cmp_lt_false(self):
144+ var_x = Expr.int(2) < Expr.int(1)
145+ Expr.str(var_x)
146+ 
147+ self.assertEqual(Expr.trace, [('int', 2), ('int', 1), ('str', False)])
148+ self.assertEqual(self.get_var(locals()), {'var_x': False})
149+ 
150+ def test_cmp_lte(self):
151+ var_x = Expr.int(1) <= Expr.int(1)
152+ Expr.str(var_x)
153+ 
154+ self.assertEqual(Expr.trace, [('int', 1), ('int', 1), ('str', True)])
155+ self.assertEqual(self.get_var(locals()), {'var_x': True})
156+ 
157+ def test_cmp_gt(self):
158+ var_x = Expr.int(2) > Expr.int(1)
159+ Expr.str(var_x)
160+ 
161+ self.assertEqual(Expr.trace, [('int', 2), ('int', 1), ('str', True)])
162+ self.assertEqual(self.get_var(locals()), {'var_x': True})
163+ 
164+ def test_cmp_gte(self):
165+ var_x = Expr.int(2) >= Expr.int(2)
166+ Expr.str(var_x)
167+ 
168+ self.assertEqual(Expr.trace, [('int', 2), ('int', 2), ('str', True)])
169+ self.assertEqual(self.get_var(locals()), {'var_x': True})
170+ 
171+ def test_cmp_eq_true(self):
172+ var_x = Expr.int(1) == Expr.int(1)
173+ Expr.str(var_x)
174+ 
175+ self.assertEqual(Expr.trace, [('int', 1), ('int', 1), ('str', True)])
176+ self.assertEqual(self.get_var(locals()), {'var_x': True})
177+ 
178+ def test_cmp_eq_false(self):
179+ var_x = Expr.int(1) == Expr.int(2)
180+ Expr.str(var_x)
181+ 
182+ self.assertEqual(Expr.trace, [('int', 1), ('int', 2), ('str', False)])
183+ self.assertEqual(self.get_var(locals()), {'var_x': False})
184+ 
185+ def test_cmp_neq(self):
186+ var_x = Expr.int(1) != Expr.int(2)
187+ Expr.str(var_x)
188+ 
189+ self.assertEqual(Expr.trace, [('int', 1), ('int', 2), ('str', True)])
190+ self.assertEqual(self.get_var(locals()), {'var_x': True})
191+ 
192+ def test_cmp_is(self):
193+ var_a = Expr.int(0)
194+ var_x = var_a is var_a
195+ Expr.str(var_x)
196+ 
197+ self.assertEqual(Expr.trace, [('int', 0), ('str', True)])
198+ self.assertEqual(self.get_var(locals()), {'var_a': 0, 'var_x': True})
199+ 
200+ def test_cmp_is_not(self):
201+ var_a = Expr.int(0)
202+ var_b = Expr.int(1)
203+ var_x = var_a is not var_b
204+ Expr.str(var_x)
205+ 
206+ self.assertEqual(Expr.trace, [('int', 0), ('int', 1), ('str', True)])
207+ self.assertEqual(self.get_var(locals()), {'var_a': 0, 'var_b': 1, 'var_x': True})
208+ 
209+ def test_cmp_in(self):
210+ var_l = [Expr.int(0), Expr.int(1)]
211+ var_x = Expr.int(0) in var_l
212+ Expr.str(var_x)
213+ 
214+ self.assertEqual(Expr.trace, [('int', 0), ('int', 1), ('int', 0), ('str', True)])
215+ self.assertEqual(self.get_var(locals()), {'var_l': [0, 1], 'var_x': True})
216+ 
217+ def test_cmp_not_in(self):
218+ var_l = [Expr.int(0), Expr.int(1)]
219+ var_x = Expr.int(2) not in var_l
220+ Expr.str(var_x)
221+ 
222+ self.assertEqual(Expr.trace, [('int', 0), ('int', 1), ('int', 2), ('str', True)])
223+ self.assertEqual(self.get_var(locals()), {'var_l': [0, 1], 'var_x': True})
224+ 
225+ def test_cmp_chain_lt_lt_all_true(self):
226+ # e.g. 1 < 2 < 3 — both sub-comparisons true, b evaluated once
227+ var_x = Expr.int(1) < Expr.int(2) < Expr.int(3)
228+ Expr.str(var_x)
229+ 
230+ self.assertEqual(Expr.trace, [('int', 1), ('int', 2), ('int', 3), ('str', True)])
231+ self.assertEqual(self.get_var(locals()), {'var_x': True})
232+ 
233+ def test_cmp_chain_lt_lt_first_false(self):
234+ # e.g. 3 < 2 < 4 — first false, third operand not evaluated
235+ var_x = Expr.int(3) < Expr.int(2) < Expr.int(4)
236+ Expr.str(var_x)
237+ 
238+ self.assertEqual(Expr.trace, [('int', 3), ('int', 2), ('str', False)])
239+ self.assertEqual(self.get_var(locals()), {'var_x': False})
240+ 
241+ def test_cmp_chain_lt_eq(self):
242+ # e.g. 1 < 2 == 2
243+ var_x = Expr.int(1) < Expr.int(2) == Expr.int(2)
244+ Expr.str(var_x)
245+ 
246+ self.assertEqual(Expr.trace, [('int', 1), ('int', 2), ('int', 2), ('str', True)])
247+ self.assertEqual(self.get_var(locals()), {'var_x': True})
248+ 
249+ def test_cmp_chain_three_ops(self):
250+ # e.g. 1 < 2 <= 3 < 4
251+ var_x = Expr.int(1) < Expr.int(2) <= Expr.int(3) < Expr.int(4)
252+ Expr.str(var_x)
253+ 
254+ self.assertEqual(Expr.trace, [('int', 1), ('int', 2), ('int', 3), ('int', 4), ('str', True)])
255+ self.assertEqual(self.get_var(locals()), {'var_x': True})
256+ 
257+ def test_cmp_in_binop(self):
258+ var_x = (Expr.int(1) < Expr.int(2)) + 0
259+ Expr.str(var_x)
260+ 
261+ self.assertEqual(Expr.trace, [('int', 1), ('int', 2), ('str', 1)])
262+ self.assertEqual(self.get_var(locals()), {'var_x': 1})
263+ 
264+ def test_cmp_in_unary(self):
265+ var_x = not (Expr.int(1) == Expr.int(2))
266+ Expr.str(var_x)
267+ 
268+ self.assertEqual(Expr.trace, [('int', 1), ('int', 2), ('str', True)])
269+ self.assertEqual(self.get_var(locals()), {'var_x': True})
270+ 
271+ def test_cmp_if_true(self):
272+ if Expr.int(1) < Expr.int(2):
273+ Expr.str(0)
274+ else:
275+ Expr.str(1)
276+ 
277+ self.assertEqual(Expr.trace, [('int', 1), ('int', 2), ('str', 0)])
278+ self.assertEqual(self.get_var(locals()), {})
279+ 
280+ def test_cmp_if_false(self):
281+ if Expr.int(2) < Expr.int(1):
282+ Expr.str(0)
283+ else:
284+ Expr.str(1)
285+ 
286+ self.assertEqual(Expr.trace, [('int', 2), ('int', 1), ('str', 1)])
287+ self.assertEqual(self.get_var(locals()), {})
288+ 
289+ def test_cmp_for_iter(self):
290+ for var_x in [Expr.int(0) < Expr.int(1), Expr.int(2) < Expr.int(1)]:
291+ Expr.str(var_x)
292+ 
293+ self.assertEqual(Expr.trace, [('int', 0), ('int', 1), ('int', 2), ('int', 1), ('str', True), ('str', False)])
294+ self.assertEqual(self.get_var(locals()), {'var_x': False})
295+ 
296+ def test_cmp_while_test(self):
297+ var_n = [0]
298+ while var_n[0] < 3:
299+ Expr.str(var_n[0])
300+ var_n[0] = var_n[0] + 1
301+ 
302+ self.assertEqual(Expr.trace, [('str', 0), ('str', 1), ('str', 2)])
303+ self.assertEqual(self.get_var(locals()), {'var_n': [3]})
304+ 
305+ def test_cmp_call_pos_arg(self):
306+ Expr.str(Expr.int(1) < Expr.int(2))
307+ 
308+ self.assertEqual(Expr.trace, [('int', 1), ('int', 2), ('str', True)])
309+ self.assertEqual(self.get_var(locals()), {})
310+ 
311+ def test_cmp_call_kw_arg(self):
312+ def func(x):
313+ Expr.str(x)
314+ 
315+ func(x=Expr.int(1) == Expr.int(1))
316+ 
317+ self.assertEqual(Expr.trace, [('int', 1), ('int', 1), ('str', True)])
318+ self.assertEqual(self.get_var(locals()), {})
319+ 
320+ def test_cmp_in_tuple(self):
321+ var_t = (Expr.int(1) < Expr.int(2), Expr.int(3) > Expr.int(4))
322+ Expr.str(var_t[0])
323+ Expr.str(var_t[1])
324+ 
325+ self.assertEqual(Expr.trace, [('int', 1), ('int', 2), ('int', 3), ('int', 4), ('str', True), ('str', False)])
326+ self.assertEqual(self.get_var(locals()), {'var_t': (True, False)})
327+ 
328+ def test_cmp_in_list(self):
329+ var_l = [Expr.int(1) < Expr.int(2), Expr.int(3) > Expr.int(4)]
330+ Expr.str(var_l[0])
331+ Expr.str(var_l[1])
332+ 
333+ self.assertEqual(Expr.trace, [('int', 1), ('int', 2), ('int', 3), ('int', 4), ('str', True), ('str', False)])
334+ self.assertEqual(self.get_var(locals()), {'var_l': [True, False]})
335+ 
336+ def test_cmp_dict_value(self):
337+ var_d = {0: Expr.int(1) < Expr.int(2)}
338+ Expr.str(var_d[0])
339+ 
340+ self.assertEqual(Expr.trace, [('int', 1), ('int', 2), ('str', True)])
341+ self.assertEqual(self.get_var(locals()), {'var_d': {0: True}})
342+ 
343+ def test_cmp_dict_key(self):
344+ var_d = {Expr.int(1) == Expr.int(1): Expr.int(0)}
345+ Expr.str(var_d[True])
346+ 
347+ self.assertEqual(Expr.trace, [('int', 1), ('int', 1), ('int', 0), ('str', 0)])
348+ self.assertEqual(self.get_var(locals()), {'var_d': {True: 0}})
349+ 
350+ def test_cmp_in_set(self):
351+ var_s = {Expr.int(1) < Expr.int(2), Expr.int(3) > Expr.int(4)}
352+ Expr.str(True in var_s)
353+ 
354+ self.assertEqual(Expr.trace, [('int', 1), ('int', 2), ('int', 3), ('int', 4), ('str', True)])
355+ self.assertEqual(self.get_var(locals()), {'var_s': {False, True}})
356+ 
357+ def test_cmp_as_subscript_index(self):
358+ var_arr = Expr(0)
359+ var_arr[True] = Expr.int(99)
360+ var_x = var_arr[Expr.int(1) == Expr.int(1)]
361+ Expr.str(var_x)
362+ 
363+ self.assertEqual(
364+ Expr.trace,
365+ [
366+ ('init', 0),
367+ ('int', 99),
368+ ('setitem', 0, True, 99),
369+ ('int', 1),
370+ ('int', 1),
371+ ('getitem', 0, True),
372+ ('str', 99),
373+ ],
374+ )
375+ self.assertEqual(self.get_var(locals()), {'var_arr': Expr(0, {True: 99}, {}), 'var_x': 99})
376+ 
377+ def test_cmp_as_slice_bound(self):
378+ var_l = [Expr.int(0), Expr.int(1), Expr.int(2)]
379+ # True == 1, so slice [True:3] == [1:3]
380+ var_s = var_l[Expr.int(1) == Expr.int(1):]
381+ Expr.str(var_s[0])
382+ 
383+ self.assertEqual(Expr.trace, [('int', 0), ('int', 1), ('int', 2), ('int', 1), ('int', 1), ('str', 1)])
384+ self.assertEqual(self.get_var(locals()), {'var_l': [0, 1, 2], 'var_s': [1, 2]})
385+ 
386+ def test_cmp_annotation_with_value(self):
387+ var_x: bool = Expr.int(1) < Expr.int(2)
388+ Expr.str(var_x)
389+ 
390+ self.assertEqual(Expr.trace, [('int', 1), ('int', 2), ('str', True)])
391+ self.assertEqual(self.get_var(locals()), {'var_x': True})
@@ -0,0 +1,468 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 CANN community contributors.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+ 
12+from .test_pil_builder_utils import Expr, PILTestCase
13+ 
14+ 
15+class RaiseTest(PILTestCase):
16+ 
17+ def test_raise_bare(self):
18+ try:
19+ raise Expr.TypeA(0)
20+ except Expr.TypeA:
21+ try:
22+ raise
23+ except Expr.TypeA:
24+ Expr.str(1)
25+ 
26+ self.assertEqual(Expr.trace, [('error', 0), ('str', 1)])
27+ self.assertEqual(self.get_var(locals()), {})
28+ 
29+ def test_raise_bare_simple(self):
30+ try:
31+ try:
32+ raise Expr.TypeA(0)
33+ except Expr.TypeA:
34+ raise
35+ except Expr.TypeA as e:
36+ Expr.int(e.value)
37+ 
38+ self.assertEqual(Expr.trace, [('error', 0), ('int', 0)])
39+ self.assertEqual(self.get_var(locals()), {})
40+ 
41+ def test_raise_name(self):
42+ try:
43+ exc = Expr.TypeA(0)
44+ raise exc
45+ except Expr.TypeA as e:
46+ Expr.int(e.value)
47+ 
48+ self.assertEqual(Expr.trace, [('error', 0), ('int', 0)])
49+ self.assertEqual(self.get_var(locals()), {})
50+ 
51+ def test_raise_attribute(self):
52+ var_obj = Expr(0)
53+ var_obj.val = Expr.TypeB(1)
54+ try:
55+ raise var_obj.val
56+ except Expr.TypeB as e:
57+ Expr.int(e.value)
58+ 
59+ self.assertEqual(
60+ list(Expr.trace),
61+ [('init', 0), ('error', 1), ('setattr', 0, 'val', Expr.TypeB(1)), ('getattr', 0, 'val'), ('int', 1)],
62+ )
63+ self.assertEqual(self.get_var(locals()), {'var_obj': Expr(0, {}, {'val': Expr.TypeB(1)})})
64+ 
65+ def test_raise_subscript(self):
66+ var_obj = Expr(0)
67+ var_obj[Expr.str(1)] = Expr.TypeC(2)
68+ try:
69+ raise var_obj[Expr.str(1)]
70+ except Expr.TypeC as e:
71+ Expr.int(e.value)
72+ 
73+ self.assertEqual(
74+ list(Expr.trace),
75+ [
76+ ('init', 0),
77+ ('error', 2),
78+ ('str', 1),
79+ ('setitem', 0, 'str(1)', Expr.TypeC(2)),
80+ ('str', 1),
81+ ('getitem', 0, 'str(1)'),
82+ ('int', 2),
83+ ],
84+ )
85+ self.assertEqual(self.get_var(locals()), {'var_obj': Expr(0, {'str(1)': Expr.TypeC(2)}, {})})
86+ 
87+ def test_raise_ifexp_true(self):
88+ try:
89+ raise Expr.TypeA(0) if Expr.true(1) else Expr.TypeB(2)
90+ except Expr.TypeA as e:
91+ Expr.int(e.value)
92+ 
93+ self.assertEqual(Expr.trace, [('true', 1), ('error', 0), ('int', 0)])
94+ self.assertEqual(self.get_var(locals()), {})
95+ 
96+ def test_raise_ifexp_false(self):
97+ try:
98+ raise Expr.TypeA(0) if Expr.false(1) else Expr.TypeB(2)
99+ except Expr.TypeB as e:
100+ Expr.int(e.value)
101+ 
102+ self.assertEqual(Expr.trace, [('false', 1), ('error', 2), ('int', 2)])
103+ self.assertEqual(self.get_var(locals()), {})
104+ 
105+ def test_raise_from_name(self):
106+ try:
107+ cause = Expr.TypeA(0)
108+ raise Expr.TypeB(1) from cause
109+ except Expr.TypeB as e:
110+ Expr.int(e.value)
111+ 
112+ self.assertEqual(Expr.trace, [('error', 0), ('error', 1), ('int', 1)])
113+ self.assertEqual(self.get_var(locals()), {})
114+ 
115+ def test_raise_from_attribute(self):
116+ var_obj = Expr(0)
117+ var_obj.val = Expr.TypeA(1)
118+ try:
119+ raise Expr.TypeB(2) from var_obj.val
120+ except Expr.TypeB as e:
121+ Expr.int(e.value)
122+ 
123+ self.assertEqual(
124+ list(Expr.trace),
125+ [
126+ ('init', 0),
127+ ('error', 1),
128+ ('setattr', 0, 'val', Expr.TypeA(1)),
129+ ('error', 2),
130+ ('getattr', 0, 'val'),
131+ ('int', 2),
132+ ],
133+ )
134+ self.assertEqual(self.get_var(locals()), {'var_obj': Expr(0, {}, {'val': Expr.TypeA(1)})})
135+ 
136+ def test_raise_attribute_from_subscript(self):
137+ var_obj = Expr(0)
138+ var_obj.val = Expr.TypeB(1)
139+ var_obj[Expr.str(2)] = Expr.TypeA(3)
140+ try:
141+ raise var_obj.val from var_obj[Expr.str(2)]
142+ except Expr.TypeB as e:
143+ Expr.int(e.value)
144+ 
145+ self.assertEqual(
146+ list(Expr.trace),
147+ [
148+ ('init', 0),
149+ ('error', 1),
150+ ('setattr', 0, 'val', Expr.TypeB(1)),
151+ ('error', 3),
152+ ('str', 2),
153+ ('setitem', 0, 'str(2)', Expr.TypeA(3)),
154+ ('getattr', 0, 'val'),
155+ ('str', 2),
156+ ('getitem', 0, 'str(2)'),
157+ ('int', 1),
158+ ],
159+ )
160+ self.assertEqual(
161+ self.get_var(locals()),
162+ {'var_obj': Expr(0, {'str(2)': Expr.TypeA(3)}, {'val': Expr.TypeB(1)})},
163+ )
164+ 
165+ 
166+class TryTest(PILTestCase):
167+ 
168+ def test_try_single_typed_no_binding(self):
169+ try:
170+ raise Expr.TypeA(0)
171+ except Expr.TypeA:
172+ Expr.str(1)
173+ 
174+ self.assertEqual(Expr.trace, [('error', 0), ('str', 1)])
175+ self.assertEqual(self.get_var(locals()), {})
176+ 
177+ def test_try_single_typed_with_binding(self):
178+ try:
179+ raise Expr.TypeA(0)
180+ except Expr.TypeA as e:
181+ Expr.str(e.value)
182+ 
183+ self.assertEqual(Expr.trace, [('error', 0), ('str', 0)])
184+ self.assertEqual(self.get_var(locals()), {})
185+ 
186+ def test_try_multi_handler_typea(self):
187+ try:
188+ raise Expr.TypeA(0)
189+ except Expr.TypeA:
190+ Expr.str(10)
191+ except Expr.TypeB:
192+ Expr.str(20)
193+ except Expr.TypeC:
194+ Expr.str(30)
195+ 
196+ self.assertEqual(Expr.trace, [('error', 0), ('str', 10)])
197+ self.assertEqual(self.get_var(locals()), {})
198+ 
199+ def test_try_multi_handler_typeb(self):
200+ try:
201+ raise Expr.TypeB(0)
202+ except Expr.TypeA:
203+ Expr.str(10)
204+ except Expr.TypeB:
205+ Expr.str(20)
206+ except Expr.TypeC:
207+ Expr.str(30)
208+ 
209+ self.assertEqual(Expr.trace, [('error', 0), ('str', 20)])
210+ self.assertEqual(self.get_var(locals()), {})
211+ 
212+ def test_try_multi_handler_typec(self):
213+ try:
214+ raise Expr.TypeC(0)
215+ except Expr.TypeA:
216+ Expr.str(10)
217+ except Expr.TypeB:
218+ Expr.str(20)
219+ except Expr.TypeC:
220+ Expr.str(30)
221+ 
222+ self.assertEqual(Expr.trace, [('error', 0), ('str', 30)])
223+ self.assertEqual(self.get_var(locals()), {})
224+ 
225+ def test_try_bare_except(self):
226+ try:
227+ raise Expr.TypeA(0)
228+ except Expr.TypeB:
229+ Expr.str(10)
230+ except Exception:
231+ Expr.str(20)
232+ 
233+ self.assertEqual(Expr.trace, [('error', 0), ('str', 20)])
234+ self.assertEqual(self.get_var(locals()), {})
235+ 
236+ def test_try_else_no_exception(self):
237+ try:
238+ Expr.str(0)
239+ except Expr.TypeA:
240+ Expr.str(10)
241+ else:
242+ Expr.str(20)
243+ 
244+ self.assertEqual(Expr.trace, [('str', 0), ('str', 20)])
245+ self.assertEqual(self.get_var(locals()), {})
246+ 
247+ def test_try_else_with_exception(self):
248+ try:
249+ if Expr.true(0):
250+ raise Expr.TypeA(1)
251+ except Expr.TypeA:
252+ Expr.str(10)
253+ else:
254+ Expr.str(20)
255+ 
256+ self.assertEqual(Expr.trace, [('true', 0), ('error', 1), ('str', 10)])
257+ self.assertEqual(self.get_var(locals()), {})
258+ 
259+ def test_try_finally_no_exception(self):
260+ try:
261+ Expr.str(0)
262+ finally:
263+ Expr.str(1)
264+ 
265+ self.assertEqual(Expr.trace, [('str', 0), ('str', 1)])
266+ self.assertEqual(self.get_var(locals()), {})
267+ 
268+ def test_try_finally_with_exception(self):
269+ try:
270+ raise Expr.TypeA(0)
271+ except Expr.TypeA:
272+ Expr.str(10)
273+ finally:
274+ Expr.str(20)
275+ 
276+ self.assertEqual(Expr.trace, [('error', 0), ('str', 10), ('str', 20)])
277+ self.assertEqual(self.get_var(locals()), {})
278+ 
279+ def test_try_combined_no_exception(self):
280+ try:
281+ Expr.str(0)
282+ except Expr.TypeA as e:
283+ Expr.int(e.value)
284+ except Expr.TypeB as e:
285+ Expr.str(e.value)
286+ else:
287+ Expr.str(30)
288+ finally:
289+ Expr.str(40)
290+ 
291+ self.assertEqual(Expr.trace, [('str', 0), ('str', 30), ('str', 40)])
292+ self.assertEqual(self.get_var(locals()), {})
293+ 
294+ def test_try_combined_typea(self):
295+ try:
296+ if Expr.true(0):
297+ raise Expr.TypeA(1)
298+ except Expr.TypeA as e:
299+ Expr.int(e.value)
300+ except Expr.TypeB as e:
301+ Expr.str(e.value)
302+ else:
303+ Expr.str(30)
304+ finally:
305+ Expr.str(40)
306+ 
307+ self.assertEqual(Expr.trace, [('true', 0), ('error', 1), ('int', 1), ('str', 40)])
308+ self.assertEqual(self.get_var(locals()), {})
309+ 
310+ def test_try_combined_typeb(self):
311+ try:
312+ if Expr.true(0):
313+ raise Expr.TypeB(1)
314+ except Expr.TypeA as e:
315+ Expr.int(e.value)
316+ except Expr.TypeB as e:
317+ Expr.str(e.value)
318+ else:
319+ Expr.str(30)
320+ finally:
321+ Expr.str(40)
322+ 
323+ self.assertEqual(Expr.trace, [('true', 0), ('error', 1), ('str', 1), ('str', 40)])
324+ self.assertEqual(self.get_var(locals()), {})
325+ 
326+ def test_try_nested(self):
327+ try:
328+ try:
329+ raise Expr.TypeA(0)
330+ except Expr.TypeB:
331+ Expr.str(10)
332+ except Expr.TypeA as e:
333+ Expr.int(e.value)
334+ 
335+ self.assertEqual(Expr.trace, [('error', 0), ('int', 0)])
336+ self.assertEqual(self.get_var(locals()), {})
337+ 
338+ 
339+class AssertTest(PILTestCase):
340+ 
341+ def test_assert_pass_subscript(self):
342+ var_obj = Expr(0)
343+ var_obj[Expr.str(1)] = Expr.true(2)
344+ assert var_obj[Expr.str(1)]
345+ 
346+ self.assertEqual(
347+ Expr.trace,
348+ [
349+ ('init', 0),
350+ ('true', 2),
351+ ('str', 1),
352+ ('setitem', 0, 'str(1)', True),
353+ ('str', 1),
354+ ('getitem', 0, 'str(1)'),
355+ ],
356+ )
357+ self.assertEqual(self.get_var(locals()), {'var_obj': Expr(0, {'str(1)': True}, {})})
358+ 
359+ def test_assert_pass_subscript_msg_call(self):
360+ var_obj = Expr(0)
361+ var_obj[Expr.str(1)] = Expr.true(2)
362+ assert var_obj[Expr.str(1)], Expr.str(3)
363+ 
364+ self.assertEqual(
365+ Expr.trace,
366+ [
367+ ('init', 0),
368+ ('true', 2),
369+ ('str', 1),
370+ ('setitem', 0, 'str(1)', True),
371+ ('str', 1),
372+ ('getitem', 0, 'str(1)'),
373+ ],
374+ )
375+ self.assertEqual(self.get_var(locals()), {'var_obj': Expr(0, {'str(1)': True}, {})})
376+ 
377+ def test_assert_pass_subscript_msg_name(self):
378+ var_msg = 'assertion failed'
379+ var_obj = Expr(0)
380+ var_obj[Expr.str(1)] = Expr.true(2)
381+ assert var_obj[Expr.str(1)], var_msg
382+ 
383+ self.assertEqual(
384+ Expr.trace,
385+ [
386+ ('init', 0),
387+ ('true', 2),
388+ ('str', 1),
389+ ('setitem', 0, 'str(1)', True),
390+ ('str', 1),
391+ ('getitem', 0, 'str(1)'),
392+ ],
393+ )
394+ self.assertEqual(
395+ self.get_var(locals()),
396+ {'var_msg': 'assertion failed', 'var_obj': Expr(0, {'str(1)': True}, {})},
397+ )
398+ 
399+ def test_assert_fail_subscript_no_msg(self):
400+ var_obj = Expr(0)
401+ var_obj[Expr.str(1)] = Expr.false(2)
402+ try:
403+ assert var_obj[Expr.str(1)]
404+ except AssertionError:
405+ Expr.str(3)
406+ 
407+ self.assertEqual(
408+ Expr.trace,
409+ [
410+ ('init', 0),
411+ ('false', 2),
412+ ('str', 1),
413+ ('setitem', 0, 'str(1)', False),
414+ ('str', 1),
415+ ('getitem', 0, 'str(1)'),
416+ ('str', 3),
417+ ],
418+ )
419+ self.assertEqual(self.get_var(locals()), {'var_obj': Expr(0, {'str(1)': False}, {})})
420+ 
421+ def test_assert_fail_subscript_msg_call(self):
422+ var_obj = Expr(0)
423+ var_obj[Expr.str(1)] = Expr.false(2)
424+ try:
425+ assert var_obj[Expr.str(1)], Expr.str(3)
426+ except AssertionError:
427+ Expr.str(4)
428+ 
429+ self.assertEqual(
430+ Expr.trace,
431+ [
432+ ('init', 0),
433+ ('false', 2),
434+ ('str', 1),
435+ ('setitem', 0, 'str(1)', False),
436+ ('str', 1),
437+ ('getitem', 0, 'str(1)'),
438+ ('str', 3),
439+ ('str', 4),
440+ ],
441+ )
442+ self.assertEqual(self.get_var(locals()), {'var_obj': Expr(0, {'str(1)': False}, {})})
443+ 
444+ def test_assert_fail_subscript_msg_name(self):
445+ var_msg = 'assertion failed'
446+ var_obj = Expr(0)
447+ var_obj[Expr.str(1)] = Expr.false(2)
448+ try:
449+ assert var_obj[Expr.str(1)], var_msg
450+ except AssertionError:
451+ Expr.str(3)
452+ 
453+ self.assertEqual(
454+ Expr.trace,
455+ [
456+ ('init', 0),
457+ ('false', 2),
458+ ('str', 1),
459+ ('setitem', 0, 'str(1)', False),
460+ ('str', 1),
461+ ('getitem', 0, 'str(1)'),
462+ ('str', 3),
463+ ],
464+ )
465+ self.assertEqual(
466+ self.get_var(locals()),
467+ {'var_msg': 'assertion failed', 'var_obj': Expr(0, {'str(1)': False}, {})},
468+ )
Rpython/tests/ut/interface/test_pil_builder_utils.py→python/tests/ut/interface/test_pil_builder_data/test_pil_builder_utils.py+18-3
@@ -13,6 +13,7 @@ import ast
13import inspect13import inspect
14import logging14import logging
15import textwrap15import textwrap
16+import unittest
16 17 
17import pypto.frontend.parser.pil as pil18import pypto.frontend.parser.pil as pil
18 19 
@@ -22,9 +23,9 @@ LOGGER = logging.getLogger(__name__)
22class Expr:23class Expr:
23 trace = []24 trace = []
24 25 
25- def __init__(self, value):26+ def __init__(self, value, item_dict=None, attr_dict=None):
26- self._item_dict = {}27+ self._item_dict = dict(item_dict) if item_dict else {}
27- self._attr_dict = {}28+ self._attr_dict = dict(attr_dict) if attr_dict else {}
28 self._value = value29 self._value = value
29 Expr.trace.append(('init', self._value))30 Expr.trace.append(('init', self._value))
30 31 
@@ -163,6 +164,20 @@ class Expr:
163 pass164 pass
164 165 
165 166 
167+class PILTestCase(unittest.TestCase):
168+ """Base class for the data-driven pil builder tests.
169+ 
170+ Provides a fresh ``Expr.trace`` before each case and a helper to project a
171+ ``locals()`` snapshot down to the ``var_``-prefixed names under test.
172+ """
173+ 
174+ def setUp(self):
175+ Expr.trace.clear()
176+ 
177+ def get_var(self, local_dict):
178+ return {k: v for k, v in local_dict.items() if k.startswith("var_")}
179+ 
180+ 
166class TestParser:181class TestParser:
167 __test__ = False182 __test__ = False
168 183