You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tvm.apache.org by ju...@apache.org on 2026/04/08 05:29:40 UTC
(tvm-ffi) branch main updated: build(deps): replace cmake version exclusion with uv exclude-newer (#524)
This is an automated email from the ASF dual-hosted git repository.
junrushao pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tvm-ffi.git
The following commit(s) were added to refs/heads/main by this push:
new d964f29 build(deps): replace cmake version exclusion with uv exclude-newer (#524)
d964f29 is described below
commit d964f294229150b425a054b5efada0602acb1cbf
Author: Junru Shao <ju...@apache.org>
AuthorDate: Tue Apr 7 22:29:36 2026 -0700
build(deps): replace cmake version exclusion with uv exclude-newer (#524)
## Summary
- Remove the `cmake!=4.3.1` version pin from dev dependencies, which was
a temporary workaround for a specific broken cmake release.
- Add `[tool.uv] exclude-newer = "30 days"` to prevent installing any
package released within the last 30 days, providing a more general and
maintainable guard against freshly-released broken packages across the
entire dependency tree.
---
.pre-commit-config.yaml | 4 -
CMakeLists.txt | 4 +
addons/ast-testsuit/README.md | 87 +
addons/ast-testsuit/ast_roundtrip_check.py | 179 ++
addons/ast-testsuit/run_multi_python.sh | 54 +
include/tvm/ffi/extra/ir_traits.h | 759 +++++++
include/tvm/ffi/extra/pyast.h | 3259 ++++++++++++++++++++++++++++
include/tvm/ffi/object.h | 2 +-
include/tvm/ffi/reflection/creator.h | 1 +
include/tvm/ffi/reflection/init.h | 1 +
include/tvm/ffi/reflection/registry.h | 18 +
include/tvm/ffi/string.h | 116 +
include/tvm/ffi/type_traits.h | 7 +-
pyproject.toml | 7 +-
python/tvm_ffi/_ffi_api.py | 11 +
python/tvm_ffi/_pyast_colored_print.py | 160 ++
python/tvm_ffi/_pyast_translator.py | 770 +++++++
python/tvm_ffi/cython/type_info.pxi | 53 +
python/tvm_ffi/dataclasses/py_class.py | 22 +
python/tvm_ffi/ir_traits.py | 306 +++
python/tvm_ffi/pyast.py | 2340 ++++++++++++++++++++
python/tvm_ffi/testing/testing.py | 722 +++++-
src/ffi/extra/pyast_printer.cc | 1942 +++++++++++++++++
src/ffi/extra/pyast_trait_print.cc | 1638 ++++++++++++++
tests/python/test_dataclass_copy.py | 3 -
tests/python/test_dataclass_init.py | 6 +-
tests/python/test_dataclass_py_class.py | 4 +-
tests/python/test_ir_traits.py | 876 ++++++++
tests/python/test_pyast.py | 1463 +++++++++++++
tests/python/test_pyast_from_py.py | 1064 +++++++++
tests/python/test_pyast_printer.py | 235 ++
tests/python/test_type_converter.py | 8 +-
32 files changed, 16094 insertions(+), 27 deletions(-)
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index a2cabf2..5ca2826 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -108,10 +108,6 @@ repos:
rev: v0.11.0.1
hooks:
- id: shellcheck
- - repo: https://github.com/DavidAnson/markdownlint-cli2
- rev: v0.20.0
- hooks:
- - id: markdownlint-cli2
- repo: https://github.com/rstcheck/rstcheck
rev: v6.2.5
hooks:
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 427a106..44e9a83 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -86,6 +86,8 @@ set(_tvm_ffi_extra_objs_sources
"${CMAKE_CURRENT_SOURCE_DIR}/src/ffi/extra/library_module_dynamic_lib.cc"
"${CMAKE_CURRENT_SOURCE_DIR}/src/ffi/extra/env_context.cc"
"${CMAKE_CURRENT_SOURCE_DIR}/src/ffi/extra/env_c_api.cc"
+ "${CMAKE_CURRENT_SOURCE_DIR}/src/ffi/extra/pyast_printer.cc"
+ "${CMAKE_CURRENT_SOURCE_DIR}/src/ffi/extra/pyast_trait_print.cc"
)
if (TVM_FFI_USE_EXTRA_CXX_API)
list(APPEND _tvm_ffi_objs_sources ${_tvm_ffi_extra_objs_sources})
@@ -150,6 +152,8 @@ if (MSVC)
target_link_libraries(tvm_ffi_objs PRIVATE DbgHelp.lib)
target_link_libraries(tvm_ffi_shared PRIVATE DbgHelp.lib)
target_link_libraries(tvm_ffi_static PRIVATE DbgHelp.lib)
+ # /bigobj: printer.cc exceeds default section limit
+ target_compile_options(tvm_ffi_objs PRIVATE /bigobj)
# produce pdb file
target_link_options(tvm_ffi_shared PRIVATE /DEBUG)
endif ()
diff --git a/addons/ast-testsuit/README.md b/addons/ast-testsuit/README.md
new file mode 100644
index 0000000..720d6a1
--- /dev/null
+++ b/addons/ast-testsuit/README.md
@@ -0,0 +1,87 @@
+<!--- Licensed to the Apache Software Foundation (ASF) under one -->
+<!--- or more contributor license agreements. See the NOTICE file -->
+<!--- distributed with this work for additional information -->
+<!--- regarding copyright ownership. The ASF licenses this file -->
+<!--- to you under the Apache License, Version 2.0 (the -->
+<!--- "License"); you may not use this file except in compliance -->
+<!--- with the License. You may obtain a copy of the License at -->
+
+<!--- http://www.apache.org/licenses/LICENSE-2.0 -->
+
+<!--- Unless required by applicable law or agreed to in writing, -->
+<!--- software distributed under the License is distributed on an -->
+<!--- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -->
+<!--- KIND, either express or implied. See the License for the -->
+<!--- specific language governing permissions and limitations -->
+<!--- under the License. -->
+
+# ast-testsuit
+
+AST roundtrip test harness: parse Python files, run them through a transform,
+re-parse the output, and diff the two ASTs field by field.
+
+## Usage
+
+```bash
+uv run ast_roundtrip_check.py <directory> <method>
+```
+
+**Arguments:**
+
+| Argument | Description |
+| --- | --- |
+| `directory` | Directory to walk recursively for `.py` files |
+| `method` | Dotted callable (`ast.AST -> str`), e.g. `tvm_ffi.text._roundtrip` |
+| `--include-positions` | Also compare `lineno`/`col_offset` fields (skipped by default) |
+
+## Example
+
+```bash
+# roundtrip all Python files under tests/python/testdata/
+uv run ast_roundtrip_check.py ../../tests/python/testdata/ tvm_ffi.text._roundtrip
+```
+
+## How it works
+
+For each `.py` file found:
+
+1. **Parse** the source into a Python AST (`a`).
+2. **Transform** by calling `method(a)` to get a string `b`.
+3. **Re-parse** `b` into a second AST (`b'`).
+4. **Compare** `a` and `b'` recursively, field by field.
+
+Positional fields (`lineno`, `col_offset`, `end_lineno`, `end_col_offset`,
+`type_comment`) are skipped by default since printers rarely preserve them.
+
+## Output
+
+```text
+OK tests/testdata/simple.py
+
+MISMATCH tests/testdata/complex.py (2 diff(s))
+ body[0].name: 'foo' != 'bar'
+ body[1].value.args: length: 2 vs 3
+
+ERROR tests/testdata/broken.py
+Traceback ...
+
+--- 3 files: 1 ok, 1 mismatched, 1 errors ---
+```
+
+Exit code is 0 when all files match, 1 otherwise.
+
+## Multi-version testing
+
+The script declares `apache-tvm-ffi` as an inline dependency with a path source,
+so `uv run --python <version>` builds and installs tvm-ffi into an isolated
+ephemeral venv automatically:
+
+```bash
+# single version
+uv run --python 3.12 ast_roundtrip_check.py <directory> <method>
+
+# all versions (3.9–3.14)
+./run_multi_python.sh <directory> <method>
+```
+
+uv downloads any missing Python interpreter on the fly.
diff --git a/addons/ast-testsuit/ast_roundtrip_check.py b/addons/ast-testsuit/ast_roundtrip_check.py
new file mode 100644
index 0000000..6bb96dc
--- /dev/null
+++ b/addons/ast-testsuit/ast_roundtrip_check.py
@@ -0,0 +1,179 @@
+#!/usr/bin/env -S uv run
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+# /// script
+# requires-python = ">=3.9"
+# dependencies = ["apache-tvm-ffi"]
+#
+# [tool.uv]
+# reinstall-package = ["apache-tvm-ffi"]
+#
+# [tool.uv.sources]
+# apache-tvm-ffi = { path = "../../" }
+# ///
+"""AST roundtrip comparison: parse -> transform -> re-parse -> diff field-by-field."""
+
+from __future__ import annotations
+
+import argparse
+import ast
+import importlib
+import sys
+import warnings
+from collections.abc import Generator
+from pathlib import Path
+from typing import Any
+
+_POSITION_FIELDS = frozenset(
+ {"lineno", "col_offset", "end_lineno", "end_col_offset", "type_comment"}
+)
+_SENTINEL = object()
+
+
+def import_callable(dotted: str) -> Any:
+ """Import 'pkg.mod.func' -> callable."""
+ mod_path, _, attr = dotted.rpartition(".")
+ if not mod_path:
+ print(f"error: need 'module.name', got {dotted!r}", file=sys.stderr)
+ sys.exit(1)
+ return getattr(importlib.import_module(mod_path), attr)
+
+
+def compare(
+ a: Any, b: Any, path: str = "", *, skip: frozenset[str] = _POSITION_FIELDS
+) -> Generator[tuple[str, str], None, None]:
+ """Recursively compare two AST values. Yield (path, message) for each mismatch."""
+ if type(a) is not type(b):
+ yield (path or "<root>", f"type: {type(a).__name__} vs {type(b).__name__}")
+ return
+
+ if isinstance(a, ast.AST):
+ a_fields = {f for f, _ in ast.iter_fields(a)}
+ b_fields = {f for f, _ in ast.iter_fields(b)}
+ for field in sorted(a_fields | b_fields):
+ if field in skip:
+ continue
+ child = f"{path}.{field}" if path else field
+ val_a = getattr(a, field, _SENTINEL)
+ val_b = getattr(b, field, _SENTINEL)
+ if val_a is _SENTINEL:
+ yield (child, "extra field in roundtripped AST")
+ elif val_b is _SENTINEL:
+ yield (child, "field missing in roundtripped AST")
+ else:
+ yield from compare(val_a, val_b, child, skip=skip)
+ elif isinstance(a, list):
+ if len(a) != len(b):
+ yield (path, f"length: {len(a)} vs {len(b)}")
+ for i, (x, y) in enumerate(zip(a, b)):
+ yield from compare(x, y, f"{path}[{i}]", skip=skip)
+ elif a != b:
+ yield (path or "<root>", f"{a!r} != {b!r}")
+
+
+def _collect_warnings(source: str, filename: str = "<unknown>") -> set[str]:
+ """Parse *source* and return the set of SyntaxWarning messages produced."""
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always", SyntaxWarning)
+ ast.parse(source, filename=filename)
+ return {str(w.message) for w in caught}
+
+
+def main() -> int: # noqa: PLR0915
+ """CLI entry point."""
+ ap = argparse.ArgumentParser(description=__doc__)
+ ap.add_argument("path", type=Path, help="file or directory to check")
+ ap.add_argument(
+ "method",
+ help="dotted callable: ast.AST -> str (e.g. tvm_ffi.text._roundtrip)",
+ )
+ ap.add_argument(
+ "--include-positions",
+ action="store_true",
+ help="also compare lineno / col_offset fields",
+ )
+ args = ap.parse_args()
+
+ target: Path = args.path
+ if target.is_file():
+ files = [target]
+ elif target.is_dir():
+ files = sorted(target.rglob("*.py"))
+ else:
+ print(f"error: {target} is not a file or directory", file=sys.stderr)
+ return 1
+
+ fn = import_callable(args.method)
+ skip = frozenset() if args.include_positions else _POSITION_FIELDS
+
+ if not files:
+ print(f"no .py files found under {target}")
+ return 0
+
+ n_ok = n_err = n_mismatch = n_skip = 0
+
+ for path in files:
+ # Step 1: parse the original source
+ try:
+ source = path.read_text()
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", SyntaxWarning)
+ a = ast.parse(source, filename=str(path))
+ except Exception as exc:
+ n_skip += 1
+ print(f"SKIP {path}: {exc}")
+ continue
+
+ # Collect warnings the *source* itself produces (e.g. Python 3.14's
+ # "return in finally" warning). These are not roundtrip bugs.
+ source_warnings = _collect_warnings(source, str(path))
+
+ # Step 2: roundtrip through the transform and re-parse
+ try:
+ b_str: str = fn(a)
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always", SyntaxWarning)
+ b_prime = ast.parse(b_str)
+ # Only flag NEW warnings not already present in the source
+ new_warnings = {str(w.message) for w in caught} - source_warnings
+ if new_warnings:
+ msgs = "; ".join(sorted(new_warnings))
+ raise SyntaxWarning(msgs)
+ except Exception as exc:
+ n_err += 1
+ print(f"\nERROR {path}: {exc}")
+ continue
+
+ diffs = list(compare(a, b_prime, skip=skip))
+ if diffs:
+ n_mismatch += 1
+ print(f"\nMISMATCH {path} ({len(diffs)} diff(s))")
+ for field_path, msg in diffs:
+ print(f" {field_path}: {msg}")
+ else:
+ n_ok += 1
+ print(f"OK {path}")
+
+ total = n_ok + n_err + n_mismatch
+ skipped = f", {n_skip} skipped" if n_skip else ""
+ print(f"\n--- {total} files: {n_ok} ok, {n_mismatch} mismatched, {n_err} errors{skipped} ---")
+ return 1 if (n_err or n_mismatch) else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/addons/ast-testsuit/run_multi_python.sh b/addons/ast-testsuit/run_multi_python.sh
new file mode 100755
index 0000000..502f8d4
--- /dev/null
+++ b/addons/ast-testsuit/run_multi_python.sh
@@ -0,0 +1,54 @@
+#!/usr/bin/env bash
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+# Run ast_roundtrip_check.py across multiple Python versions.
+# Each version gets its own isolated venv with tvm-ffi built from source.
+#
+# Usage: ./run_multi_python.sh <directory> <method> [extra-args...]
+# Example: ./run_multi_python.sh ../../tests/python tvm_ffi.text._roundtrip
+set -euo pipefail
+
+VERSIONS=(3.9 3.10 3.11 3.12 3.13 3.14)
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+SCRIPT="$SCRIPT_DIR/ast_roundtrip_check.py"
+
+if [[ $# -lt 2 ]]; then
+ echo "usage: $0 <directory> <method> [extra-args...]" >&2
+ exit 1
+fi
+
+pass=0
+fail=0
+
+for v in "${VERSIONS[@]}"; do
+ echo ""
+ echo "========================================"
+ echo " Python $v"
+ echo "========================================"
+ if uv run --python "$v" "$SCRIPT" "$@"; then
+ ((pass++))
+ else
+ ((fail++))
+ fi
+done
+
+echo ""
+echo "========================================"
+echo " ${#VERSIONS[@]} versions: $pass passed, $fail failed"
+echo "========================================"
+exit $((fail > 0))
diff --git a/include/tvm/ffi/extra/ir_traits.h b/include/tvm/ffi/extra/ir_traits.h
new file mode 100644
index 0000000..f76fa6d
--- /dev/null
+++ b/include/tvm/ffi/extra/ir_traits.h
@@ -0,0 +1,759 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/*!
+ * \file tvm/ffi/extra/ir_traits.h
+ * \brief Merged header: semantic IR trait types + trait-driven printer declarations.
+ *
+ * Traits describe WHAT each IR node IS (a loop, a value, a function)
+ * and are consumed by tools such as the text printer, optimizers,
+ * and visualizers. Trait objects are immutable FFI objects stored
+ * in TypeAttrColumn("__ffi_ir_traits__").
+ *
+ * This file also declares the TraitPrint / DefaultPrint dispatch
+ * functions used by the text printer.
+ */
+#ifndef TVM_FFI_EXTRA_IR_TRAITS_H_
+#define TVM_FFI_EXTRA_IR_TRAITS_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/cast.h>
+#include <tvm/ffi/function.h>
+#include <tvm/ffi/object.h>
+#include <tvm/ffi/optional.h>
+#include <tvm/ffi/reflection/accessor.h>
+#include <tvm/ffi/string.h>
+
+namespace tvm {
+namespace ffi {
+namespace ir_traits {
+
+/************** Helpers **************/
+
+/*! \brief Convert nullable const char* to Optional<String>. */
+inline Optional<String> ToOptString(const char* s) {
+ return s ? Optional<String>(String(s)) : Optional<String>();
+}
+
+/************** IRTraits (base) **************/
+
+/*! \brief Base class for all semantic traits. */
+struct IRTraitsObj : public Object {
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO("ffi.ir_traits.IRTraits", IRTraitsObj, Object);
+ /// \endcond
+};
+
+/// \cond Doxygen_Suppress
+/*! \brief Reference wrapper for IRTraitsObj. */
+struct IRTraits : public ObjectRef {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(IRTraits, ObjectRef, IRTraitsObj);
+};
+
+/************** ExprTraits / StmtTraits (intermediate) **************/
+
+/*! \brief Base class for expression-level traits (produce a value). */
+struct ExprTraitsObj : public IRTraitsObj {
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO("ffi.ir_traits.ExprTraits", ExprTraitsObj, IRTraitsObj);
+ /// \endcond
+};
+
+/// \cond Doxygen_Suppress
+struct ExprTraits : public IRTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(ExprTraits, IRTraits, ExprTraitsObj);
+};
+/// \endcond
+
+/*! \brief Base class for statement-level traits (side effects, control flow, scope). */
+struct StmtTraitsObj : public IRTraitsObj {
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO("ffi.ir_traits.StmtTraits", StmtTraitsObj, IRTraitsObj);
+ /// \endcond
+};
+
+/// \cond Doxygen_Suppress
+struct StmtTraits : public IRTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(StmtTraits, IRTraits, StmtTraitsObj);
+};
+/// \endcond
+/// \endcond
+
+/************** Region **************/
+
+/*! \brief Embedded scope descriptor for body regions. */
+struct RegionTraitsObj : public IRTraitsObj {
+ /*! \brief Body reference ("$field:..." or "$method:..."). */
+ String body;
+ /*! \brief Variables defined before body. */
+ Optional<String> def_values;
+ /*! \brief Expression that binds def_values. */
+ Optional<String> def_expr;
+ /*! \brief Return / yield value. */
+ Optional<String> ret;
+ /// \cond Doxygen_Suppress
+ explicit RegionTraitsObj(String body, Optional<String> def_values, Optional<String> def_expr,
+ Optional<String> ret)
+ : body(std::move(body)),
+ def_values(std::move(def_values)),
+ def_expr(std::move(def_expr)),
+ ret(std::move(ret)) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.RegionTraits", RegionTraitsObj, IRTraitsObj);
+ /// \endcond
+};
+
+/// \cond Doxygen_Suppress
+/*! \brief Reference wrapper for RegionTraitsObj. */
+struct RegionTraits : public IRTraits {
+ explicit RegionTraits(String body, Optional<String> def_values = {},
+ Optional<String> def_expr = {}, Optional<String> ret = {})
+ : RegionTraits(make_object<RegionTraitsObj>(std::move(body), std::move(def_values),
+ std::move(def_expr), std::move(ret))) {}
+ explicit RegionTraits(const char* body, const char* def_values = nullptr,
+ const char* def_expr = nullptr, const char* ret = nullptr)
+ : RegionTraits(String(body), ToOptString(def_values), ToOptString(def_expr),
+ ToOptString(ret)) {}
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(RegionTraits, IRTraits, RegionTraitsObj);
+};
+/// \endcond
+
+/************** Expression traits **************/
+
+/*! \brief Binary operation trait. */
+struct BinOpTraitsObj : public ExprTraitsObj {
+ /*! \brief Left-hand side reference. */
+ String lhs;
+ /*! \brief Right-hand side reference. */
+ String rhs;
+ /*! \brief Operator string ("+", "-", etc.). */
+ String op;
+ /*! \brief When set, $method: returning bool. If false, fall back to T.OpName(a, b) form. */
+ Optional<String> text_printer_sugar_check;
+ /*! \brief Fallback function name (e.g. "Add", "FloorDiv") when sugar check fails. */
+ Optional<String> text_printer_func_name;
+ /// \cond Doxygen_Suppress
+ explicit BinOpTraitsObj(String lhs, String rhs, String op,
+ Optional<String> text_printer_sugar_check = {},
+ Optional<String> text_printer_func_name = {})
+ : lhs(std::move(lhs)),
+ rhs(std::move(rhs)),
+ op(std::move(op)),
+ text_printer_sugar_check(std::move(text_printer_sugar_check)),
+ text_printer_func_name(std::move(text_printer_func_name)) {}
+ explicit BinOpTraitsObj(const char* lhs, const char* rhs, const char* op,
+ const char* sugar_check = nullptr, const char* func_name = nullptr)
+ : lhs(lhs),
+ rhs(rhs),
+ op(op),
+ text_printer_sugar_check(ToOptString(sugar_check)),
+ text_printer_func_name(ToOptString(func_name)) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.BinOpTraits", BinOpTraitsObj, ExprTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct BinOpTraits : public ExprTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(BinOpTraits, ExprTraits, BinOpTraitsObj);
+};
+/// \endcond
+
+/*! \brief Unary operation trait. */
+struct UnaryOpTraitsObj : public ExprTraitsObj {
+ /*! \brief Operand reference. */
+ String operand;
+ /*! \brief Operator string ("-", "~", "not"). */
+ String op;
+ /// \cond Doxygen_Suppress
+ explicit UnaryOpTraitsObj(String operand, String op)
+ : operand(std::move(operand)), op(std::move(op)) {}
+ explicit UnaryOpTraitsObj(const char* operand, const char* op) : operand(operand), op(op) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.UnaryOpTraits", UnaryOpTraitsObj, ExprTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct UnaryOpTraits : public ExprTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(UnaryOpTraits, ExprTraits, UnaryOpTraitsObj);
+};
+/// \endcond
+
+/*! \brief SSA variable trait. */
+struct ValueTraitsObj : public ExprTraitsObj {
+ /*! \brief Name reference. */
+ String name;
+ /*! \brief Type annotation reference. */
+ Optional<String> ty;
+ /*! \brief Custom type rendering at def site. */
+ Optional<String> text_printer_type;
+ /// \cond Doxygen_Suppress
+ explicit ValueTraitsObj(String name, Optional<String> ty, Optional<String> text_printer_type)
+ : name(std::move(name)), ty(std::move(ty)), text_printer_type(std::move(text_printer_type)) {}
+ explicit ValueTraitsObj(const char* name, const char* ty = nullptr,
+ const char* text_printer_type = nullptr)
+ : name(name), ty(ToOptString(ty)), text_printer_type(ToOptString(text_printer_type)) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.ValueTraits", ValueTraitsObj, ExprTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct ValueTraits : public ExprTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(ValueTraits, ExprTraits, ValueTraitsObj);
+};
+/// \endcond
+
+/************** Statement traits **************/
+
+/*!
+ * \brief Assignment / binding / expression-statement trait.
+ *
+ * When def_values is set: renders as `def_values = rhs` (assignment).
+ * When def_values is absent: renders `rhs` as a statement (expression-statement).
+ * In expr-statement mode, text_printer_kind wraps the expression (e.g. `T.evaluate(expr)`)
+ * and text_printer_return_check can render it as `return expr`.
+ */
+struct AssignTraitsObj : public StmtTraitsObj {
+ /*! \brief Target variable(s) reference. Absent for expression-statements. */
+ Optional<String> def_values;
+ /*! \brief Right-hand side / expression reference. */
+ String rhs;
+ /*! \brief Method called before printing. */
+ Optional<String> text_printer_pre;
+ /*! \brief Method called after printing. */
+ Optional<String> text_printer_post;
+ /*! \brief Wrapper callee for expr-stmt mode (e.g. "T.evaluate"). */
+ Optional<String> text_printer_kind;
+ /*! \brief $method: returning bool — if true, render as `return expr` instead of stmt. */
+ Optional<String> text_printer_return_check;
+ /// \cond Doxygen_Suppress
+ explicit AssignTraitsObj(Optional<String> def_values, String rhs,
+ Optional<String> text_printer_pre = {},
+ Optional<String> text_printer_post = {},
+ Optional<String> text_printer_kind = {},
+ Optional<String> text_printer_return_check = {})
+ : def_values(std::move(def_values)),
+ rhs(std::move(rhs)),
+ text_printer_pre(std::move(text_printer_pre)),
+ text_printer_post(std::move(text_printer_post)),
+ text_printer_kind(std::move(text_printer_kind)),
+ text_printer_return_check(std::move(text_printer_return_check)) {}
+ explicit AssignTraitsObj(const char* def_values, const char* rhs, const char* pre = nullptr,
+ const char* post = nullptr, const char* kind = nullptr,
+ const char* return_check = nullptr)
+ : def_values(def_values ? Optional<String>(String(def_values)) : Optional<String>()),
+ rhs(rhs),
+ text_printer_pre(ToOptString(pre)),
+ text_printer_post(ToOptString(post)),
+ text_printer_kind(ToOptString(kind)),
+ text_printer_return_check(ToOptString(return_check)) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.AssignTraits", AssignTraitsObj, StmtTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct AssignTraits : public StmtTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(AssignTraits, StmtTraits, AssignTraitsObj);
+};
+/// \endcond
+
+/*! \brief Memory load trait. */
+struct LoadTraitsObj : public ExprTraitsObj {
+ /*! \brief Source buffer/tensor reference. */
+ String source;
+ /*! \brief Index expressions reference. */
+ Optional<String> indices;
+ /*! \brief Predicate reference (for conditional loads). */
+ Optional<String> predicate;
+ /// \cond Doxygen_Suppress
+ explicit LoadTraitsObj(String source, Optional<String> indices, Optional<String> predicate = {})
+ : source(std::move(source)), indices(std::move(indices)), predicate(std::move(predicate)) {}
+ explicit LoadTraitsObj(const char* source, const char* indices = nullptr,
+ const char* predicate = nullptr)
+ : source(source), indices(ToOptString(indices)), predicate(ToOptString(predicate)) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.LoadTraits", LoadTraitsObj, ExprTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct LoadTraits : public ExprTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(LoadTraits, ExprTraits, LoadTraitsObj);
+};
+/// \endcond
+
+/*! \brief Memory store trait. */
+struct StoreTraitsObj : public StmtTraitsObj {
+ /*! \brief Target buffer/tensor reference. */
+ String target;
+ /*! \brief Value to store reference. */
+ String value;
+ /*! \brief Index expressions reference. */
+ Optional<String> indices;
+ /*! \brief Predicate reference (for conditional stores). */
+ Optional<String> predicate;
+ /// \cond Doxygen_Suppress
+ explicit StoreTraitsObj(String target, String value, Optional<String> indices,
+ Optional<String> predicate = {})
+ : target(std::move(target)),
+ value(std::move(value)),
+ indices(std::move(indices)),
+ predicate(std::move(predicate)) {}
+ explicit StoreTraitsObj(const char* target, const char* value, const char* indices = nullptr,
+ const char* predicate = nullptr)
+ : target(target),
+ value(value),
+ indices(ToOptString(indices)),
+ predicate(ToOptString(predicate)) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.StoreTraits", StoreTraitsObj, StmtTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct StoreTraits : public StmtTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(StoreTraits, StmtTraits, StoreTraitsObj);
+};
+/// \endcond
+
+/*! \brief Assertion trait. */
+struct AssertTraitsObj : public StmtTraitsObj {
+ /*! \brief Condition reference. */
+ String cond;
+ /*! \brief Message reference. */
+ Optional<String> message;
+ /// \cond Doxygen_Suppress
+ explicit AssertTraitsObj(String cond, Optional<String> message)
+ : cond(std::move(cond)), message(std::move(message)) {}
+ explicit AssertTraitsObj(const char* cond, const char* message = nullptr)
+ : cond(cond), message(ToOptString(message)) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.AssertTraits", AssertTraitsObj, StmtTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct AssertTraits : public StmtTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(AssertTraits, StmtTraits, AssertTraitsObj);
+};
+/// \endcond
+
+/*! \brief Return trait. */
+struct ReturnTraitsObj : public StmtTraitsObj {
+ /*! \brief Return value reference. */
+ String value;
+ /// \cond Doxygen_Suppress
+ explicit ReturnTraitsObj(String value) : value(std::move(value)) {}
+ explicit ReturnTraitsObj(const char* value) : value(value) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.ReturnTraits", ReturnTraitsObj, StmtTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct ReturnTraits : public StmtTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(ReturnTraits, StmtTraits, ReturnTraitsObj);
+};
+/// \endcond
+
+/*! \brief Literal / leaf value trait. */
+struct LiteralTraitsObj : public ExprTraitsObj {
+ /*! \brief Value reference. */
+ String value;
+ /*! \brief Format hint (e.g. "int", "float", "string"). */
+ Optional<String> format;
+ /// \cond Doxygen_Suppress
+ explicit LiteralTraitsObj(String value, Optional<String> format = {})
+ : value(std::move(value)), format(std::move(format)) {}
+ explicit LiteralTraitsObj(const char* value, const char* format = nullptr)
+ : value(value), format(ToOptString(format)) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.LiteralTraits", LiteralTraitsObj, ExprTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct LiteralTraits : public ExprTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(LiteralTraits, ExprTraits, LiteralTraitsObj);
+};
+/// \endcond
+
+/*! \brief Call expression trait (function call with op and args). */
+struct CallTraitsObj : public ExprTraitsObj {
+ /*! \brief Callee / operator reference (literal string or $field:/$method:). */
+ String op;
+ /*! \brief Arguments reference. */
+ String args;
+ /*! \brief Attributes reference. */
+ Optional<String> attrs;
+ /*! \brief Keyword args reference ($method: returning Map<String, Any>). */
+ Optional<String> kwargs;
+ /*! \brief Dynamic callee override ($method: returning String callee name). */
+ Optional<String> text_printer_callee;
+ /*! \brief Hook called before printing ($global:). */
+ Optional<String> text_printer_pre;
+ /// \cond Doxygen_Suppress
+ explicit CallTraitsObj(String op, String args, Optional<String> attrs = {},
+ Optional<String> kwargs = {}, Optional<String> text_printer_callee = {},
+ Optional<String> text_printer_pre = {})
+ : op(std::move(op)),
+ args(std::move(args)),
+ attrs(std::move(attrs)),
+ kwargs(std::move(kwargs)),
+ text_printer_callee(std::move(text_printer_callee)),
+ text_printer_pre(std::move(text_printer_pre)) {}
+ explicit CallTraitsObj(const char* op, const char* args, const char* attrs = nullptr,
+ const char* kwargs = nullptr, const char* callee = nullptr,
+ const char* pre = nullptr)
+ : op(op),
+ args(args),
+ attrs(ToOptString(attrs)),
+ kwargs(ToOptString(kwargs)),
+ text_printer_callee(ToOptString(callee)),
+ text_printer_pre(ToOptString(pre)) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.CallTraits", CallTraitsObj, ExprTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct CallTraits : public ExprTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(CallTraits, ExprTraits, CallTraitsObj);
+};
+/// \endcond
+
+/*! \brief Function trait. */
+struct FuncTraitsObj : public StmtTraitsObj {
+ /*! \brief Symbol name reference. */
+ String symbol;
+ /*! \brief Function body region. */
+ RegionTraits region;
+ /*! \brief Attributes reference. */
+ Optional<String> attrs;
+ /*! \brief Decorator/callee text. */
+ Optional<String> text_printer_kind;
+ /*! \brief Method called before body. */
+ Optional<String> text_printer_pre;
+ /// \cond Doxygen_Suppress
+ explicit FuncTraitsObj(String symbol, RegionTraits region, Optional<String> attrs,
+ Optional<String> text_printer_kind, Optional<String> text_printer_pre)
+ : symbol(std::move(symbol)),
+ region(std::move(region)),
+ attrs(std::move(attrs)),
+ text_printer_kind(std::move(text_printer_kind)),
+ text_printer_pre(std::move(text_printer_pre)) {}
+ explicit FuncTraitsObj(const char* symbol, RegionTraits region, const char* attrs = nullptr,
+ const char* kind = nullptr, const char* pre = nullptr)
+ : symbol(symbol),
+ region(std::move(region)),
+ attrs(ToOptString(attrs)),
+ text_printer_kind(ToOptString(kind)),
+ text_printer_pre(ToOptString(pre)) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.FuncTraits", FuncTraitsObj, StmtTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct FuncTraits : public StmtTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(FuncTraits, StmtTraits, FuncTraitsObj);
+};
+/// \endcond
+
+/*! \brief For-loop trait. */
+struct ForTraitsObj : public StmtTraitsObj {
+ /*! \brief Loop body region. */
+ RegionTraits region;
+ /*! \brief Loop start reference. */
+ Optional<String> start;
+ /*! \brief Loop end reference. */
+ Optional<String> end;
+ /*! \brief Loop step reference. */
+ Optional<String> step;
+ /*! \brief Carried variables reference. */
+ Optional<String> def_carry;
+ /*! \brief Initial carry values reference. */
+ Optional<String> carry_init;
+ /*! \brief Attributes reference. */
+ Optional<String> attrs;
+ /*! \brief Custom iterator kind text. */
+ Optional<String> text_printer_kind;
+ /// \cond Doxygen_Suppress
+ explicit ForTraitsObj(RegionTraits region, Optional<String> start, Optional<String> end,
+ Optional<String> step, Optional<String> def_carry,
+ Optional<String> carry_init, Optional<String> attrs,
+ Optional<String> text_printer_kind)
+ : region(std::move(region)),
+ start(std::move(start)),
+ end(std::move(end)),
+ step(std::move(step)),
+ def_carry(std::move(def_carry)),
+ carry_init(std::move(carry_init)),
+ attrs(std::move(attrs)),
+ text_printer_kind(std::move(text_printer_kind)) {}
+ explicit ForTraitsObj(RegionTraits region, const char* start = nullptr, const char* end = nullptr,
+ const char* step = nullptr, const char* def_carry = nullptr,
+ const char* carry_init = nullptr, const char* attrs = nullptr,
+ const char* kind = nullptr)
+ : region(std::move(region)),
+ start(ToOptString(start)),
+ end(ToOptString(end)),
+ step(ToOptString(step)),
+ def_carry(ToOptString(def_carry)),
+ carry_init(ToOptString(carry_init)),
+ attrs(ToOptString(attrs)),
+ text_printer_kind(ToOptString(kind)) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.ForTraits", ForTraitsObj, StmtTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct ForTraits : public StmtTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(ForTraits, StmtTraits, ForTraitsObj);
+};
+/// \endcond
+
+/*!
+ * \brief Context manager / sequence trait.
+ *
+ * When text_printer_kind is set: renders as `with kind(...) as var:` block.
+ * When text_printer_kind is absent and region has no def_values: renders as
+ * an inline sequence of the region body (replaces SeqTraits).
+ */
+struct WithTraitsObj : public StmtTraitsObj {
+ /*! \brief Scoped body region. */
+ RegionTraits region;
+ /*! \brief Carried variables reference. */
+ Optional<String> def_carry;
+ /*! \brief Initial carry values reference. */
+ Optional<String> carry_init;
+ /*! \brief Context expression kind text. */
+ Optional<String> text_printer_kind;
+ /*! \brief Method called before body. */
+ Optional<String> text_printer_pre;
+ /*! \brief Method called after body. */
+ Optional<String> text_printer_post;
+ /*! \brief When true, skip frame push/pop (elements stay in parent scope). */
+ Optional<bool> text_printer_no_frame;
+ /// \cond Doxygen_Suppress
+ explicit WithTraitsObj(RegionTraits region, Optional<String> def_carry,
+ Optional<String> carry_init, Optional<String> text_printer_kind,
+ Optional<String> text_printer_pre, Optional<String> text_printer_post,
+ Optional<bool> text_printer_no_frame = {})
+ : region(std::move(region)),
+ def_carry(std::move(def_carry)),
+ carry_init(std::move(carry_init)),
+ text_printer_kind(std::move(text_printer_kind)),
+ text_printer_pre(std::move(text_printer_pre)),
+ text_printer_post(std::move(text_printer_post)),
+ text_printer_no_frame(std::move(text_printer_no_frame)) {}
+ explicit WithTraitsObj(RegionTraits region, const char* def_carry = nullptr,
+ const char* carry_init = nullptr, const char* kind = nullptr,
+ const char* pre = nullptr, const char* post = nullptr,
+ Optional<bool> no_frame = {})
+ : region(std::move(region)),
+ def_carry(ToOptString(def_carry)),
+ carry_init(ToOptString(carry_init)),
+ text_printer_kind(ToOptString(kind)),
+ text_printer_pre(ToOptString(pre)),
+ text_printer_post(ToOptString(post)),
+ text_printer_no_frame(std::move(no_frame)) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.WithTraits", WithTraitsObj, StmtTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct WithTraits : public StmtTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(WithTraits, StmtTraits, WithTraitsObj);
+};
+/// \endcond
+
+/*! \brief While-loop trait. */
+struct WhileTraitsObj : public StmtTraitsObj {
+ /*! \brief Condition reference. */
+ String cond;
+ /*! \brief Loop body region. */
+ RegionTraits region;
+ /// \cond Doxygen_Suppress
+ explicit WhileTraitsObj(String cond, RegionTraits region)
+ : cond(std::move(cond)), region(std::move(region)) {}
+ explicit WhileTraitsObj(const char* cond, RegionTraits region)
+ : cond(cond), region(std::move(region)) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.WhileTraits", WhileTraitsObj, StmtTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct WhileTraits : public StmtTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(WhileTraits, StmtTraits, WhileTraitsObj);
+};
+/// \endcond
+
+/*! \brief Conditional trait. */
+struct IfTraitsObj : public StmtTraitsObj {
+ /*! \brief Condition reference. */
+ String cond;
+ /*! \brief Then-branch region. */
+ RegionTraits then_region;
+ /*! \brief Else-branch region (optional). */
+ Optional<RegionTraits> else_region;
+ /// \cond Doxygen_Suppress
+ explicit IfTraitsObj(String cond, RegionTraits then_region, Optional<RegionTraits> else_region)
+ : cond(std::move(cond)),
+ then_region(std::move(then_region)),
+ else_region(std::move(else_region)) {}
+ explicit IfTraitsObj(const char* cond, RegionTraits then_region,
+ Optional<RegionTraits> else_region = {})
+ : cond(cond), then_region(std::move(then_region)), else_region(std::move(else_region)) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.IfTraits", IfTraitsObj, StmtTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct IfTraits : public StmtTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(IfTraits, StmtTraits, IfTraitsObj);
+};
+/// \endcond
+
+/************** Type traits **************/
+
+/*! \brief Base type marker trait. */
+struct TyTraitsObj : public IRTraitsObj {
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO("ffi.ir_traits.TyTraits", TyTraitsObj, IRTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct TyTraits : public IRTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(TyTraits, IRTraits, TyTraitsObj);
+};
+/// \endcond
+
+/*! \brief Tensor type trait. */
+struct TensorTyTraitsObj : public TyTraitsObj {
+ /*! \brief Shape reference. */
+ Optional<String> shape;
+ /*! \brief Data type reference. */
+ Optional<String> dtype;
+ /*! \brief Device reference. */
+ Optional<String> device;
+ /// \cond Doxygen_Suppress
+ explicit TensorTyTraitsObj(Optional<String> shape, Optional<String> dtype,
+ Optional<String> device)
+ : shape(std::move(shape)), dtype(std::move(dtype)), device(std::move(device)) {}
+ explicit TensorTyTraitsObj(const char* shape = nullptr, const char* dtype = nullptr,
+ const char* device = nullptr)
+ : shape(ToOptString(shape)), dtype(ToOptString(dtype)), device(ToOptString(device)) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.TensorTyTraits", TensorTyTraitsObj, TyTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct TensorTyTraits : public TyTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(TensorTyTraits, TyTraits, TensorTyTraitsObj);
+};
+/// \endcond
+
+/*! \brief Buffer / MemRef type trait. */
+struct BufferTyTraitsObj : public TyTraitsObj {
+ /*! \brief Shape reference. */
+ String shape;
+ /*! \brief Data type reference. */
+ String dtype;
+ /*! \brief Strides reference. */
+ Optional<String> strides;
+ /*! \brief Element offset reference. */
+ Optional<String> offset;
+ /*! \brief Memory scope reference. */
+ Optional<String> scope;
+ /// \cond Doxygen_Suppress
+ explicit BufferTyTraitsObj(String shape, String dtype, Optional<String> strides,
+ Optional<String> offset, Optional<String> scope)
+ : shape(std::move(shape)),
+ dtype(std::move(dtype)),
+ strides(std::move(strides)),
+ offset(std::move(offset)),
+ scope(std::move(scope)) {}
+ explicit BufferTyTraitsObj(const char* shape, const char* dtype, const char* strides = nullptr,
+ const char* offset = nullptr, const char* scope = nullptr)
+ : shape(shape),
+ dtype(dtype),
+ strides(ToOptString(strides)),
+ offset(ToOptString(offset)),
+ scope(ToOptString(scope)) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.BufferTyTraits", BufferTyTraitsObj, TyTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct BufferTyTraits : public TyTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(BufferTyTraits, TyTraits, BufferTyTraitsObj);
+};
+/// \endcond
+
+/*! \brief Scalar primitive type trait. */
+struct PrimTyTraitsObj : public TyTraitsObj {
+ /*! \brief Data type reference. */
+ String dtype;
+ /// \cond Doxygen_Suppress
+ explicit PrimTyTraitsObj(String dtype) : dtype(std::move(dtype)) {}
+ explicit PrimTyTraitsObj(const char* dtype) : dtype(dtype) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.PrimTyTraits", PrimTyTraitsObj, TyTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct PrimTyTraits : public TyTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(PrimTyTraits, TyTraits, PrimTyTraitsObj);
+};
+/// \endcond
+
+/*! \brief Function signature type trait. */
+struct FuncTyTraitsObj : public TyTraitsObj {
+ /*! \brief Parameter types reference. */
+ Optional<String> params;
+ /*! \brief Return type reference. */
+ Optional<String> ret;
+ /// \cond Doxygen_Suppress
+ explicit FuncTyTraitsObj(Optional<String> params, Optional<String> ret)
+ : params(std::move(params)), ret(std::move(ret)) {}
+ explicit FuncTyTraitsObj(const char* params = nullptr, const char* ret = nullptr)
+ : params(ToOptString(params)), ret(ToOptString(ret)) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.FuncTyTraits", FuncTyTraitsObj, TyTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct FuncTyTraits : public TyTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(FuncTyTraits, TyTraits, FuncTyTraitsObj);
+};
+/// \endcond
+
+/*! \brief Tuple / product type trait. */
+struct TupleTyTraitsObj : public TyTraitsObj {
+ /*! \brief Element types reference. */
+ String fields;
+ /// \cond Doxygen_Suppress
+ explicit TupleTyTraitsObj(String fields) : fields(std::move(fields)) {}
+ explicit TupleTyTraitsObj(const char* fields) : fields(fields) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.TupleTyTraits", TupleTyTraitsObj, TyTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct TupleTyTraits : public TyTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(TupleTyTraits, TyTraits, TupleTyTraitsObj);
+};
+/// \endcond
+
+/*! \brief Shape descriptor type trait. */
+struct ShapeTyTraitsObj : public TyTraitsObj {
+ /*! \brief Dimension expressions reference. */
+ Optional<String> dims;
+ /*! \brief Rank reference. */
+ Optional<String> ndim;
+ /// \cond Doxygen_Suppress
+ explicit ShapeTyTraitsObj(Optional<String> dims, Optional<String> ndim)
+ : dims(std::move(dims)), ndim(std::move(ndim)) {}
+ explicit ShapeTyTraitsObj(const char* dims = nullptr, const char* ndim = nullptr)
+ : dims(ToOptString(dims)), ndim(ToOptString(ndim)) {}
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.ir_traits.ShapeTyTraits", ShapeTyTraitsObj, TyTraitsObj);
+ /// \endcond
+};
+/// \cond Doxygen_Suppress
+struct ShapeTyTraits : public TyTraits {
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(ShapeTyTraits, TyTraits, ShapeTyTraitsObj);
+};
+/// \endcond
+
+} // namespace ir_traits
+} // namespace ffi
+} // namespace tvm
+
+#endif // TVM_FFI_EXTRA_IR_TRAITS_H_
diff --git a/include/tvm/ffi/extra/pyast.h b/include/tvm/ffi/extra/pyast.h
new file mode 100644
index 0000000..f94ecf3
--- /dev/null
+++ b/include/tvm/ffi/extra/pyast.h
@@ -0,0 +1,3259 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/*\!
+ * \file tvm/ffi/extra/pyast.h
+ * \brief Merged Python-style AST node definitions and IRPrinter.
+ *
+ * Combines the text format AST node hierarchy (expressions, statements)
+ * with the IRPrinter class and rendering functions. All definitions live
+ * in the flat namespace tvm::ffi::pyast.
+ */
+#ifndef TVM_FFI_EXTRA_PYAST_H_
+#define TVM_FFI_EXTRA_PYAST_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/container/dict.h>
+#include <tvm/ffi/container/list.h>
+#include <tvm/ffi/dtype.h>
+#include <tvm/ffi/extra/base.h>
+#include <tvm/ffi/function.h>
+#include <tvm/ffi/object.h>
+#include <tvm/ffi/optional.h>
+#include <tvm/ffi/reflection/access_path.h>
+#include <tvm/ffi/string.h>
+
+#include <algorithm>
+#include <iomanip>
+#include <sstream>
+#include <string>
+
+namespace tvm {
+namespace ffi {
+namespace pyast {
+
+using AccessPath = ::tvm::ffi::reflection::AccessPath;
+
+// Forward declaration — full definition is below.
+struct PrinterConfigObj;
+struct PrinterConfig;
+
+/************** NodeAST **************/
+
+/*!
+ * \brief Base data object for all text AST nodes.
+ *
+ * Every node in the text format AST inherits from NodeASTObj. It carries
+ * a list of source access paths that trace which IR fields produced this
+ * node, enabling underline highlighting in the rendered output.
+ *
+ * \code{.cpp}
+ * // Typically not constructed directly; use ExprAST or StmtAST subtypes.
+ * // Render any node to Python text:
+ * NodeAST node = IdAST("x");
+ * String code = node->ToPython(PrinterConfig());
+ * \endcode
+ *
+ * \sa NodeAST, ExprASTObj, StmtASTObj
+ */
+struct NodeASTObj : public Object {
+ /// \cond Doxygen_Suppress
+ static constexpr bool _type_mutable = true;
+ /// \endcond
+ /*!
+ * \brief Access paths tracing this node back to the original IR structure.
+ *
+ * Populated by IRPrinter during dispatch. Typically empty for manually
+ * constructed AST nodes. Used by the renderer to decide which text
+ * regions to underline when path_to_underline is set in PrinterConfig.
+ */
+ List<AccessPath> source_paths;
+ /*! \brief Source line number (1-based), or -1 if unavailable. */
+ int64_t lineno{-1};
+ /*! \brief Source column offset (0-based), or -1 if unavailable. */
+ int64_t col_offset{-1};
+ /*! \brief Source end line number (1-based), or -1 if unavailable. */
+ int64_t end_lineno{-1};
+ /*! \brief Source end column offset (0-based), or -1 if unavailable. */
+ int64_t end_col_offset{-1};
+ /// \cond Doxygen_Suppress
+ explicit NodeASTObj(List<AccessPath> source_paths) : source_paths(std::move(source_paths)) {}
+ /// \endcond
+ /*!
+ * \brief Render this AST node to Python-style source code.
+ *
+ * Delegates to details::PyAST2Str to produce a Python-style text
+ * representation of this node and all its children.
+ *
+ * \param cfg Printer configuration controlling indentation, line numbers,
+ * and underline highlighting.
+ * \return The rendered Python-style source code as a String.
+ *
+ * \code{.cpp}
+ * NodeAST node = IdAST("x");
+ * String code = node->ToPython(PrinterConfig());
+ * // code == "x"
+ * \endcode
+ */
+ String ToPython(const PrinterConfig& cfg) const;
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO("ffi.pyast.Node", NodeASTObj, Object);
+ /// \endcond
+};
+
+/*!
+ * \brief Nullable reference to a NodeASTObj.
+ *
+ * Root reference type for the text format AST. All expression and statement
+ * AST references derive from this. Can be rendered to a Python-style
+ * string via details::PyAST2Str.
+ *
+ * \code{.cpp}
+ * NodeAST node = LiteralAST::Int(42);
+ * String code = details::PyAST2Str(node, PrinterConfig());
+ * \endcode
+ *
+ * \sa NodeASTObj
+ */
+struct NodeAST : public ObjectRef {
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(NodeAST, ObjectRef, NodeASTObj);
+ /// \endcond
+};
+
+/************** ExprAST **************/
+
+struct ExprAST;
+
+/*!
+ * \brief Base data object for all expression AST nodes.
+ *
+ * Represents a Python-style expression in the text format AST. Concrete
+ * subtypes include literals, identifiers, attribute accesses, calls,
+ * operations, tuples, lists, dicts, and slices.
+ *
+ * Expression nodes can be composed using the free-function builders
+ * ExprAttr, ExprIndex, ExprCall, and ExprCallKw to form complex
+ * expressions.
+ *
+ * \code{.cpp}
+ * // Build: my_func(x, y).result
+ * ExprAST callee = IdAST("my_func");
+ * ExprAST call = ExprCall(callee, {IdAST("x"), IdAST("y")});
+ * ExprAST attr = ExprAttr(call, "result");
+ * // Renders as: my_func(x, y).result
+ * \endcode
+ *
+ * \sa ExprAST, LiteralASTObj, IdASTObj, CallASTObj
+ */
+struct ExprASTObj : public NodeASTObj {
+ /// \cond Doxygen_Suppress
+ explicit ExprASTObj(List<AccessPath> source_paths) : NodeASTObj(std::move(source_paths)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO("ffi.pyast.Expr", ExprASTObj, NodeASTObj);
+ /// \endcond
+};
+
+/*!
+ * \brief Nullable reference to an ExprASTObj.
+ *
+ * Provides the AddPath helper for appending source-tracking metadata
+ * and serves as the common handle for all expression AST nodes.
+ * Convenience builders ExprAttr, ExprIndex, ExprCall, and ExprCallKw
+ * are provided as free functions.
+ *
+ * \code{.cpp}
+ * ExprAST expr = IdAST("x");
+ * // Chain an attribute access: x.shape
+ * ExprAST attr = ExprAttr(expr, "shape");
+ * \endcode
+ *
+ * \sa ExprASTObj
+ */
+struct ExprAST : public NodeAST {
+ /*!
+ * \brief Append an access path to this expression's source_paths and return *this.
+ *
+ * Enables fluent chaining when building expressions with traceability.
+ *
+ * \param p The access path to append, linking this node to an IR field.
+ * \return A reference to *this, allowing method chaining.
+ *
+ * \code{.cpp}
+ * ExprAST expr = IdAST("x");
+ * expr.AddPath(AccessPath::Root());
+ * \endcode
+ */
+ ExprAST AddPath(const AccessPath& p) {
+ const_cast<ExprASTObj*>(get())->source_paths.push_back(p);
+ return *this;
+ }
+ // Convenience builders: Attr, Index, Call, CallKw — defined as free functions below.
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(ExprAST, NodeAST, ExprASTObj);
+ /// \endcond
+};
+
+/************** StmtAST **************/
+
+/*!
+ * \brief Base data object for all statement AST nodes.
+ *
+ * Represents a Python-style statement in the text format AST. Each statement
+ * may carry an optional inline comment. Concrete subtypes include
+ * assignments, if/while/for blocks, function/class definitions, and more.
+ *
+ * \code{.cpp}
+ * // Build: x = 42 # initial value
+ * StmtAST stmt = AssignAST(
+ * {}, String("initial value"),
+ * IdAST("x"), LiteralAST::Int(42), NullOpt);
+ * \endcode
+ *
+ * \sa StmtAST, AssignASTObj, IfASTObj, FunctionASTObj
+ */
+struct StmtASTObj : public NodeASTObj {
+ /// \cond Doxygen_Suppress
+ static constexpr bool _type_mutable = true;
+ /// \endcond
+ /*!
+ * \brief Optional inline or block comment text.
+ *
+ * When set, the comment is rendered after the statement on the same line
+ * (e.g. `x = 42 # initial value`). Null means no comment.
+ */
+ Optional<String> comment;
+ /// \cond Doxygen_Suppress
+ explicit StmtASTObj(List<AccessPath> source_paths, Optional<String> comment)
+ : NodeASTObj(std::move(source_paths)), comment(std::move(comment)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO("ffi.pyast.Stmt", StmtASTObj, NodeASTObj);
+ /// \endcond
+};
+
+/*! \brief Nullable reference to a StmtASTObj. */
+struct StmtAST : public NodeAST {
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(StmtAST, NodeAST, StmtASTObj);
+ /// \endcond
+};
+
+/************** StmtBlockAST **************/
+
+/*!
+ * \brief Data object for a block of sequential statements.
+ *
+ * Groups multiple statements into a single renderable unit. Used as
+ * the top-level container when rendering a complete program or module.
+ *
+ * \code{.cpp}
+ * // Build a block of two statements:
+ * StmtBlockAST block({
+ * AssignAST(IdAST("x"), LiteralAST::Int(1)),
+ * AssignAST(IdAST("y"), LiteralAST::Int(2)),
+ * });
+ * \endcode
+ *
+ * \sa StmtBlockAST
+ */
+struct StmtBlockASTObj : public StmtASTObj {
+ /*! \brief The list of statements. */
+ List<StmtAST> stmts;
+ /// \cond Doxygen_Suppress
+ explicit StmtBlockASTObj(List<StmtAST> stmts)
+ : StmtBlockASTObj(List<AccessPath>{}, Optional<String>{}, std::move(stmts)) {}
+ explicit StmtBlockASTObj(List<AccessPath> source_paths, Optional<String> comment,
+ List<StmtAST> stmts)
+ : StmtASTObj(std::move(source_paths), std::move(comment)), stmts(std::move(stmts)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.StmtBlock", StmtBlockASTObj, StmtASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for a block of sequential statements. */
+struct StmtBlockAST : public StmtAST {
+ /// \cond Doxygen_Suppress
+ explicit StmtBlockAST(List<StmtAST> stmts)
+ : StmtBlockAST(List<AccessPath>{}, Optional<String>{}, std::move(stmts)) {}
+ explicit StmtBlockAST(List<AccessPath> source_paths, Optional<String> comment,
+ List<StmtAST> stmts)
+ : StmtBlockAST(make_object<StmtBlockASTObj>(std::move(source_paths), std::move(comment),
+ std::move(stmts))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(StmtBlockAST, StmtAST, StmtBlockASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit StmtBlockAST(ObjectPtr<StmtBlockASTObj> ptr)
+ : StmtAST(ObjectPtr<StmtASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** LiteralAST **************/
+
+/*!
+ * \brief Data object for a literal value expression (int, float, string, bool, null).
+ *
+ * Wraps a type-erased Any value that will be rendered as its Python literal
+ * representation (e.g. 42, 3.14, "hello", True, None).
+ *
+ * \code{.cpp}
+ * auto lit_int = LiteralAST::Int(42);
+ * auto lit_str = LiteralAST::Str("hello");
+ * auto lit_none = LiteralAST::Null();
+ * \endcode
+ *
+ * \sa LiteralAST
+ */
+struct LiteralASTObj : public ExprASTObj {
+ /*! \brief The literal value (bool, int, float, string, or null). */
+ Any value;
+ /// \cond Doxygen_Suppress
+ explicit LiteralASTObj(Any value) : LiteralASTObj(List<AccessPath>{}, std::move(value)) {}
+ explicit LiteralASTObj(List<AccessPath> source_paths, Any value)
+ : ExprASTObj(std::move(source_paths)), value(std::move(value)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Literal", LiteralASTObj, ExprASTObj);
+ /// \endcond
+};
+
+/*!
+ * \brief Reference wrapper for a literal value expression.
+ *
+ * Provides static factory methods for common literal types: Bool, Int,
+ * Str, Float, and Null. Each factory creates a fully constructed literal
+ * node ready for insertion into the text format AST.
+ *
+ * \code{.cpp}
+ * LiteralAST answer = LiteralAST::Int(42);
+ * LiteralAST pi = LiteralAST::Float(3.14159);
+ * LiteralAST name = LiteralAST::Str("world");
+ * LiteralAST flag = LiteralAST::Bool(true);
+ * LiteralAST nothing = LiteralAST::Null();
+ * \endcode
+ *
+ * \sa LiteralASTObj
+ */
+struct LiteralAST : public ExprAST {
+ /*!
+ * \brief Create a bool literal.
+ * \param value The boolean value (renders as `True` or `False`).
+ * \param source_paths Optional access paths for IR traceability.
+ * \return A LiteralAST wrapping the bool value.
+ *
+ * \code{.cpp}
+ * LiteralAST flag = LiteralAST::Bool(true);
+ * // Renders as: True
+ * \endcode
+ */
+ static LiteralAST Bool(bool value, List<AccessPath> source_paths = {}) {
+ return LiteralAST(std::move(source_paths), Any(value));
+ }
+ /*!
+ * \brief Create an integer literal.
+ * \param value The 64-bit integer value (renders as a decimal, e.g. `42`).
+ * \param source_paths Optional access paths for IR traceability.
+ * \return A LiteralAST wrapping the int value.
+ *
+ * \code{.cpp}
+ * LiteralAST answer = LiteralAST::Int(42);
+ * // Renders as: 42
+ * \endcode
+ */
+ static LiteralAST Int(int64_t value, List<AccessPath> source_paths = {}) {
+ return LiteralAST(std::move(source_paths), Any(value));
+ }
+ /*!
+ * \brief Create a string literal.
+ * \param value The string content (rendered with quotes, e.g. `"hello"`).
+ * \param source_paths Optional access paths for IR traceability.
+ * \return A LiteralAST wrapping the string value.
+ *
+ * \code{.cpp}
+ * LiteralAST greeting = LiteralAST::Str("hello");
+ * // Renders as: "hello"
+ * \endcode
+ */
+ static LiteralAST Str(String value, List<AccessPath> source_paths = {}) {
+ return LiteralAST(std::move(source_paths), Any(std::move(value)));
+ }
+ /*!
+ * \brief Create a floating-point literal.
+ * \param value The double-precision float value (e.g. `3.14`).
+ * \param source_paths Optional access paths for IR traceability.
+ * \return A LiteralAST wrapping the float value.
+ *
+ * \code{.cpp}
+ * LiteralAST pi = LiteralAST::Float(3.14159);
+ * // Renders as: 3.14159
+ * \endcode
+ */
+ static LiteralAST Float(double value, List<AccessPath> source_paths = {}) {
+ return LiteralAST(std::move(source_paths), Any(value));
+ }
+ /*!
+ * \brief Create a null literal (renders as `None`).
+ * \param source_paths Optional access paths for IR traceability.
+ * \return A LiteralAST representing Python's None.
+ *
+ * \code{.cpp}
+ * LiteralAST nothing = LiteralAST::Null();
+ * // Renders as: None
+ * \endcode
+ */
+ static LiteralAST Null(List<AccessPath> source_paths = {}) {
+ return LiteralAST(std::move(source_paths), Any());
+ }
+ /// \cond Doxygen_Suppress
+ explicit LiteralAST(Any value) : LiteralAST(List<AccessPath>{}, std::move(value)) {}
+ explicit LiteralAST(List<AccessPath> source_paths, Any value)
+ : LiteralAST(make_object<LiteralASTObj>(std::move(source_paths), std::move(value))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(LiteralAST, ExprAST, LiteralASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit LiteralAST(ObjectPtr<LiteralASTObj> ptr)
+ : ExprAST(ObjectPtr<ExprASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** IdAST **************/
+
+/*!
+ * \brief Data object for an identifier expression (variable or name reference).
+ *
+ * Holds the string name of the identifier as it will appear in the
+ * rendered Python-style output.
+ *
+ * \code{.cpp}
+ * auto id = IdAST("my_var");
+ * // Renders as: my_var
+ * \endcode
+ *
+ * \sa IdAST
+ */
+struct IdASTObj : public ExprASTObj {
+ /*! \brief The identifier name. */
+ String name;
+ /// \cond Doxygen_Suppress
+ explicit IdASTObj(String name) : IdASTObj(List<AccessPath>{}, std::move(name)) {}
+ explicit IdASTObj(List<AccessPath> source_paths, String name)
+ : ExprASTObj(std::move(source_paths)), name(std::move(name)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Id", IdASTObj, ExprASTObj);
+ /// \endcond
+};
+
+/*!
+ * \brief Reference wrapper for an identifier expression.
+ *
+ * Can be constructed from a name string alone (no source paths) or
+ * with explicit source paths for traceability.
+ *
+ * \code{.cpp}
+ * IdAST x("x");
+ * IdAST y({}, "y"); // with explicit empty source paths
+ * \endcode
+ *
+ * \sa IdASTObj
+ */
+struct IdAST : public ExprAST {
+ /// \cond Doxygen_Suppress
+ explicit IdAST(List<AccessPath> source_paths, String name)
+ : IdAST(make_object<IdASTObj>(std::move(source_paths), std::move(name))) {}
+ explicit IdAST(String name) : IdAST({}, std::move(name)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(IdAST, ExprAST, IdASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit IdAST(ObjectPtr<IdASTObj> ptr) : ExprAST(ObjectPtr<ExprASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** AttrAST **************/
+
+/*!
+ * \brief Data object for an attribute access expression (e.g. `obj.name`).
+ *
+ * Represents the Python construct `obj.name` in the text format AST.
+ *
+ * \code{.cpp}
+ * // Build: tensor.shape
+ * AttrAST attr({}, IdAST("tensor"), "shape");
+ * // Or use the convenience builder:
+ * ExprAST attr2 = ExprAttr(IdAST("tensor"), "shape");
+ * \endcode
+ *
+ * \sa AttrAST, ExprAttr
+ */
+struct AttrASTObj : public ExprASTObj {
+ /*! \brief The target expression being accessed (e.g. `tensor` in `tensor.shape`). */
+ ExprAST obj;
+ /*! \brief The attribute name (e.g. `"shape"` in `tensor.shape`). */
+ String name;
+ /// \cond Doxygen_Suppress
+ explicit AttrASTObj(ExprAST obj, String name)
+ : AttrASTObj(List<AccessPath>{}, std::move(obj), std::move(name)) {}
+ explicit AttrASTObj(List<AccessPath> source_paths, ExprAST obj, String name)
+ : ExprASTObj(std::move(source_paths)), obj(std::move(obj)), name(std::move(name)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Attr", AttrASTObj, ExprASTObj);
+ /// \endcond
+};
+
+/*!
+ * \brief Reference wrapper for an attribute access expression (e.g. `obj.name`).
+ *
+ * \code{.cpp}
+ * AttrAST attr(IdAST("module"), "func");
+ * // Renders as: module.func
+ * \endcode
+ *
+ * \sa AttrASTObj, ExprAttr
+ */
+struct AttrAST : public ExprAST {
+ /// \cond Doxygen_Suppress
+ explicit AttrAST(ExprAST obj, String name)
+ : AttrAST(List<AccessPath>{}, std::move(obj), std::move(name)) {}
+ explicit AttrAST(List<AccessPath> source_paths, ExprAST obj, String name)
+ : AttrAST(make_object<AttrASTObj>(std::move(source_paths), std::move(obj), std::move(name))) {
+ }
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(AttrAST, ExprAST, AttrASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit AttrAST(ObjectPtr<AttrASTObj> ptr) : ExprAST(ObjectPtr<ExprASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** IndexAST **************/
+
+/*!
+ * \brief Data object for an index/subscript expression (e.g. `obj[idx]`).
+ *
+ * Represents the Python construct `obj[idx]` in the text format AST.
+ * Supports multiple index expressions for multi-dimensional subscripts.
+ *
+ * \code{.cpp}
+ * // Build: data[0]
+ * IndexAST idx(IdAST("data"), {LiteralAST::Int(0)});
+ * // Or use the convenience builder:
+ * ExprAST idx2 = ExprIndex(IdAST("data"), {LiteralAST::Int(0)});
+ * \endcode
+ *
+ * \sa IndexAST, ExprIndex
+ */
+struct IndexASTObj : public ExprASTObj {
+ /*! \brief The target expression being indexed. */
+ ExprAST obj;
+ /*! \brief The index expressions. */
+ List<ExprAST> idx;
+ /// \cond Doxygen_Suppress
+ explicit IndexASTObj(ExprAST obj, List<ExprAST> idx)
+ : IndexASTObj(List<AccessPath>{}, std::move(obj), std::move(idx)) {}
+ explicit IndexASTObj(List<AccessPath> source_paths, ExprAST obj, List<ExprAST> idx)
+ : ExprASTObj(std::move(source_paths)), obj(std::move(obj)), idx(std::move(idx)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Index", IndexASTObj, ExprASTObj);
+ /// \endcond
+};
+
+/*!
+ * \brief Reference wrapper for an index/subscript expression (e.g. `obj[idx]`).
+ *
+ * \code{.cpp}
+ * IndexAST idx(IdAST("arr"), {LiteralAST::Int(0)});
+ * // Renders as: arr[0]
+ * \endcode
+ *
+ * \sa IndexASTObj, ExprIndex
+ */
+struct IndexAST : public ExprAST {
+ /// \cond Doxygen_Suppress
+ explicit IndexAST(ExprAST obj, List<ExprAST> idx)
+ : IndexAST(List<AccessPath>{}, std::move(obj), std::move(idx)) {}
+ explicit IndexAST(List<AccessPath> source_paths, ExprAST obj, List<ExprAST> idx)
+ : IndexAST(
+ make_object<IndexASTObj>(std::move(source_paths), std::move(obj), std::move(idx))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(IndexAST, ExprAST, IndexASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit IndexAST(ObjectPtr<IndexASTObj> ptr) : ExprAST(ObjectPtr<ExprASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** CallAST **************/
+
+/*!
+ * \brief Data object for a function call expression with positional and keyword arguments.
+ *
+ * Represents the Python construct `callee(args..., key=value...)` in the
+ * text format AST. Keyword arguments are stored as parallel lists of keys
+ * and values.
+ *
+ * \code{.cpp}
+ * // Build: alloc(shape, dtype="float32")
+ * CallAST call(
+ * IdAST("alloc"),
+ * {IdAST("shape")}, // positional args
+ * {String("dtype")}, // kwarg keys
+ * {LiteralAST::Str("float32")} // kwarg values
+ * );
+ * \endcode
+ *
+ * \sa CallAST, ExprCall, ExprCallKw
+ */
+struct CallASTObj : public ExprASTObj {
+ /*! \brief The callee expression (e.g. `alloc` in `alloc(shape)`). */
+ ExprAST callee;
+ /*! \brief Positional argument expressions. */
+ List<ExprAST> args;
+ /*! \brief Keyword argument names, parallel to kwargs_values (e.g. `{"dtype"}`). */
+ List<String> kwargs_keys;
+ /*! \brief Keyword argument value expressions, parallel to kwargs_keys. */
+ List<ExprAST> kwargs_values;
+ /// \cond Doxygen_Suppress
+ explicit CallASTObj(ExprAST callee, List<ExprAST> args, List<String> kwargs_keys,
+ List<ExprAST> kwargs_values)
+ : CallASTObj(List<AccessPath>{}, std::move(callee), std::move(args), std::move(kwargs_keys),
+ std::move(kwargs_values)) {}
+ explicit CallASTObj(List<AccessPath> source_paths, ExprAST callee, List<ExprAST> args,
+ List<String> kwargs_keys, List<ExprAST> kwargs_values)
+ : ExprASTObj(std::move(source_paths)),
+ callee(std::move(callee)),
+ args(std::move(args)),
+ kwargs_keys(std::move(kwargs_keys)),
+ kwargs_values(std::move(kwargs_values)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Call", CallASTObj, ExprASTObj);
+ /// \endcond
+};
+
+/*!
+ * \brief Reference wrapper for a function call expression.
+ *
+ * \code{.cpp}
+ * // Build: print("hello", end="")
+ * CallAST call(
+ * IdAST("print"),
+ * {LiteralAST::Str("hello")},
+ * {String("end")},
+ * {LiteralAST::Str("")}
+ * );
+ * \endcode
+ *
+ * \sa CallASTObj, ExprCall, ExprCallKw
+ */
+struct CallAST : public ExprAST {
+ /// \cond Doxygen_Suppress
+ explicit CallAST(ExprAST callee, List<ExprAST> args, List<String> kwargs_keys,
+ List<ExprAST> kwargs_values)
+ : CallAST(List<AccessPath>{}, std::move(callee), std::move(args), std::move(kwargs_keys),
+ std::move(kwargs_values)) {}
+ explicit CallAST(List<AccessPath> source_paths, ExprAST callee, List<ExprAST> args,
+ List<String> kwargs_keys, List<ExprAST> kwargs_values)
+ : CallAST(make_object<CallASTObj>(std::move(source_paths), std::move(callee), std::move(args),
+ std::move(kwargs_keys), std::move(kwargs_values))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(CallAST, ExprAST, CallASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit CallAST(ObjectPtr<CallASTObj> ptr) : ExprAST(ObjectPtr<ExprASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** OperationAST **************/
+
+/*!
+ * \brief Data object for a unary, binary, or special operation expression.
+ *
+ * Represents Python operators in the text format AST. The `op` field
+ * selects the operator kind, and `operands` holds 1, 2, or 3 sub-expressions
+ * depending on the operator arity.
+ *
+ * \code{.cpp}
+ * // Build: x + 1
+ * OperationAST add(
+ * OperationASTObj::kAdd,
+ * {IdAST("x"), LiteralAST::Int(1)}
+ * );
+ * // Build: -x (unary negation)
+ * OperationAST neg(OperationASTObj::kUSub, {IdAST("x")});
+ * // Build: a if cond else b (ternary)
+ * OperationAST ternary(
+ * OperationASTObj::kIfThenElse,
+ * {IdAST("a"), IdAST("cond"), IdAST("b")}
+ * );
+ * \endcode
+ *
+ * \sa OperationAST
+ */
+struct OperationASTObj : public ExprASTObj {
+ /*!
+ * \brief Enumeration of unary, binary, and special operation kinds.
+ *
+ * Values are grouped into three ranges:
+ * - **Unary** (kUnaryStart..kUnaryEnd): kUSub (`-x`), kInvert (`~x`), kNot (`not x`).
+ * Takes 1 operand.
+ * - **Binary** (kBinaryStart..kBinaryEnd): arithmetic (kAdd, kSub, kMult, kDiv,
+ * kFloorDiv, kMod, kPow), bitwise (kLShift, kRShift, kBitAnd, kBitOr, kBitXor),
+ * comparison (kLt, kLtE, kEq, kNotEq, kGt, kGtE), and logical (kAnd, kOr).
+ * Takes 2 operands.
+ * - **Special** (kSpecialStart..kSpecialEnd): kIfThenElse (`a if cond else b`).
+ * Takes 3 operands: [true_value, condition, false_value].
+ */
+ enum Kind : int64_t {
+ kUndefined = -1, /*!< \brief Undefined / not applicable. */
+ kUnaryStart = 0, /*!< \brief Sentinel: start of unary operators. */
+ kUSub = 1, /*!< \brief Unary minus: `-x`. */
+ kInvert = 2, /*!< \brief Bitwise invert: `~x`. */
+ kNot = 3, /*!< \brief Logical not: `not x`. */
+ kUAdd = 4, /*!< \brief Unary plus: `+x`. */
+ kUnaryEnd = 5, /*!< \brief Sentinel: end of unary operators. */
+ kBinaryStart = 5, /*!< \brief Sentinel: start of binary operators. */
+ kAdd = 6, /*!< \brief Addition: `x + y`. */
+ kSub = 7, /*!< \brief Subtraction: `x - y`. */
+ kMult = 8, /*!< \brief Multiplication: `x * y`. */
+ kDiv = 9, /*!< \brief True division: `x / y`. */
+ kFloorDiv = 10, /*!< \brief Floor division: `x // y`. */
+ kMod = 11, /*!< \brief Modulo: `x % y`. */
+ kPow = 12, /*!< \brief Exponentiation: `x ** y`. */
+ kLShift = 13, /*!< \brief Left shift: `x << y`. */
+ kRShift = 14, /*!< \brief Right shift: `x >> y`. */
+ kBitAnd = 15, /*!< \brief Bitwise AND: `x & y`. */
+ kBitOr = 16, /*!< \brief Bitwise OR: `x | y`. */
+ kBitXor = 17, /*!< \brief Bitwise XOR: `x ^ y`. */
+ kLt = 18, /*!< \brief Less than: `x < y`. */
+ kLtE = 19, /*!< \brief Less than or equal: `x <= y`. */
+ kEq = 20, /*!< \brief Equal: `x == y`. */
+ kNotEq = 21, /*!< \brief Not equal: `x != y`. */
+ kGt = 22, /*!< \brief Greater than: `x > y`. */
+ kGtE = 23, /*!< \brief Greater than or equal: `x >= y`. */
+ kAnd = 24, /*!< \brief Logical AND: `x and y`. */
+ kOr = 25, /*!< \brief Logical OR: `x or y`. */
+ kMatMult = 26, /*!< \brief Matrix multiply: `x @ y`. */
+ kIs = 27, /*!< \brief Identity test: `x is y`. */
+ kIsNot = 28, /*!< \brief Negated identity test: `x is not y`. */
+ kIn = 29, /*!< \brief Containment test: `x in y`. */
+ kNotIn = 30, /*!< \brief Negated containment test: `x not in y`. */
+ kBinaryEnd = 31, /*!< \brief Sentinel: end of binary operators. */
+ kSpecialStart = 32, /*!< \brief Sentinel: start of special operators. */
+ kIfThenElse = 33, /*!< \brief Ternary: `a if cond else b`. */
+ kChainedCompare = 34, /*!< \brief Chained comparison: `a < b < c`. */
+ kParens = 35, /*!< \brief Explicit parenthesization: `(expr)`. */
+ kSpecialEnd = 36, /*!< \brief Sentinel: end of special operators. */
+ };
+
+ /*!
+ * \brief The operation kind, storing a value from the Kind enum.
+ *
+ * Use one of the Kind enum values (e.g. `OperationASTObj::kAdd`,
+ * `OperationASTObj::kUSub`, `OperationASTObj::kIfThenElse`).
+ */
+ int64_t op;
+ /*! \brief The operand expressions (1 for unary, 2 for binary, 3 for ternary). */
+ List<ExprAST> operands;
+ /// \cond Doxygen_Suppress
+ explicit OperationASTObj(int64_t op, List<ExprAST> operands)
+ : OperationASTObj(List<AccessPath>{}, op, std::move(operands)) {}
+ explicit OperationASTObj(List<AccessPath> source_paths, int64_t op, List<ExprAST> operands)
+ : ExprASTObj(std::move(source_paths)), op(op), operands(std::move(operands)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Operation", OperationASTObj, ExprASTObj);
+ /// \endcond
+};
+
+/*!
+ * \brief Reference wrapper for a unary, binary, or special operation expression.
+ *
+ * \code{.cpp}
+ * // Build: a * b + c
+ * OperationAST mul(OperationASTObj::kMult, {IdAST("a"), IdAST("b")});
+ * OperationAST add(OperationASTObj::kAdd, {mul, IdAST("c")});
+ * \endcode
+ *
+ * \sa OperationASTObj
+ */
+struct OperationAST : public ExprAST {
+ /// \cond Doxygen_Suppress
+ explicit OperationAST(int64_t op, List<ExprAST> operands)
+ : OperationAST(List<AccessPath>{}, op, std::move(operands)) {}
+ explicit OperationAST(List<AccessPath> source_paths, int64_t op, List<ExprAST> operands)
+ : OperationAST(
+ make_object<OperationASTObj>(std::move(source_paths), op, std::move(operands))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(OperationAST, ExprAST, OperationASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit OperationAST(ObjectPtr<OperationASTObj> ptr)
+ : ExprAST(ObjectPtr<ExprASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** LambdaAST **************/
+
+/*!
+ * \brief Data object for a lambda expression (e.g. `lambda x, y: x + y`).
+ *
+ * Represents a Python lambda expression in the text format AST.
+ *
+ * \code{.cpp}
+ * // Build: lambda x, y: x + y
+ * LambdaAST lam(
+ * {IdAST("x"), IdAST("y")},
+ * OperationAST(OperationASTObj::kAdd, {IdAST("x"), IdAST("y")})
+ * );
+ * \endcode
+ *
+ * \sa LambdaAST
+ */
+struct LambdaASTObj : public ExprASTObj {
+ /*! \brief The argument list (IdAST or StarredExpr for varargs). */
+ List<ExprAST> args;
+ /*! \brief The lambda body expression. */
+ ExprAST body;
+ /// \cond Doxygen_Suppress
+ explicit LambdaASTObj(List<ExprAST> args, ExprAST body)
+ : LambdaASTObj(List<AccessPath>{}, std::move(args), std::move(body)) {}
+ explicit LambdaASTObj(List<AccessPath> source_paths, List<ExprAST> args, ExprAST body)
+ : ExprASTObj(std::move(source_paths)), args(std::move(args)), body(std::move(body)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Lambda", LambdaASTObj, ExprASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for a lambda expression. */
+struct LambdaAST : public ExprAST {
+ /// \cond Doxygen_Suppress
+ explicit LambdaAST(List<ExprAST> args, ExprAST body)
+ : LambdaAST(List<AccessPath>{}, std::move(args), std::move(body)) {}
+ explicit LambdaAST(List<AccessPath> source_paths, List<ExprAST> args, ExprAST body)
+ : LambdaAST(
+ make_object<LambdaASTObj>(std::move(source_paths), std::move(args), std::move(body))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(LambdaAST, ExprAST, LambdaASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit LambdaAST(ObjectPtr<LambdaASTObj> ptr)
+ : ExprAST(ObjectPtr<ExprASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** TupleAST **************/
+
+/*!
+ * \brief Data object for a tuple expression (e.g. `(a, b, c)`).
+ *
+ * Represents a Python tuple literal in the text format AST.
+ *
+ * \code{.cpp}
+ * // Build: (1, 2, 3)
+ * TupleAST tup({LiteralAST::Int(1), LiteralAST::Int(2), LiteralAST::Int(3)});
+ * \endcode
+ *
+ * \sa TupleAST
+ */
+struct TupleASTObj : public ExprASTObj {
+ /*! \brief The contained values. */
+ List<ExprAST> values;
+ /// \cond Doxygen_Suppress
+ explicit TupleASTObj(List<ExprAST> values) : TupleASTObj(List<AccessPath>{}, std::move(values)) {}
+ explicit TupleASTObj(List<AccessPath> source_paths, List<ExprAST> values)
+ : ExprASTObj(std::move(source_paths)), values(std::move(values)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Tuple", TupleASTObj, ExprASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for a tuple expression. */
+struct TupleAST : public ExprAST {
+ /// \cond Doxygen_Suppress
+ explicit TupleAST(List<ExprAST> values) : TupleAST(List<AccessPath>{}, std::move(values)) {}
+ explicit TupleAST(List<AccessPath> source_paths, List<ExprAST> values)
+ : TupleAST(make_object<TupleASTObj>(std::move(source_paths), std::move(values))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(TupleAST, ExprAST, TupleASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit TupleAST(ObjectPtr<TupleASTObj> ptr) : ExprAST(ObjectPtr<ExprASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** ListAST **************/
+
+/*!
+ * \brief Data object for a list expression (e.g. `[a, b, c]`).
+ *
+ * Represents a Python list literal in the text format AST.
+ *
+ * \code{.cpp}
+ * // Build: [1, 2, 3]
+ * ListAST lst({LiteralAST::Int(1), LiteralAST::Int(2), LiteralAST::Int(3)});
+ * \endcode
+ *
+ * \sa ListAST
+ */
+struct ListASTObj : public ExprASTObj {
+ /*! \brief The contained values. */
+ List<ExprAST> values;
+ /// \cond Doxygen_Suppress
+ explicit ListASTObj(List<ExprAST> values) : ListASTObj(List<AccessPath>{}, std::move(values)) {}
+ explicit ListASTObj(List<AccessPath> source_paths, List<ExprAST> values)
+ : ExprASTObj(std::move(source_paths)), values(std::move(values)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.List", ListASTObj, ExprASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for a list expression. */
+struct ListAST : public ExprAST {
+ /// \cond Doxygen_Suppress
+ explicit ListAST(List<ExprAST> values) : ListAST(List<AccessPath>{}, std::move(values)) {}
+ explicit ListAST(List<AccessPath> source_paths, List<ExprAST> values)
+ : ListAST(make_object<ListASTObj>(std::move(source_paths), std::move(values))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(ListAST, ExprAST, ListASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit ListAST(ObjectPtr<ListASTObj> ptr) : ExprAST(ObjectPtr<ExprASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** DictAST **************/
+
+/*!
+ * \brief Data object for a dictionary expression (e.g. `{k1: v1, k2: v2}`).
+ *
+ * Represents a Python dict literal in the text format AST. Keys and
+ * values are stored as parallel lists.
+ *
+ * \code{.cpp}
+ * // Build: {"x": 1, "y": 2}
+ * DictAST d(
+ * {LiteralAST::Str("x"), LiteralAST::Str("y")},
+ * {LiteralAST::Int(1), LiteralAST::Int(2)}
+ * );
+ * \endcode
+ *
+ * \sa DictAST
+ */
+struct DictASTObj : public ExprASTObj {
+ /*! \brief The key expressions (parallel to values). */
+ List<ExprAST> keys;
+ /*! \brief The value expressions (parallel to keys). */
+ List<ExprAST> values;
+ /// \cond Doxygen_Suppress
+ explicit DictASTObj(List<ExprAST> keys, List<ExprAST> values)
+ : DictASTObj(List<AccessPath>{}, std::move(keys), std::move(values)) {}
+ explicit DictASTObj(List<AccessPath> source_paths, List<ExprAST> keys, List<ExprAST> values)
+ : ExprASTObj(std::move(source_paths)), keys(std::move(keys)), values(std::move(values)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Dict", DictASTObj, ExprASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for a dictionary expression. */
+struct DictAST : public ExprAST {
+ /// \cond Doxygen_Suppress
+ explicit DictAST(List<ExprAST> keys, List<ExprAST> values)
+ : DictAST(List<AccessPath>{}, std::move(keys), std::move(values)) {}
+ explicit DictAST(List<AccessPath> source_paths, List<ExprAST> keys, List<ExprAST> values)
+ : DictAST(
+ make_object<DictASTObj>(std::move(source_paths), std::move(keys), std::move(values))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(DictAST, ExprAST, DictASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit DictAST(ObjectPtr<DictASTObj> ptr) : ExprAST(ObjectPtr<ExprASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** SetAST **************/
+
+/*! \brief Data object for a set expression (e.g. `{a, b, c}`). */
+struct SetASTObj : public ExprASTObj {
+ /*! \brief The contained values. */
+ List<ExprAST> values;
+ /// \cond Doxygen_Suppress
+ explicit SetASTObj(List<ExprAST> values) : SetASTObj(List<AccessPath>{}, std::move(values)) {}
+ explicit SetASTObj(List<AccessPath> source_paths, List<ExprAST> values)
+ : ExprASTObj(std::move(source_paths)), values(std::move(values)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Set", SetASTObj, ExprASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for a set expression. */
+struct SetAST : public ExprAST {
+ /// \cond Doxygen_Suppress
+ explicit SetAST(List<ExprAST> values) : SetAST(List<AccessPath>{}, std::move(values)) {}
+ explicit SetAST(List<AccessPath> source_paths, List<ExprAST> values)
+ : SetAST(make_object<SetASTObj>(std::move(source_paths), std::move(values))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(SetAST, ExprAST, SetASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit SetAST(ObjectPtr<SetASTObj> ptr) : ExprAST(ObjectPtr<ExprASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** ComprehensionIterAST **************/
+
+/*! \brief Data object for one `for target in iter [if cond]...` clause in a comprehension. */
+struct ComprehensionIterASTObj : public NodeASTObj {
+ /*! \brief The loop variable (e.g. `x` in `for x in items`). */
+ ExprAST target;
+ /*! \brief The iterable expression (e.g. `items` in `for x in items`). */
+ ExprAST iter;
+ /*! \brief Zero or more filter conditions. */
+ List<ExprAST> ifs;
+ /// \cond Doxygen_Suppress
+ explicit ComprehensionIterASTObj(ExprAST target, ExprAST iter, List<ExprAST> ifs)
+ : ComprehensionIterASTObj(List<AccessPath>{}, std::move(target), std::move(iter),
+ std::move(ifs)) {}
+ explicit ComprehensionIterASTObj(List<AccessPath> source_paths, ExprAST target, ExprAST iter,
+ List<ExprAST> ifs)
+ : NodeASTObj(std::move(source_paths)),
+ target(std::move(target)),
+ iter(std::move(iter)),
+ ifs(std::move(ifs)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.ComprehensionIter", ComprehensionIterASTObj,
+ NodeASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for a comprehension iterator clause. */
+struct ComprehensionIterAST : public NodeAST {
+ /// \cond Doxygen_Suppress
+ explicit ComprehensionIterAST(ExprAST target, ExprAST iter, List<ExprAST> ifs)
+ : ComprehensionIterAST(List<AccessPath>{}, std::move(target), std::move(iter),
+ std::move(ifs)) {}
+ explicit ComprehensionIterAST(List<AccessPath> source_paths, ExprAST target, ExprAST iter,
+ List<ExprAST> ifs)
+ : ComprehensionIterAST(make_object<ComprehensionIterASTObj>(
+ std::move(source_paths), std::move(target), std::move(iter), std::move(ifs))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(ComprehensionIterAST, NodeAST,
+ ComprehensionIterASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit ComprehensionIterAST(ObjectPtr<ComprehensionIterASTObj> ptr)
+ : NodeAST(ObjectPtr<NodeASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** ComprehensionAST **************/
+
+/*!
+ * \brief Data object for a comprehension expression.
+ *
+ * Covers list comprehensions (`[elt for ...]`), set comprehensions
+ * (`{elt for ...}`), dict comprehensions (`{key: value for ...}`),
+ * and generator expressions (`(elt for ...)`).
+ */
+struct ComprehensionASTObj : public ExprASTObj {
+ /*! \brief Kind of comprehension. */
+ enum Kind : int64_t {
+ kList = 0, /*!< \brief List comprehension: `[elt for ...]`. */
+ kSet = 1, /*!< \brief Set comprehension: `{elt for ...}`. */
+ kDict = 2, /*!< \brief Dict comprehension: `{key: value for ...}`. */
+ kGenerator = 3, /*!< \brief Generator expression: `(elt for ...)`. */
+ };
+ /*! \brief The comprehension kind. */
+ int64_t kind;
+ /*! \brief The element expression (or key for dict comprehensions). */
+ ExprAST elt;
+ /*! \brief The value expression (only for dict comprehensions; null otherwise). */
+ Optional<ExprAST> value;
+ /*! \brief The list of `for ... in ... [if ...]` clauses. */
+ List<ComprehensionIterAST> iters;
+ /// \cond Doxygen_Suppress
+ explicit ComprehensionASTObj(int64_t kind, ExprAST elt, Optional<ExprAST> value,
+ List<ComprehensionIterAST> iters)
+ : ComprehensionASTObj(List<AccessPath>{}, kind, std::move(elt), std::move(value),
+ std::move(iters)) {}
+ explicit ComprehensionASTObj(List<AccessPath> source_paths, int64_t kind, ExprAST elt,
+ Optional<ExprAST> value, List<ComprehensionIterAST> iters)
+ : ExprASTObj(std::move(source_paths)),
+ kind(kind),
+ elt(std::move(elt)),
+ value(std::move(value)),
+ iters(std::move(iters)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Comprehension", ComprehensionASTObj, ExprASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for a comprehension expression. */
+struct ComprehensionAST : public ExprAST {
+ /// \cond Doxygen_Suppress
+ explicit ComprehensionAST(int64_t kind, ExprAST elt, Optional<ExprAST> value,
+ List<ComprehensionIterAST> iters)
+ : ComprehensionAST(List<AccessPath>{}, kind, std::move(elt), std::move(value),
+ std::move(iters)) {}
+ explicit ComprehensionAST(List<AccessPath> source_paths, int64_t kind, ExprAST elt,
+ Optional<ExprAST> value, List<ComprehensionIterAST> iters)
+ : ComprehensionAST(make_object<ComprehensionASTObj>(
+ std::move(source_paths), kind, std::move(elt), std::move(value), std::move(iters))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(ComprehensionAST, ExprAST, ComprehensionASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit ComprehensionAST(ObjectPtr<ComprehensionASTObj> ptr)
+ : ExprAST(ObjectPtr<ExprASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** YieldAST **************/
+
+/*! \brief Data object for a yield expression (e.g. `yield value`). */
+struct YieldASTObj : public ExprASTObj {
+ /*! \brief The yielded value, or null for bare `yield`. */
+ Optional<ExprAST> value;
+ /// \cond Doxygen_Suppress
+ explicit YieldASTObj(Optional<ExprAST> value = {})
+ : YieldASTObj(List<AccessPath>{}, std::move(value)) {}
+ explicit YieldASTObj(List<AccessPath> source_paths, Optional<ExprAST> value)
+ : ExprASTObj(std::move(source_paths)), value(std::move(value)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Yield", YieldASTObj, ExprASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for a yield expression. */
+struct YieldAST : public ExprAST {
+ /// \cond Doxygen_Suppress
+ explicit YieldAST(Optional<ExprAST> value = {})
+ : YieldAST(List<AccessPath>{}, std::move(value)) {}
+ explicit YieldAST(List<AccessPath> source_paths, Optional<ExprAST> value)
+ : YieldAST(make_object<YieldASTObj>(std::move(source_paths), std::move(value))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(YieldAST, ExprAST, YieldASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit YieldAST(ObjectPtr<YieldASTObj> ptr) : ExprAST(ObjectPtr<ExprASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** YieldFromAST **************/
+
+/*! \brief Data object for a yield-from expression (e.g. `yield from iterable`). */
+struct YieldFromASTObj : public ExprASTObj {
+ /*! \brief The iterable to yield from. */
+ ExprAST value;
+ /// \cond Doxygen_Suppress
+ explicit YieldFromASTObj(ExprAST value) : YieldFromASTObj(List<AccessPath>{}, std::move(value)) {}
+ explicit YieldFromASTObj(List<AccessPath> source_paths, ExprAST value)
+ : ExprASTObj(std::move(source_paths)), value(std::move(value)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.YieldFrom", YieldFromASTObj, ExprASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for a yield-from expression. */
+struct YieldFromAST : public ExprAST {
+ /// \cond Doxygen_Suppress
+ explicit YieldFromAST(ExprAST value) : YieldFromAST(List<AccessPath>{}, std::move(value)) {}
+ explicit YieldFromAST(List<AccessPath> source_paths, ExprAST value)
+ : YieldFromAST(make_object<YieldFromASTObj>(std::move(source_paths), std::move(value))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(YieldFromAST, ExprAST, YieldFromASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit YieldFromAST(ObjectPtr<YieldFromASTObj> ptr)
+ : ExprAST(ObjectPtr<ExprASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** SliceAST **************/
+
+/*!
+ * \brief Data object for a slice expression (e.g. `start:stop:step`).
+ *
+ * Represents a Python slice in the text format AST, typically used
+ * inside an IndexAST. Each of start, stop, and step is optional.
+ *
+ * \code{.cpp}
+ * // Build: 0:10:2 (used inside obj[0:10:2])
+ * SliceAST slc(LiteralAST::Int(0), LiteralAST::Int(10), LiteralAST::Int(2));
+ * // Build: :5 (start omitted)
+ * SliceAST slc2(NullOpt, LiteralAST::Int(5), NullOpt);
+ * \endcode
+ *
+ * \sa SliceAST
+ */
+struct SliceASTObj : public ExprASTObj {
+ /*! \brief The start expression, or null if omitted (e.g. `:5` has no start). */
+ Optional<ExprAST> start;
+ /*! \brief The stop expression, or null if omitted (e.g. `1:` has no stop). */
+ Optional<ExprAST> stop;
+ /*! \brief The step expression, or null if omitted (e.g. `1:5` has no step). */
+ Optional<ExprAST> step;
+ /// \cond Doxygen_Suppress
+ explicit SliceASTObj(Optional<ExprAST> start = {}, Optional<ExprAST> stop = {},
+ Optional<ExprAST> step = {})
+ : SliceASTObj(List<AccessPath>{}, std::move(start), std::move(stop), std::move(step)) {}
+ explicit SliceASTObj(List<AccessPath> source_paths, Optional<ExprAST> start,
+ Optional<ExprAST> stop, Optional<ExprAST> step)
+ : ExprASTObj(std::move(source_paths)),
+ start(std::move(start)),
+ stop(std::move(stop)),
+ step(std::move(step)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Slice", SliceASTObj, ExprASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for a slice expression. */
+struct SliceAST : public ExprAST {
+ /// \cond Doxygen_Suppress
+ explicit SliceAST(Optional<ExprAST> start = {}, Optional<ExprAST> stop = {},
+ Optional<ExprAST> step = {})
+ : SliceAST(List<AccessPath>{}, std::move(start), std::move(stop), std::move(step)) {}
+ explicit SliceAST(List<AccessPath> source_paths, Optional<ExprAST> start, Optional<ExprAST> stop,
+ Optional<ExprAST> step)
+ : SliceAST(make_object<SliceASTObj>(std::move(source_paths), std::move(start),
+ std::move(stop), std::move(step))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(SliceAST, ExprAST, SliceASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit SliceAST(ObjectPtr<SliceASTObj> ptr) : ExprAST(ObjectPtr<ExprASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** AssignAST **************/
+
+/*!
+ * \brief Data object for an assignment statement (e.g. `lhs = rhs` or `lhs: annotation = rhs`).
+ *
+ * Represents the Python construct `lhs = rhs` with an optional type
+ * annotation. When used for function arguments in FunctionAST, only
+ * lhs (parameter name) and annotation (type hint) are set, with no rhs.
+ *
+ * \code{.cpp}
+ * // Build: x: int = 42
+ * AssignAST assign(
+ * {}, String("initial value"),
+ * IdAST("x"), LiteralAST::Int(42), IdAST("int")
+ * );
+ * // Renders as: x: int = 42 # initial value
+ * \endcode
+ *
+ * \sa AssignAST
+ */
+struct AssignASTObj : public StmtASTObj {
+ /*! \brief The left-hand side expression (e.g. `x` in `x = 42`). */
+ ExprAST lhs;
+ /*! \brief The right-hand side expression (e.g. `42` in `x = 42`), or null for declarations. */
+ Optional<ExprAST> rhs;
+ /*! \brief Optional type annotation (e.g. `int` in `x: int = 42`). */
+ Optional<ExprAST> annotation;
+ /*!
+ * \brief Augmented-assignment operator kind, or kUndefined for plain assignment.
+ *
+ * When not kUndefined, this holds an OperationASTObj::Kind value (e.g. kAdd
+ * for `+=`) and the printer renders `lhs op= rhs` instead of `lhs = rhs`.
+ */
+ OperationASTObj::Kind aug_op{OperationASTObj::kUndefined};
+ /// \cond Doxygen_Suppress
+ explicit AssignASTObj(ExprAST lhs, Optional<ExprAST> rhs = {}, Optional<ExprAST> annotation = {},
+ int64_t aug_op = OperationASTObj::kUndefined)
+ : AssignASTObj(List<AccessPath>{}, Optional<String>{}, std::move(lhs), std::move(rhs),
+ std::move(annotation), static_cast<OperationASTObj::Kind>(aug_op)) {}
+ explicit AssignASTObj(List<AccessPath> source_paths, Optional<String> comment, ExprAST lhs,
+ Optional<ExprAST> rhs, Optional<ExprAST> annotation,
+ OperationASTObj::Kind aug_op = OperationASTObj::kUndefined)
+ : StmtASTObj(std::move(source_paths), std::move(comment)),
+ lhs(std::move(lhs)),
+ rhs(std::move(rhs)),
+ annotation(std::move(annotation)),
+ aug_op(aug_op) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Assign", AssignASTObj, StmtASTObj);
+ /// \endcond
+};
+
+/*!
+ * \brief Reference wrapper for an assignment statement.
+ *
+ * \code{.cpp}
+ * // Build: result = compute(data)
+ * AssignAST stmt(IdAST("result"), ExprCall(IdAST("compute"), {IdAST("data")}));
+ * \endcode
+ *
+ * \sa AssignASTObj
+ */
+struct AssignAST : public StmtAST {
+ /// \cond Doxygen_Suppress
+ explicit AssignAST(ExprAST lhs, Optional<ExprAST> rhs = {}, Optional<ExprAST> annotation = {},
+ int64_t aug_op = OperationASTObj::kUndefined)
+ : AssignAST(List<AccessPath>{}, Optional<String>{}, std::move(lhs), std::move(rhs),
+ std::move(annotation), static_cast<OperationASTObj::Kind>(aug_op)) {}
+ explicit AssignAST(List<AccessPath> source_paths, Optional<String> comment, ExprAST lhs,
+ Optional<ExprAST> rhs, Optional<ExprAST> annotation,
+ OperationASTObj::Kind aug_op = OperationASTObj::kUndefined)
+ : AssignAST(make_object<AssignASTObj>(std::move(source_paths), std::move(comment),
+ std::move(lhs), std::move(rhs), std::move(annotation),
+ aug_op)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(AssignAST, StmtAST, AssignASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit AssignAST(ObjectPtr<AssignASTObj> ptr)
+ : StmtAST(ObjectPtr<StmtASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** IfAST **************/
+
+/*!
+ * \brief Data object for an if/else statement.
+ *
+ * Represents the Python construct `if cond: ... else: ...` in the text
+ * format AST. The else_branch may be empty for a plain `if` without `else`.
+ *
+ * \code{.cpp}
+ * // Build:
+ * // if x > 0:
+ * // return x
+ * // else:
+ * // return -x
+ * IfAST if_stmt(
+ * OperationAST(OperationASTObj::kGt, {IdAST("x"), LiteralAST::Int(0)}),
+ * {ReturnAST(IdAST("x"))},
+ * {ReturnAST(OperationAST(OperationASTObj::kUSub, {IdAST("x")}))}
+ * );
+ * \endcode
+ *
+ * \sa IfAST
+ */
+struct IfASTObj : public StmtASTObj {
+ /*! \brief The condition expression (e.g. `x > 0`). */
+ ExprAST cond;
+ /*! \brief Statements for the true branch (the `if` body). */
+ List<StmtAST> then_branch;
+ /*! \brief Statements for the false branch (the `else` body; may be empty for no else). */
+ List<StmtAST> else_branch;
+ /// \cond Doxygen_Suppress
+ explicit IfASTObj(ExprAST cond, List<StmtAST> then_branch, List<StmtAST> else_branch)
+ : IfASTObj(List<AccessPath>{}, Optional<String>{}, std::move(cond), std::move(then_branch),
+ std::move(else_branch)) {}
+ explicit IfASTObj(List<AccessPath> source_paths, Optional<String> comment, ExprAST cond,
+ List<StmtAST> then_branch, List<StmtAST> else_branch)
+ : StmtASTObj(std::move(source_paths), std::move(comment)),
+ cond(std::move(cond)),
+ then_branch(std::move(then_branch)),
+ else_branch(std::move(else_branch)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.If", IfASTObj, StmtASTObj);
+ /// \endcond
+};
+
+/*!
+ * \brief Reference wrapper for an if/else statement.
+ *
+ * \code{.cpp}
+ * // Build: if flag: pass (no else branch)
+ * IfAST if_only(IdAST("flag"), {ExprStmtAST(IdAST("pass"))}, {});
+ * \endcode
+ *
+ * \sa IfASTObj
+ */
+struct IfAST : public StmtAST {
+ /// \cond Doxygen_Suppress
+ explicit IfAST(ExprAST cond, List<StmtAST> then_branch, List<StmtAST> else_branch)
+ : IfAST(List<AccessPath>{}, Optional<String>{}, std::move(cond), std::move(then_branch),
+ std::move(else_branch)) {}
+ explicit IfAST(List<AccessPath> source_paths, Optional<String> comment, ExprAST cond,
+ List<StmtAST> then_branch, List<StmtAST> else_branch)
+ : IfAST(make_object<IfASTObj>(std::move(source_paths), std::move(comment), std::move(cond),
+ std::move(then_branch), std::move(else_branch))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(IfAST, StmtAST, IfASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit IfAST(ObjectPtr<IfASTObj> ptr) : StmtAST(ObjectPtr<StmtASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** WhileAST **************/
+
+/*!
+ * \brief Data object for a while-loop statement.
+ *
+ * Represents the Python construct `while cond: body` in the text format AST.
+ *
+ * \code{.cpp}
+ * // Build:
+ * // while i < n:
+ * // i = i + 1
+ * WhileAST loop(
+ * OperationAST(OperationASTObj::kLt, {IdAST("i"), IdAST("n")}),
+ * {AssignAST(IdAST("i"),
+ * OperationAST(OperationASTObj::kAdd, {IdAST("i"), LiteralAST::Int(1)}))}
+ * );
+ * \endcode
+ *
+ * \sa WhileAST
+ */
+struct WhileASTObj : public StmtASTObj {
+ /*! \brief The loop condition expression (e.g. `i < n`). */
+ ExprAST cond;
+ /*! \brief The loop body statements. */
+ List<StmtAST> body;
+ /*! \brief The else-branch statements (executed when loop finishes normally). */
+ List<StmtAST> orelse;
+ /// \cond Doxygen_Suppress
+ explicit WhileASTObj(ExprAST cond, List<StmtAST> body, List<StmtAST> orelse = {})
+ : WhileASTObj(List<AccessPath>{}, Optional<String>{}, std::move(cond), std::move(body),
+ std::move(orelse)) {}
+ explicit WhileASTObj(List<AccessPath> source_paths, Optional<String> comment, ExprAST cond,
+ List<StmtAST> body, List<StmtAST> orelse)
+ : StmtASTObj(std::move(source_paths), std::move(comment)),
+ cond(std::move(cond)),
+ body(std::move(body)),
+ orelse(std::move(orelse)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.While", WhileASTObj, StmtASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for a while-loop statement. */
+struct WhileAST : public StmtAST {
+ /// \cond Doxygen_Suppress
+ explicit WhileAST(ExprAST cond, List<StmtAST> body, List<StmtAST> orelse = {})
+ : WhileAST(List<AccessPath>{}, Optional<String>{}, std::move(cond), std::move(body),
+ std::move(orelse)) {}
+ explicit WhileAST(List<AccessPath> source_paths, Optional<String> comment, ExprAST cond,
+ List<StmtAST> body, List<StmtAST> orelse)
+ : WhileAST(make_object<WhileASTObj>(std::move(source_paths), std::move(comment),
+ std::move(cond), std::move(body), std::move(orelse))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(WhileAST, StmtAST, WhileASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit WhileAST(ObjectPtr<WhileASTObj> ptr) : StmtAST(ObjectPtr<StmtASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** ForAST **************/
+
+/*!
+ * \brief Data object for a for-loop statement (e.g. `for lhs in rhs`).
+ *
+ * Represents the Python construct `for lhs in rhs: body` in the text format AST.
+ *
+ * \code{.cpp}
+ * // Build:
+ * // for i in range(10):
+ * // compute(i)
+ * ForAST loop(
+ * IdAST("i"),
+ * ExprCall(IdAST("range"), {LiteralAST::Int(10)}),
+ * {ExprStmtAST(ExprCall(IdAST("compute"), {IdAST("i")}))}
+ * );
+ * \endcode
+ *
+ * \sa ForAST
+ */
+struct ForASTObj : public StmtASTObj {
+ /*! \brief The loop variable expression (e.g. `i` in `for i in range(10)`). */
+ ExprAST lhs;
+ /*! \brief The iterable expression (e.g. `range(10)` in `for i in range(10)`). */
+ ExprAST rhs;
+ /*! \brief The loop body statements. */
+ List<StmtAST> body;
+ /*! \brief Whether this is an `async for` loop. */
+ bool is_async;
+ /*! \brief The else-branch statements (executed when loop finishes normally). */
+ List<StmtAST> orelse;
+ /// \cond Doxygen_Suppress
+ explicit ForASTObj(ExprAST lhs, ExprAST rhs, List<StmtAST> body, bool is_async = false,
+ List<StmtAST> orelse = {})
+ : ForASTObj(List<AccessPath>{}, Optional<String>{}, std::move(lhs), std::move(rhs),
+ std::move(body), is_async, std::move(orelse)) {}
+ explicit ForASTObj(List<AccessPath> source_paths, Optional<String> comment, ExprAST lhs,
+ ExprAST rhs, List<StmtAST> body, bool is_async, List<StmtAST> orelse)
+ : StmtASTObj(std::move(source_paths), std::move(comment)),
+ lhs(std::move(lhs)),
+ rhs(std::move(rhs)),
+ body(std::move(body)),
+ is_async(is_async),
+ orelse(std::move(orelse)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.For", ForASTObj, StmtASTObj);
+ /// \endcond
+};
+
+/*!
+ * \brief Reference wrapper for a for-loop statement.
+ *
+ * \code{.cpp}
+ * ForAST loop(IdAST("item"), IdAST("items"), {ExprStmtAST(IdAST("pass"))});
+ * // Renders as: for item in items:\n pass
+ * \endcode
+ *
+ * \sa ForASTObj
+ */
+struct ForAST : public StmtAST {
+ /// \cond Doxygen_Suppress
+ explicit ForAST(ExprAST lhs, ExprAST rhs, List<StmtAST> body, bool is_async = false,
+ List<StmtAST> orelse = {})
+ : ForAST(List<AccessPath>{}, Optional<String>{}, std::move(lhs), std::move(rhs),
+ std::move(body), is_async, std::move(orelse)) {}
+ explicit ForAST(List<AccessPath> source_paths, Optional<String> comment, ExprAST lhs, ExprAST rhs,
+ List<StmtAST> body, bool is_async, List<StmtAST> orelse)
+ : ForAST(make_object<ForASTObj>(std::move(source_paths), std::move(comment), std::move(lhs),
+ std::move(rhs), std::move(body), is_async,
+ std::move(orelse))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(ForAST, StmtAST, ForASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit ForAST(ObjectPtr<ForASTObj> ptr) : StmtAST(ObjectPtr<StmtASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** WithAST **************/
+
+/*!
+ * \brief Data object for a with-statement (e.g. `with rhs as lhs`).
+ *
+ * Represents the Python construct `with rhs as lhs: body` in the text
+ * format AST. The `as lhs` part is optional (lhs may be null).
+ *
+ * \code{.cpp}
+ * // Build:
+ * // with open("data.txt") as f:
+ * // read(f)
+ * WithAST with_stmt(
+ * IdAST("f"),
+ * ExprCall(IdAST("open"), {LiteralAST::Str("data.txt")}),
+ * {ExprStmtAST(ExprCall(IdAST("read"), {IdAST("f")}))}
+ * );
+ * // Build: with lock(): ... (no `as` target)
+ * WithAST with_no_as(
+ * NullOpt,
+ * ExprCall(IdAST("lock"), {}),
+ * {ExprStmtAST(IdAST("pass"))}
+ * );
+ * \endcode
+ *
+ * \sa WithAST
+ */
+struct WithASTObj : public StmtASTObj {
+ /*! \brief Optional `as` target expression (e.g. `f` in `with open(...) as f`). */
+ Optional<ExprAST> lhs;
+ /*! \brief The context manager expression (e.g. `open("data.txt")`). */
+ ExprAST rhs;
+ /*! \brief The with-block body statements. */
+ List<StmtAST> body;
+ /*! \brief Whether this is an `async with` statement. */
+ bool is_async;
+ /// \cond Doxygen_Suppress
+ explicit WithASTObj(Optional<ExprAST> lhs, ExprAST rhs, List<StmtAST> body, bool is_async = false)
+ : WithASTObj(List<AccessPath>{}, Optional<String>{}, std::move(lhs), std::move(rhs),
+ std::move(body), is_async) {}
+ explicit WithASTObj(List<AccessPath> source_paths, Optional<String> comment,
+ Optional<ExprAST> lhs, ExprAST rhs, List<StmtAST> body, bool is_async)
+ : StmtASTObj(std::move(source_paths), std::move(comment)),
+ lhs(std::move(lhs)),
+ rhs(std::move(rhs)),
+ body(std::move(body)),
+ is_async(is_async) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.With", WithASTObj, StmtASTObj);
+ /// \endcond
+};
+
+/*!
+ * \brief Reference wrapper for a with-statement.
+ *
+ * \code{.cpp}
+ * WithAST ws(IdAST("ctx"), ExprCall(IdAST("scope"), {}), {ExprStmtAST(IdAST("pass"))});
+ * // Renders as: with scope() as ctx:\n pass
+ * \endcode
+ *
+ * \sa WithASTObj
+ */
+struct WithAST : public StmtAST {
+ /// \cond Doxygen_Suppress
+ explicit WithAST(Optional<ExprAST> lhs, ExprAST rhs, List<StmtAST> body, bool is_async = false)
+ : WithAST(List<AccessPath>{}, Optional<String>{}, std::move(lhs), std::move(rhs),
+ std::move(body), is_async) {}
+ explicit WithAST(List<AccessPath> source_paths, Optional<String> comment, Optional<ExprAST> lhs,
+ ExprAST rhs, List<StmtAST> body, bool is_async)
+ : WithAST(make_object<WithASTObj>(std::move(source_paths), std::move(comment), std::move(lhs),
+ std::move(rhs), std::move(body), is_async)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(WithAST, StmtAST, WithASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit WithAST(ObjectPtr<WithASTObj> ptr) : StmtAST(ObjectPtr<StmtASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** ExprStmtAST **************/
+
+/*!
+ * \brief Data object for an expression used as a statement.
+ *
+ * Wraps an expression so it can appear in a statement context, such as
+ * a bare function call.
+ *
+ * \code{.cpp}
+ * // Build: print("hello") (as a statement)
+ * ExprStmtAST stmt(ExprCall(IdAST("print"), {LiteralAST::Str("hello")}));
+ * \endcode
+ *
+ * \sa ExprStmtAST
+ */
+struct ExprStmtASTObj : public StmtASTObj {
+ /*! \brief The expression to evaluate as a statement. */
+ ExprAST expr;
+ /// \cond Doxygen_Suppress
+ explicit ExprStmtASTObj(ExprAST expr)
+ : ExprStmtASTObj(List<AccessPath>{}, Optional<String>{}, std::move(expr)) {}
+ explicit ExprStmtASTObj(List<AccessPath> source_paths, Optional<String> comment, ExprAST expr)
+ : StmtASTObj(std::move(source_paths), std::move(comment)), expr(std::move(expr)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.ExprStmt", ExprStmtASTObj, StmtASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for an expression used as a statement. */
+struct ExprStmtAST : public StmtAST {
+ /// \cond Doxygen_Suppress
+ explicit ExprStmtAST(ExprAST expr)
+ : ExprStmtAST(List<AccessPath>{}, Optional<String>{}, std::move(expr)) {}
+ explicit ExprStmtAST(List<AccessPath> source_paths, Optional<String> comment, ExprAST expr)
+ : ExprStmtAST(make_object<ExprStmtASTObj>(std::move(source_paths), std::move(comment),
+ std::move(expr))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(ExprStmtAST, StmtAST, ExprStmtASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit ExprStmtAST(ObjectPtr<ExprStmtASTObj> ptr)
+ : StmtAST(ObjectPtr<StmtASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** AssertAST **************/
+
+/*!
+ * \brief Data object for an assert statement (e.g. `assert cond, msg`).
+ *
+ * Represents the Python construct `assert cond` or `assert cond, msg`
+ * in the text format AST.
+ *
+ * \code{.cpp}
+ * // Build: assert x > 0, "must be positive"
+ * AssertAST stmt(
+ * OperationAST(OperationASTObj::kGt, {IdAST("x"), LiteralAST::Int(0)}),
+ * LiteralAST::Str("must be positive")
+ * );
+ * \endcode
+ *
+ * \sa AssertAST
+ */
+struct AssertASTObj : public StmtASTObj {
+ /*! \brief The condition expression. */
+ ExprAST cond;
+ /*! \brief Optional assertion failure message. */
+ Optional<ExprAST> msg;
+ /// \cond Doxygen_Suppress
+ explicit AssertASTObj(ExprAST cond, Optional<ExprAST> msg = {})
+ : AssertASTObj(List<AccessPath>{}, Optional<String>{}, std::move(cond), std::move(msg)) {}
+ explicit AssertASTObj(List<AccessPath> source_paths, Optional<String> comment, ExprAST cond,
+ Optional<ExprAST> msg)
+ : StmtASTObj(std::move(source_paths), std::move(comment)),
+ cond(std::move(cond)),
+ msg(std::move(msg)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Assert", AssertASTObj, StmtASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for an assert statement. */
+struct AssertAST : public StmtAST {
+ /// \cond Doxygen_Suppress
+ explicit AssertAST(ExprAST cond, Optional<ExprAST> msg = {})
+ : AssertAST(List<AccessPath>{}, Optional<String>{}, std::move(cond), std::move(msg)) {}
+ explicit AssertAST(List<AccessPath> source_paths, Optional<String> comment, ExprAST cond,
+ Optional<ExprAST> msg)
+ : AssertAST(make_object<AssertASTObj>(std::move(source_paths), std::move(comment),
+ std::move(cond), std::move(msg))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(AssertAST, StmtAST, AssertASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit AssertAST(ObjectPtr<AssertASTObj> ptr)
+ : StmtAST(ObjectPtr<StmtASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** ReturnAST **************/
+
+/*!
+ * \brief Data object for a return statement.
+ *
+ * Represents the Python construct `return value` in the text format AST.
+ * The value is optional (a bare `return` has no value).
+ *
+ * \code{.cpp}
+ * // Build: return x + 1
+ * ReturnAST ret(OperationAST(OperationASTObj::kAdd, {IdAST("x"), LiteralAST::Int(1)}));
+ * // Build: return (bare return)
+ * ReturnAST bare_ret;
+ * \endcode
+ *
+ * \sa ReturnAST
+ */
+struct ReturnASTObj : public StmtASTObj {
+ /*! \brief Optional return value expression. */
+ Optional<ExprAST> value;
+ /// \cond Doxygen_Suppress
+ explicit ReturnASTObj(Optional<ExprAST> value = {})
+ : ReturnASTObj(List<AccessPath>{}, Optional<String>{}, std::move(value)) {}
+ explicit ReturnASTObj(List<AccessPath> source_paths, Optional<String> comment,
+ Optional<ExprAST> value)
+ : StmtASTObj(std::move(source_paths), std::move(comment)), value(std::move(value)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Return", ReturnASTObj, StmtASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for a return statement. */
+struct ReturnAST : public StmtAST {
+ /// \cond Doxygen_Suppress
+ explicit ReturnAST(Optional<ExprAST> value = {})
+ : ReturnAST(List<AccessPath>{}, Optional<String>{}, std::move(value)) {}
+ explicit ReturnAST(List<AccessPath> source_paths, Optional<String> comment,
+ Optional<ExprAST> value)
+ : ReturnAST(make_object<ReturnASTObj>(std::move(source_paths), std::move(comment),
+ std::move(value))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(ReturnAST, StmtAST, ReturnASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit ReturnAST(ObjectPtr<ReturnASTObj> ptr)
+ : StmtAST(ObjectPtr<StmtASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** FunctionAST **************/
+
+/*!
+ * \brief Data object for a function definition statement.
+ *
+ * Represents the Python construct `def name(args) -> return_type: body`,
+ * optionally preceded by decorator expressions. Function arguments are
+ * represented as AssignAST nodes where lhs is the parameter name and
+ * annotation is the optional type hint (rhs is unused for parameters).
+ *
+ * \code{.cpp}
+ * // Build:
+ * // @decorator
+ * // def add(x: int, y: int) -> int:
+ * // return x + y
+ * FunctionAST func(
+ * IdAST("add"),
+ * {AssignAST(IdAST("x"), NullOpt, IdAST("int")),
+ * AssignAST(IdAST("y"), NullOpt, IdAST("int"))},
+ * {IdAST("decorator")},
+ * IdAST("int"),
+ * {ReturnAST(OperationAST(OperationASTObj::kAdd, {IdAST("x"), IdAST("y")}))}
+ * );
+ * \endcode
+ *
+ * \sa FunctionAST
+ */
+struct FunctionASTObj : public StmtASTObj {
+ /*! \brief The function name (e.g. `add`). */
+ IdAST name;
+ /*! \brief The argument list as AssignAST nodes (lhs = param name, annotation = type hint). */
+ List<AssignAST> args;
+ /*! \brief Decorator expressions (e.g. `{IdAST("staticmethod")}`). */
+ List<ExprAST> decorators;
+ /*! \brief Optional return type annotation (e.g. `int` in `-> int`). */
+ Optional<ExprAST> return_type;
+ /*! \brief The function body statements. */
+ List<StmtAST> body;
+ /*! \brief Whether this is an `async def`. */
+ bool is_async;
+ /// \cond Doxygen_Suppress
+ explicit FunctionASTObj(IdAST name, List<AssignAST> args, List<ExprAST> decorators,
+ Optional<ExprAST> return_type, List<StmtAST> body, bool is_async = false)
+ : FunctionASTObj(List<AccessPath>{}, Optional<String>{}, std::move(name), std::move(args),
+ std::move(decorators), std::move(return_type), std::move(body), is_async) {}
+ explicit FunctionASTObj(List<AccessPath> source_paths, Optional<String> comment, IdAST name,
+ List<AssignAST> args, List<ExprAST> decorators,
+ Optional<ExprAST> return_type, List<StmtAST> body, bool is_async)
+ : StmtASTObj(std::move(source_paths), std::move(comment)),
+ name(std::move(name)),
+ args(std::move(args)),
+ decorators(std::move(decorators)),
+ return_type(std::move(return_type)),
+ body(std::move(body)),
+ is_async(is_async) {
+ for (const AssignAST& arg_doc : this->args) {
+ if (arg_doc->comment.has_value()) {
+ TVM_FFI_THROW(ValueError) << "Function arg cannot have comment attached to them";
+ }
+ }
+ }
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Function", FunctionASTObj, StmtASTObj);
+ /// \endcond
+};
+
+/*!
+ * \brief Reference wrapper for a function definition statement.
+ *
+ * \code{.cpp}
+ * // Build: def noop(): pass
+ * FunctionAST func(
+ * IdAST("noop"), {}, {}, NullOpt,
+ * {ExprStmtAST(IdAST("pass"))}
+ * );
+ * \endcode
+ *
+ * \sa FunctionASTObj
+ */
+struct FunctionAST : public StmtAST {
+ /// \cond Doxygen_Suppress
+ explicit FunctionAST(IdAST name, List<AssignAST> args, List<ExprAST> decorators,
+ Optional<ExprAST> return_type, List<StmtAST> body, bool is_async = false)
+ : FunctionAST(List<AccessPath>{}, Optional<String>{}, std::move(name), std::move(args),
+ std::move(decorators), std::move(return_type), std::move(body), is_async) {}
+ explicit FunctionAST(List<AccessPath> source_paths, Optional<String> comment, IdAST name,
+ List<AssignAST> args, List<ExprAST> decorators,
+ Optional<ExprAST> return_type, List<StmtAST> body, bool is_async)
+ : FunctionAST(make_object<FunctionASTObj>(
+ std::move(source_paths), std::move(comment), std::move(name), std::move(args),
+ std::move(decorators), std::move(return_type), std::move(body), is_async)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(FunctionAST, StmtAST, FunctionASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit FunctionAST(ObjectPtr<FunctionASTObj> ptr)
+ : StmtAST(ObjectPtr<StmtASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** ClassAST **************/
+
+/*!
+ * \brief Data object for a class definition statement.
+ *
+ * Represents the Python construct `class Name: body`, optionally
+ * preceded by decorator expressions.
+ *
+ * \code{.cpp}
+ * // Build:
+ * // @dataclass
+ * // class Point:
+ * // x: int
+ * // y: int
+ * ClassAST cls(
+ * IdAST("Point"),
+ * {IdAST("dataclass")},
+ * {AssignAST(IdAST("x"), NullOpt, IdAST("int")),
+ * AssignAST(IdAST("y"), NullOpt, IdAST("int"))}
+ * );
+ * \endcode
+ *
+ * \sa ClassAST
+ */
+struct ClassASTObj : public StmtASTObj {
+ /*! \brief The class name (e.g. `Point`). */
+ IdAST name;
+ /*! \brief Base class expressions (e.g. `{IdAST("Base")}`). */
+ List<ExprAST> bases;
+ /*! \brief Decorator expressions (e.g. `{IdAST("dataclass")}`). */
+ List<ExprAST> decorators;
+ /*! \brief The class body statements. */
+ List<StmtAST> body;
+ /*! \brief Keyword argument names (e.g. `"metaclass"`). */
+ List<String> kwargs_keys;
+ /*! \brief Keyword argument values (e.g. `IdAST("ABCMeta")`). */
+ List<ExprAST> kwargs_values;
+ /// \cond Doxygen_Suppress
+ explicit ClassASTObj(IdAST name, List<ExprAST> bases, List<ExprAST> decorators,
+ List<StmtAST> body, List<String> kwargs_keys = {},
+ List<ExprAST> kwargs_values = {})
+ : ClassASTObj(List<AccessPath>{}, Optional<String>{}, std::move(name), std::move(bases),
+ std::move(decorators), std::move(body), std::move(kwargs_keys),
+ std::move(kwargs_values)) {}
+ explicit ClassASTObj(List<AccessPath> source_paths, Optional<String> comment, IdAST name,
+ List<ExprAST> bases, List<ExprAST> decorators, List<StmtAST> body,
+ List<String> kwargs_keys, List<ExprAST> kwargs_values)
+ : StmtASTObj(std::move(source_paths), std::move(comment)),
+ name(std::move(name)),
+ bases(std::move(bases)),
+ decorators(std::move(decorators)),
+ body(std::move(body)),
+ kwargs_keys(std::move(kwargs_keys)),
+ kwargs_values(std::move(kwargs_values)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Class", ClassASTObj, StmtASTObj);
+ /// \endcond
+};
+
+/*!
+ * \brief Reference wrapper for a class definition statement.
+ *
+ * \code{.cpp}
+ * ClassAST cls(IdAST("Empty"), {}, {ExprStmtAST(IdAST("pass"))});
+ * // Renders as: class Empty:\n pass
+ * \endcode
+ *
+ * \sa ClassASTObj
+ */
+struct ClassAST : public StmtAST {
+ /// \cond Doxygen_Suppress
+ explicit ClassAST(IdAST name, List<ExprAST> bases, List<ExprAST> decorators, List<StmtAST> body,
+ List<String> kwargs_keys = {}, List<ExprAST> kwargs_values = {})
+ : ClassAST(List<AccessPath>{}, Optional<String>{}, std::move(name), std::move(bases),
+ std::move(decorators), std::move(body), std::move(kwargs_keys),
+ std::move(kwargs_values)) {}
+ explicit ClassAST(List<AccessPath> source_paths, Optional<String> comment, IdAST name,
+ List<ExprAST> bases, List<ExprAST> decorators, List<StmtAST> body,
+ List<String> kwargs_keys, List<ExprAST> kwargs_values)
+ : ClassAST(make_object<ClassASTObj>(std::move(source_paths), std::move(comment),
+ std::move(name), std::move(bases), std::move(decorators),
+ std::move(body), std::move(kwargs_keys),
+ std::move(kwargs_values))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(ClassAST, StmtAST, ClassASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit ClassAST(ObjectPtr<ClassASTObj> ptr) : StmtAST(ObjectPtr<StmtASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** CommentAST **************/
+
+/*!
+ * \brief Data object for a standalone comment line (e.g. `# comment text`).
+ *
+ * Represents a full-line Python comment in the text format AST. The
+ * comment text is stored in the inherited `comment` field from StmtASTObj.
+ *
+ * \code{.cpp}
+ * // Build: # This is a comment
+ * CommentAST cmt(String("This is a comment"));
+ * \endcode
+ *
+ * \sa CommentAST
+ */
+struct CommentASTObj : public StmtASTObj {
+ /// \cond Doxygen_Suppress
+ explicit CommentASTObj(Optional<String> comment)
+ : CommentASTObj(List<AccessPath>{}, std::move(comment)) {}
+ explicit CommentASTObj(List<AccessPath> source_paths, Optional<String> comment)
+ : StmtASTObj(std::move(source_paths), std::move(comment)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Comment", CommentASTObj, StmtASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for a standalone comment line. */
+struct CommentAST : public StmtAST {
+ /// \cond Doxygen_Suppress
+ explicit CommentAST(Optional<String> comment)
+ : CommentAST(List<AccessPath>{}, std::move(comment)) {}
+ explicit CommentAST(List<AccessPath> source_paths, Optional<String> comment)
+ : CommentAST(make_object<CommentASTObj>(std::move(source_paths), std::move(comment))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(CommentAST, StmtAST, CommentASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit CommentAST(ObjectPtr<CommentASTObj> ptr)
+ : StmtAST(ObjectPtr<StmtASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** DocStringAST **************/
+
+/*!
+ * \brief Data object for a docstring statement (triple-quoted string).
+ *
+ * Represents a Python docstring in the text format AST. The text is
+ * stored in the inherited `comment` field from StmtASTObj and rendered
+ * with triple quotes.
+ *
+ * \code{.cpp}
+ * // Build: """Compute the sum of two values."""
+ * DocStringAST doc(String("Compute the sum of two values."));
+ * \endcode
+ *
+ * \sa DocStringAST
+ */
+struct DocStringASTObj : public StmtASTObj {
+ /// \cond Doxygen_Suppress
+ explicit DocStringASTObj(Optional<String> comment)
+ : DocStringASTObj(List<AccessPath>{}, std::move(comment)) {}
+ explicit DocStringASTObj(List<AccessPath> source_paths, Optional<String> comment)
+ : StmtASTObj(std::move(source_paths), std::move(comment)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.DocString", DocStringASTObj, StmtASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for a docstring statement. */
+struct DocStringAST : public StmtAST {
+ /// \cond Doxygen_Suppress
+ explicit DocStringAST(Optional<String> comment)
+ : DocStringAST(List<AccessPath>{}, std::move(comment)) {}
+ explicit DocStringAST(List<AccessPath> source_paths, Optional<String> comment)
+ : DocStringAST(make_object<DocStringASTObj>(std::move(source_paths), std::move(comment))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(DocStringAST, StmtAST, DocStringASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit DocStringAST(ObjectPtr<DocStringASTObj> ptr)
+ : StmtAST(ObjectPtr<StmtASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** StarredExprAST **************/
+
+/*! \brief Data object for a starred expression (e.g. `*args`). */
+struct StarredExprASTObj : public ExprASTObj {
+ /*! \brief The expression being starred. */
+ ExprAST value;
+ /// \cond Doxygen_Suppress
+ explicit StarredExprASTObj(ExprAST value)
+ : StarredExprASTObj(List<AccessPath>{}, std::move(value)) {}
+ explicit StarredExprASTObj(List<AccessPath> source_paths, ExprAST value)
+ : ExprASTObj(std::move(source_paths)), value(std::move(value)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.StarredExpr", StarredExprASTObj, ExprASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for a starred expression. */
+struct StarredExprAST : public ExprAST {
+ /// \cond Doxygen_Suppress
+ explicit StarredExprAST(ExprAST value) : StarredExprAST(List<AccessPath>{}, std::move(value)) {}
+ explicit StarredExprAST(List<AccessPath> source_paths, ExprAST value)
+ : StarredExprAST(make_object<StarredExprASTObj>(std::move(source_paths), std::move(value))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(StarredExprAST, ExprAST, StarredExprASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit StarredExprAST(ObjectPtr<StarredExprASTObj> ptr)
+ : ExprAST(ObjectPtr<ExprASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** AwaitExprAST **************/
+
+/*! \brief Data object for an await expression (e.g. `await coro()`). */
+struct AwaitExprASTObj : public ExprASTObj {
+ /*! \brief The awaited expression. */
+ ExprAST value;
+ /// \cond Doxygen_Suppress
+ explicit AwaitExprASTObj(ExprAST value) : AwaitExprASTObj(List<AccessPath>{}, std::move(value)) {}
+ explicit AwaitExprASTObj(List<AccessPath> source_paths, ExprAST value)
+ : ExprASTObj(std::move(source_paths)), value(std::move(value)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Await", AwaitExprASTObj, ExprASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for an await expression. */
+struct AwaitExprAST : public ExprAST {
+ /// \cond Doxygen_Suppress
+ explicit AwaitExprAST(ExprAST value) : AwaitExprAST(List<AccessPath>{}, std::move(value)) {}
+ explicit AwaitExprAST(List<AccessPath> source_paths, ExprAST value)
+ : AwaitExprAST(make_object<AwaitExprASTObj>(std::move(source_paths), std::move(value))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(AwaitExprAST, ExprAST, AwaitExprASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit AwaitExprAST(ObjectPtr<AwaitExprASTObj> ptr)
+ : ExprAST(ObjectPtr<ExprASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** WalrusExprAST **************/
+
+/*! \brief Data object for a walrus/named expression (e.g. `x := value`). */
+struct WalrusExprASTObj : public ExprASTObj {
+ /*! \brief The assignment target. */
+ ExprAST target;
+ /*! \brief The assigned value. */
+ ExprAST value;
+ /// \cond Doxygen_Suppress
+ explicit WalrusExprASTObj(ExprAST target, ExprAST value)
+ : WalrusExprASTObj(List<AccessPath>{}, std::move(target), std::move(value)) {}
+ explicit WalrusExprASTObj(List<AccessPath> source_paths, ExprAST target, ExprAST value)
+ : ExprASTObj(std::move(source_paths)), target(std::move(target)), value(std::move(value)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.WalrusExpr", WalrusExprASTObj, ExprASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for a walrus/named expression. */
+struct WalrusExprAST : public ExprAST {
+ /// \cond Doxygen_Suppress
+ explicit WalrusExprAST(ExprAST target, ExprAST value)
+ : WalrusExprAST(List<AccessPath>{}, std::move(target), std::move(value)) {}
+ explicit WalrusExprAST(List<AccessPath> source_paths, ExprAST target, ExprAST value)
+ : WalrusExprAST(make_object<WalrusExprASTObj>(std::move(source_paths), std::move(target),
+ std::move(value))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(WalrusExprAST, ExprAST, WalrusExprASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit WalrusExprAST(ObjectPtr<WalrusExprASTObj> ptr)
+ : ExprAST(ObjectPtr<ExprASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** FStrAST **************/
+
+/*! \brief Data object for an f-string expression (e.g. `f"hello {x}"`). */
+struct FStrASTObj : public ExprASTObj {
+ /*! \brief Parts: LiteralAST(str) for text, FStrValueAST for interpolations. */
+ List<ExprAST> values;
+ /// \cond Doxygen_Suppress
+ explicit FStrASTObj(List<ExprAST> values) : FStrASTObj(List<AccessPath>{}, std::move(values)) {}
+ explicit FStrASTObj(List<AccessPath> source_paths, List<ExprAST> values)
+ : ExprASTObj(std::move(source_paths)), values(std::move(values)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.FStr", FStrASTObj, ExprASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for an f-string expression. */
+struct FStrAST : public ExprAST {
+ /// \cond Doxygen_Suppress
+ explicit FStrAST(List<ExprAST> values) : FStrAST(List<AccessPath>{}, std::move(values)) {}
+ explicit FStrAST(List<AccessPath> source_paths, List<ExprAST> values)
+ : FStrAST(make_object<FStrASTObj>(std::move(source_paths), std::move(values))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(FStrAST, ExprAST, FStrASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit FStrAST(ObjectPtr<FStrASTObj> ptr) : ExprAST(ObjectPtr<ExprASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** FStrValueAST **************/
+
+/*! \brief Data object for a formatted value inside an f-string (e.g. `{x!r:.2f}`). */
+struct FStrValueASTObj : public ExprASTObj {
+ /*! \brief The expression being formatted. */
+ ExprAST value;
+ /*! \brief Conversion flag: -1=none, 115='s', 114='r', 97='a'. */
+ int64_t conversion;
+ /*! \brief Optional format spec (itself an FStrAST or LiteralAST). */
+ Optional<ExprAST> format_spec;
+ /// \cond Doxygen_Suppress
+ explicit FStrValueASTObj(ExprAST value, int64_t conversion = -1,
+ Optional<ExprAST> format_spec = {})
+ : FStrValueASTObj(List<AccessPath>{}, std::move(value), conversion, std::move(format_spec)) {}
+ explicit FStrValueASTObj(List<AccessPath> source_paths, ExprAST value, int64_t conversion,
+ Optional<ExprAST> format_spec)
+ : ExprASTObj(std::move(source_paths)),
+ value(std::move(value)),
+ conversion(conversion),
+ format_spec(std::move(format_spec)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.FStrValue", FStrValueASTObj, ExprASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for a formatted value inside an f-string. */
+struct FStrValueAST : public ExprAST {
+ /// \cond Doxygen_Suppress
+ explicit FStrValueAST(ExprAST value, int64_t conversion = -1, Optional<ExprAST> format_spec = {})
+ : FStrValueAST(List<AccessPath>{}, std::move(value), conversion, std::move(format_spec)) {}
+ explicit FStrValueAST(List<AccessPath> source_paths, ExprAST value, int64_t conversion,
+ Optional<ExprAST> format_spec)
+ : FStrValueAST(make_object<FStrValueASTObj>(std::move(source_paths), std::move(value),
+ conversion, std::move(format_spec))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(FStrValueAST, ExprAST, FStrValueASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit FStrValueAST(ObjectPtr<FStrValueASTObj> ptr)
+ : ExprAST(ObjectPtr<ExprASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** ExceptHandlerAST **************/
+
+/*! \brief Data object for one except clause in a try statement. */
+struct ExceptHandlerASTObj : public NodeASTObj {
+ /*! \brief The exception type expression, or null for bare `except:`. */
+ Optional<ExprAST> type;
+ /*! \brief The `as` name, or null. */
+ Optional<String> name;
+ /*! \brief The handler body statements. */
+ List<StmtAST> body;
+ /// \cond Doxygen_Suppress
+ explicit ExceptHandlerASTObj(Optional<ExprAST> type, Optional<String> name, List<StmtAST> body)
+ : ExceptHandlerASTObj(List<AccessPath>{}, std::move(type), std::move(name), std::move(body)) {
+ }
+ explicit ExceptHandlerASTObj(List<AccessPath> source_paths, Optional<ExprAST> type,
+ Optional<String> name, List<StmtAST> body)
+ : NodeASTObj(std::move(source_paths)),
+ type(std::move(type)),
+ name(std::move(name)),
+ body(std::move(body)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.ExceptHandler", ExceptHandlerASTObj, NodeASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for an except handler clause. */
+struct ExceptHandlerAST : public NodeAST {
+ /// \cond Doxygen_Suppress
+ explicit ExceptHandlerAST(Optional<ExprAST> type, Optional<String> name, List<StmtAST> body)
+ : ExceptHandlerAST(List<AccessPath>{}, std::move(type), std::move(name), std::move(body)) {}
+ explicit ExceptHandlerAST(List<AccessPath> source_paths, Optional<ExprAST> type,
+ Optional<String> name, List<StmtAST> body)
+ : ExceptHandlerAST(make_object<ExceptHandlerASTObj>(std::move(source_paths), std::move(type),
+ std::move(name), std::move(body))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(ExceptHandlerAST, NodeAST, ExceptHandlerASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit ExceptHandlerAST(ObjectPtr<ExceptHandlerASTObj> ptr)
+ : NodeAST(ObjectPtr<NodeASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** TryAST **************/
+
+/*! \brief Data object for a try/except/else/finally statement. */
+struct TryASTObj : public StmtASTObj {
+ /*! \brief The try body statements. */
+ List<StmtAST> body;
+ /*! \brief The except handler clauses. */
+ List<ExceptHandlerAST> handlers;
+ /*! \brief The else-branch statements. */
+ List<StmtAST> orelse;
+ /*! \brief The finally-branch statements. */
+ List<StmtAST> finalbody;
+ /// \cond Doxygen_Suppress
+ explicit TryASTObj(List<StmtAST> body, List<ExceptHandlerAST> handlers, List<StmtAST> orelse = {},
+ List<StmtAST> finalbody = {})
+ : TryASTObj(List<AccessPath>{}, Optional<String>{}, std::move(body), std::move(handlers),
+ std::move(orelse), std::move(finalbody)) {}
+ explicit TryASTObj(List<AccessPath> source_paths, Optional<String> comment, List<StmtAST> body,
+ List<ExceptHandlerAST> handlers, List<StmtAST> orelse, List<StmtAST> finalbody)
+ : StmtASTObj(std::move(source_paths), std::move(comment)),
+ body(std::move(body)),
+ handlers(std::move(handlers)),
+ orelse(std::move(orelse)),
+ finalbody(std::move(finalbody)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Try", TryASTObj, StmtASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for a try/except/else/finally statement. */
+struct TryAST : public StmtAST {
+ /// \cond Doxygen_Suppress
+ explicit TryAST(List<StmtAST> body, List<ExceptHandlerAST> handlers, List<StmtAST> orelse = {},
+ List<StmtAST> finalbody = {})
+ : TryAST(List<AccessPath>{}, Optional<String>{}, std::move(body), std::move(handlers),
+ std::move(orelse), std::move(finalbody)) {}
+ explicit TryAST(List<AccessPath> source_paths, Optional<String> comment, List<StmtAST> body,
+ List<ExceptHandlerAST> handlers, List<StmtAST> orelse, List<StmtAST> finalbody)
+ : TryAST(make_object<TryASTObj>(std::move(source_paths), std::move(comment), std::move(body),
+ std::move(handlers), std::move(orelse),
+ std::move(finalbody))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(TryAST, StmtAST, TryASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit TryAST(ObjectPtr<TryASTObj> ptr) : StmtAST(ObjectPtr<StmtASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** MatchCaseAST **************/
+
+/*! \brief Data object for one case clause in a match statement. */
+struct MatchCaseASTObj : public NodeASTObj {
+ /*! \brief The match pattern expression. */
+ ExprAST pattern;
+ /*! \brief Optional guard expression. */
+ Optional<ExprAST> guard;
+ /*! \brief The case body statements. */
+ List<StmtAST> body;
+ /// \cond Doxygen_Suppress
+ explicit MatchCaseASTObj(ExprAST pattern, Optional<ExprAST> guard, List<StmtAST> body)
+ : MatchCaseASTObj(List<AccessPath>{}, std::move(pattern), std::move(guard), std::move(body)) {
+ }
+ explicit MatchCaseASTObj(List<AccessPath> source_paths, ExprAST pattern, Optional<ExprAST> guard,
+ List<StmtAST> body)
+ : NodeASTObj(std::move(source_paths)),
+ pattern(std::move(pattern)),
+ guard(std::move(guard)),
+ body(std::move(body)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.MatchCase", MatchCaseASTObj, NodeASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for a match case clause. */
+struct MatchCaseAST : public NodeAST {
+ /// \cond Doxygen_Suppress
+ explicit MatchCaseAST(ExprAST pattern, Optional<ExprAST> guard, List<StmtAST> body)
+ : MatchCaseAST(List<AccessPath>{}, std::move(pattern), std::move(guard), std::move(body)) {}
+ explicit MatchCaseAST(List<AccessPath> source_paths, ExprAST pattern, Optional<ExprAST> guard,
+ List<StmtAST> body)
+ : MatchCaseAST(make_object<MatchCaseASTObj>(std::move(source_paths), std::move(pattern),
+ std::move(guard), std::move(body))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(MatchCaseAST, NodeAST, MatchCaseASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit MatchCaseAST(ObjectPtr<MatchCaseASTObj> ptr)
+ : NodeAST(ObjectPtr<NodeASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** MatchAST **************/
+
+/*! \brief Data object for a match/case statement. */
+struct MatchASTObj : public StmtASTObj {
+ /*! \brief The subject expression being matched. */
+ ExprAST subject;
+ /*! \brief The list of case clauses. */
+ List<MatchCaseAST> cases;
+ /// \cond Doxygen_Suppress
+ explicit MatchASTObj(ExprAST subject, List<MatchCaseAST> cases)
+ : MatchASTObj(List<AccessPath>{}, Optional<String>{}, std::move(subject), std::move(cases)) {}
+ explicit MatchASTObj(List<AccessPath> source_paths, Optional<String> comment, ExprAST subject,
+ List<MatchCaseAST> cases)
+ : StmtASTObj(std::move(source_paths), std::move(comment)),
+ subject(std::move(subject)),
+ cases(std::move(cases)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.Match", MatchASTObj, StmtASTObj);
+ /// \endcond
+};
+
+/*! \brief Reference wrapper for a match/case statement. */
+struct MatchAST : public StmtAST {
+ /// \cond Doxygen_Suppress
+ explicit MatchAST(ExprAST subject, List<MatchCaseAST> cases)
+ : MatchAST(List<AccessPath>{}, Optional<String>{}, std::move(subject), std::move(cases)) {}
+ explicit MatchAST(List<AccessPath> source_paths, Optional<String> comment, ExprAST subject,
+ List<MatchCaseAST> cases)
+ : MatchAST(make_object<MatchASTObj>(std::move(source_paths), std::move(comment),
+ std::move(subject), std::move(cases))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(MatchAST, StmtAST, MatchASTObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit MatchAST(ObjectPtr<MatchASTObj> ptr) : StmtAST(ObjectPtr<StmtASTObj>(std::move(ptr))) {}
+ /// \endcond
+};
+
+/************** Free convenience functions for ExprAST **************/
+
+/*!
+ * \brief Create an attribute access expression: obj.name.
+ * \param obj The expression to access the attribute on.
+ * \param name The attribute name.
+ * \return An ExprAST representing the attribute access.
+ */
+inline ExprAST ExprAttr(ExprAST obj, String name) {
+ return AttrAST(List<AccessPath>{}, std::move(obj), std::move(name));
+}
+
+/*!
+ * \brief Create an index/subscript expression: obj[idx].
+ * \param obj The expression to index into.
+ * \param idx The list of index expressions.
+ * \return An ExprAST representing the subscript.
+ */
+inline ExprAST ExprIndex(ExprAST obj, List<ExprAST> idx) {
+ return IndexAST(List<AccessPath>{}, std::move(obj), std::move(idx));
+}
+
+/*!
+ * \brief Create a positional-only call expression: obj(args...).
+ * \param obj The callee expression.
+ * \param args The list of positional argument expressions.
+ * \return An ExprAST representing the call.
+ */
+inline ExprAST ExprCall(ExprAST obj, List<ExprAST> args) {
+ return CallAST(List<AccessPath>{}, std::move(obj), std::move(args), List<String>{},
+ List<ExprAST>{});
+}
+
+/*!
+ * \brief Create a call expression with keyword arguments: obj(args..., key=value...).
+ * \param obj The callee expression.
+ * \param args The list of positional argument expressions.
+ * \param kwargs_keys The keyword argument names (parallel to kwargs_values).
+ * \param kwargs_values The keyword argument value expressions.
+ * \return An ExprAST representing the call.
+ */
+inline ExprAST ExprCallKw(ExprAST obj, List<ExprAST> args, List<String> kwargs_keys,
+ List<ExprAST> kwargs_values) {
+ return CallAST(List<AccessPath>{}, std::move(obj), std::move(args), std::move(kwargs_keys),
+ std::move(kwargs_values));
+}
+
+/************** PrinterConfig **************/
+
+/*!
+ * \brief Data object for printer configuration options.
+ *
+ * Controls formatting of the Python-style text output, including
+ * indentation width, line numbering, context windowing, and underline
+ * highlighting of specific access paths.
+ *
+ * \code{.cpp}
+ * // Default config: 2-space indent, no line numbers, all context lines
+ * PrinterConfig cfg;
+ * String result = ToPython(some_ir_obj, cfg);
+ *
+ * // Custom config: 4-space indent, line numbers enabled, 3 context lines
+ * PrinterConfig cfg2(true, 4, 1, 3);
+ * String result2 = ToPython(some_ir_obj, cfg2);
+ *
+ * // With underline highlighting for a specific access path
+ * PrinterConfig cfg3(true, 2, 0, -1, false,
+ * {AccessPath::Root().Attr("args").ArrayItem(0)});
+ * String result3 = ToPython(some_ir_obj, cfg3);
+ * \endcode
+ *
+ * \sa PrinterConfig
+ */
+struct PrinterConfigObj : public Object {
+ /// \cond Doxygen_Suppress
+ static constexpr bool _type_mutable = true;
+ /// \endcond
+ /*!
+ * \brief When true, defines free variables automatically.
+ *
+ * If an IR object references a variable that has not been explicitly
+ * defined via VarDef, the printer will create a definition for it
+ * automatically. Example: `true`.
+ */
+ bool def_free_var = true;
+ /*!
+ * \brief Number of spaces per indentation level.
+ *
+ * Example: `2` for two-space indent, `4` for four-space indent.
+ */
+ int32_t indent_spaces = 2;
+ /*!
+ * \brief If > 0, prefix each output line with its line number.
+ *
+ * Example: `1` to enable line numbers, `0` to disable.
+ */
+ int8_t print_line_numbers = 0;
+ /*!
+ * \brief Number of context lines to show around underlined regions.
+ *
+ * When `path_to_underline` is non-empty, this controls how many
+ * surrounding lines are displayed. Example: `-1` for all lines,
+ * `3` for 3 context lines above and below the underlined region.
+ */
+ int32_t num_context_lines = -1;
+ /*!
+ * \brief Append a hex address suffix for duplicate variable names.
+ *
+ * When true and a name collision occurs during VarDef, the printer
+ * appends `_0x...` (the object's address) instead of a numeric suffix.
+ * Example: `true` appends `_0x...` to duplicate var names.
+ */
+ bool print_addr_on_dup_var = false;
+ /*!
+ * \brief Access paths to underline in the output.
+ *
+ * Each AccessPath identifies a position in the IR tree. Lines
+ * corresponding to these paths are rendered with underline markers.
+ * Example: `{AccessPath::Root().Attr("args").ArrayItem(0)}` to
+ * underline the first argument.
+ */
+ List<AccessPath> path_to_underline;
+ /// \cond Doxygen_Suppress
+ PrinterConfigObj() = default;
+ /*!
+ * \brief Construct a PrinterConfigObj with explicit settings.
+ * \param def_free_var Whether to define free variables automatically.
+ * \param indent_spaces Number of spaces per indentation level.
+ * \param print_line_numbers Whether to prefix lines with line numbers (> 0 to enable).
+ * \param num_context_lines Context lines around underlined regions (-1 = all).
+ * \param print_addr_on_dup_var Whether to append hex address for duplicate names.
+ * \param path_to_underline Access paths to underline in the output.
+ */
+ explicit PrinterConfigObj(bool def_free_var, int32_t indent_spaces, int8_t print_line_numbers,
+ int32_t num_context_lines, bool print_addr_on_dup_var,
+ List<AccessPath> path_to_underline)
+ : def_free_var(def_free_var),
+ indent_spaces(indent_spaces),
+ print_line_numbers(print_line_numbers),
+ num_context_lines(num_context_lines),
+ print_addr_on_dup_var(print_addr_on_dup_var),
+ path_to_underline(std::move(path_to_underline)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.PrinterConfig", PrinterConfigObj, Object);
+ /// \endcond
+};
+
+/*!
+ * \brief Reference wrapper for PrinterConfigObj.
+ *
+ * \code{.cpp}
+ * PrinterConfig cfg; // default: 2-space indent, no line numbers
+ * PrinterConfig cfg2(true, 4, 1, 3); // custom settings
+ * \endcode
+ *
+ * \sa PrinterConfigObj
+ */
+struct PrinterConfig : public ObjectRef {
+ /*!
+ * \brief Construct a PrinterConfig with the given settings.
+ *
+ * All parameters have sensible defaults; a default-constructed
+ * PrinterConfig uses 2-space indent with no line numbers.
+ *
+ * \param def_free_var Whether to define free variables automatically (default true).
+ * \param indent_spaces Number of spaces per indentation level (default 2).
+ * \param print_line_numbers Whether to prefix lines with line numbers (default 0 = off).
+ * \param num_context_lines Context lines around underlined regions (default -1 = all).
+ * \param print_addr_on_dup_var Whether to append hex address for duplicate names (default false).
+ * \param path_to_underline Access paths to underline in the output (default empty).
+ */
+ explicit PrinterConfig(bool def_free_var = true, int32_t indent_spaces = 2,
+ int8_t print_line_numbers = 0, int32_t num_context_lines = -1,
+ bool print_addr_on_dup_var = false,
+ List<AccessPath> path_to_underline = {})
+ : PrinterConfig(make_object<PrinterConfigObj>(def_free_var, indent_spaces, print_line_numbers,
+ num_context_lines, print_addr_on_dup_var,
+ std::move(path_to_underline))) {}
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(PrinterConfig, ObjectRef, PrinterConfigObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit PrinterConfig(ObjectPtr<PrinterConfigObj> ptr) : ObjectRef(std::move(ptr)) {}
+ /// \endcond
+};
+
+/************** DefaultFrame **************/
+
+/*!
+ * \brief Data object for the default frame used by IRPrinter.
+ *
+ * A frame accumulates a list of statement AST nodes. The IRPrinter
+ * maintains a stack of frames; statements emitted by print dispatch
+ * are appended to the frame on top of the stack. DefaultFrame is the
+ * simplest frame type, holding only a mutable statement list.
+ *
+ * \code{.cpp}
+ * IRPrinter printer(PrinterConfig());
+ * DefaultFrame frame;
+ * // Push the frame onto the printer's frame stack
+ * printer->FramePush(frame);
+ * // Dispatch IR nodes; statements are appended to frame->stmts
+ * Any doc = printer->operator()(Any(some_ir_obj), AccessPath::Root());
+ * // Pop the frame and clean up variables defined within it
+ * printer->FramePop();
+ * // frame->stmts now contains all emitted statements
+ * for (StmtAST stmt : frame->stmts) {
+ * // process each statement...
+ * }
+ * \endcode
+ *
+ * \sa DefaultFrame, IRPrinterObj
+ */
+struct DefaultFrameObj : public Object {
+ /// \cond Doxygen_Suppress
+ static constexpr bool _type_mutable = true;
+ /// \endcond
+ /*! \brief Statements accumulated in this frame. */
+ List<StmtAST> stmts;
+ /// \cond Doxygen_Suppress
+ DefaultFrameObj() = default;
+ explicit DefaultFrameObj(List<StmtAST> stmts) : stmts(std::move(stmts)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.DefaultFrame", DefaultFrameObj, Object);
+ /// \endcond
+};
+
+/*!
+ * \brief Reference wrapper for DefaultFrameObj.
+ *
+ * Constructible with an empty statement list (default) or with a
+ * pre-populated list. Used with IRPrinter::FramePush/FramePop.
+ *
+ * \code{.cpp}
+ * // Create an empty frame and use it with a printer
+ * IRPrinter printer(PrinterConfig());
+ * DefaultFrame frame;
+ * printer->FramePush(frame);
+ * // ... emit IR nodes via printer->operator() ...
+ * printer->FramePop();
+ *
+ * // Or pre-populate with existing statements
+ * DefaultFrame frame2(List<StmtAST>{some_stmt});
+ * \endcode
+ *
+ * \sa DefaultFrameObj
+ */
+struct DefaultFrame : public ObjectRef {
+ /// \cond Doxygen_Suppress
+ explicit DefaultFrame() : DefaultFrame(make_object<DefaultFrameObj>()) {}
+ explicit DefaultFrame(List<StmtAST> stmts)
+ : DefaultFrame(make_object<DefaultFrameObj>(std::move(stmts))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(DefaultFrame, ObjectRef, DefaultFrameObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit DefaultFrame(ObjectPtr<DefaultFrameObj> ptr) : ObjectRef(std::move(ptr)) {}
+ /// \endcond
+};
+
+/************** VarInfo **************/
+
+/*!
+ * \brief Data object holding metadata for a variable tracked by IRPrinter.
+ *
+ * Each variable binding in the printer maps an IR object to a VarInfo
+ * containing its display name (if any) and a creator function that
+ * produces the definition-site AST node when invoked.
+ *
+ * \code{.cpp}
+ * // Named variable: creator returns an IdAST with the given name
+ * VarInfo named_var(String("x"), Function::FromTyped([]() -> IdAST {
+ * return IdAST("x");
+ * }));
+ *
+ * // Unnamed variable: name is null, creator returns a custom expression
+ * VarInfo unnamed_var(Optional<String>{}, some_creator_fn);
+ * \endcode
+ *
+ * \sa VarInfo, IRPrinterObj::VarDef, IRPrinterObj::VarDefNoName
+ */
+struct VarInfoObj : public Object {
+ /*!
+ * \brief The display name, or null if unnamed.
+ *
+ * For named variables (created via VarDef), this holds the normalized,
+ * de-duplicated name string. Example: `String("my_var")` or
+ * `String("my_var_1")` if the name was de-duplicated.
+ * For unnamed variables (created via VarDefNoName), this is null.
+ */
+ Optional<String> name;
+ /*!
+ * \brief Callable that produces the definition-site AST.
+ *
+ * When invoked with no arguments, returns an ExprAST node representing
+ * how this variable should be rendered. For named variables, this
+ * typically returns `IdAST(name)`. For unnamed variables, the creator
+ * may return any ExprAST. Example: `Function::FromTyped([]() -> IdAST {
+ * return IdAST("x"); })`.
+ */
+ Function creator;
+ /// \cond Doxygen_Suppress
+ explicit VarInfoObj(Optional<String> name, Function creator)
+ : name(std::move(name)), creator(std::move(creator)) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.VarInfo", VarInfoObj, Object);
+ /// \endcond
+};
+
+/*!
+ * \brief Reference wrapper for variable metadata tracked by IRPrinter.
+ *
+ * \code{.cpp}
+ * VarInfo info(String("x"), Function::FromTyped([]() -> IdAST {
+ * return IdAST("x");
+ * }));
+ * // info->name is "x"
+ * // info->creator() returns IdAST("x")
+ * \endcode
+ *
+ * \sa VarInfoObj
+ */
+struct VarInfo : public ObjectRef {
+ /// \cond Doxygen_Suppress
+ explicit VarInfo(Optional<String> name, Function creator)
+ : VarInfo(make_object<VarInfoObj>(std::move(name), std::move(creator))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(VarInfo, ObjectRef, VarInfoObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit VarInfo(ObjectPtr<VarInfoObj> ptr) : ObjectRef(std::move(ptr)) {}
+ /// \endcond
+};
+
+/************** IRPrinter **************/
+
+/*!
+ * \brief Data object for the IR-to-document-AST printer.
+ *
+ * IRPrinterObj converts IR objects into the text format AST by dispatching
+ * through __ffi_text_print__ methods registered on each IR type. It maintains:
+ * - A variable table (obj2info / defined_names) for name deduplication.
+ * - A frame stack for scoped statement collection.
+ *
+ * The call operator `operator()(source, path)` dispatches printing for
+ * a single IR value, returning the resulting text format AST node.
+ *
+ * \code{.cpp}
+ * IRPrinter printer(PrinterConfig());
+ * DefaultFrame frame;
+ * printer->FramePush(frame);
+ * // Print an IR object into the frame:
+ * Any doc = printer->operator()(Any(some_ir_obj), AccessPath::Root());
+ * printer->FramePop();
+ * // Render the collected statements:
+ * StmtBlockAST block({}, NullOpt, frame->stmts);
+ * String code = details::PyAST2Str(block, printer->cfg);
+ * \endcode
+ *
+ * \sa IRPrinter, PrinterConfig, DefaultFrame
+ */
+struct IRPrinterObj : public Object {
+ /// \cond Doxygen_Suppress
+ static constexpr bool _type_mutable = true;
+ /// \endcond
+ /*! \brief The printer configuration. */
+ PrinterConfig cfg;
+ /*! \brief Mapping from IR objects to their variable metadata. */
+ Dict<Any, VarInfo> obj2info;
+ /*! \brief Set of variable names already in use. */
+ Dict<String, int64_t> defined_names;
+ /*! \brief Stack of active scoping frames. */
+ List<Any> frames;
+ /*! \brief Mapping from frames to variables defined in each. */
+ Dict<Any, Any> frame_vars;
+ /// \cond Doxygen_Suppress
+ explicit IRPrinterObj(PrinterConfig cfg) : cfg(std::move(cfg)) {}
+ explicit IRPrinterObj(PrinterConfig cfg, Dict<Any, VarInfo> obj2info,
+ Dict<String, int64_t> defined_names, List<Any> frames,
+ Dict<Any, Any> frame_vars)
+ : cfg(std::move(cfg)),
+ obj2info(std::move(obj2info)),
+ defined_names(std::move(defined_names)),
+ frames(std::move(frames)),
+ frame_vars(std::move(frame_vars)) {}
+ /// \endcond
+
+ /*!
+ * \brief Check whether an IR object already has a variable binding in this printer.
+ *
+ * \param obj The IR object to look up.
+ * \return True if \p obj has been registered via VarDef or VarDefNoName.
+ *
+ * \code{.cpp}
+ * IRPrinter printer(PrinterConfig());
+ * DefaultFrame frame;
+ * printer->FramePush(frame);
+ * printer->VarDef("x", some_obj, {});
+ * bool defined = printer->VarIsDefined(some_obj); // true
+ * bool unknown = printer->VarIsDefined(other_obj); // false
+ * printer->FramePop();
+ * \endcode
+ */
+ bool VarIsDefined(const ObjectRef& obj) { return obj2info.count(obj) > 0; }
+ /*!
+ * \brief Define a named variable for an IR object.
+ *
+ * Normalizes the name hint (replacing non-alphanumeric characters with
+ * underscores), de-duplicates against existing names, and registers the
+ * binding in the current frame.
+ *
+ * \param name_hint Suggested display name (may be normalized).
+ * \param obj The IR object to bind.
+ * \param frame Frame to register in, or null for the current top frame.
+ * \return An IdAST node referencing the defined variable.
+ *
+ * \code{.cpp}
+ * IRPrinter printer(PrinterConfig());
+ * DefaultFrame frame;
+ * printer->FramePush(frame);
+ * IdAST x = printer->VarDef("my_var", some_ir_obj, {});
+ * // x renders as "my_var"
+ * IdAST y = printer->VarDef("my_var", another_obj, {});
+ * // y renders as "my_var_1" (de-duplicated)
+ * printer->FramePop();
+ * \endcode
+ */
+ IdAST VarDef(String name_hint, const ObjectRef& obj, const Optional<ObjectRef>& frame);
+ /*!
+ * \brief Define a variable for an IR object using a custom creator function (no name).
+ *
+ * Unlike VarDef, this does not assign a display name. Instead, the
+ * provided creator function determines how the variable renders when
+ * looked up via VarGet.
+ *
+ * \param creator A nullary function returning an ExprAST for this variable.
+ * \param obj The IR object to bind.
+ * \param frame Frame to register in, or null for the current top frame.
+ *
+ * \code{.cpp}
+ * IRPrinter printer(PrinterConfig());
+ * DefaultFrame frame;
+ * printer->FramePush(frame);
+ * Function creator = Function::FromTyped([]() -> ExprAST {
+ * return AttrAST(IdAST("module"), "func_a", {});
+ * });
+ * printer->VarDefNoName(creator, some_ir_obj, {});
+ * // VarGet(some_ir_obj) now returns AttrAST(IdAST("module"), "func_a")
+ * printer->FramePop();
+ * \endcode
+ */
+ void VarDefNoName(const Function& creator, const ObjectRef& obj,
+ const Optional<ObjectRef>& frame);
+ /*!
+ * \brief Remove the variable binding for an IR object.
+ *
+ * Erases the object from the variable table and frees the name (if any)
+ * so it can be reused. Throws KeyError if the object has no binding.
+ *
+ * \param obj The IR object whose binding to remove.
+ *
+ * \code{.cpp}
+ * IRPrinter printer(PrinterConfig());
+ * DefaultFrame frame;
+ * printer->FramePush(frame);
+ * printer->VarDef("x", some_obj, {});
+ * printer->VarRemove(some_obj);
+ * // printer->VarIsDefined(some_obj) is now false
+ * printer->FramePop();
+ * \endcode
+ */
+ void VarRemove(const ObjectRef& obj);
+ /*!
+ * \brief Look up the expression AST for a previously defined variable.
+ *
+ * If the object has a binding, invokes its creator function and returns
+ * the resulting ExprAST. Returns null if no binding exists.
+ *
+ * \param obj The IR object to look up.
+ * \return The ExprAST for the variable, or null if not defined.
+ *
+ * \code{.cpp}
+ * IRPrinter printer(PrinterConfig());
+ * DefaultFrame frame;
+ * printer->FramePush(frame);
+ * printer->VarDef("x", some_obj, {});
+ * Optional<ExprAST> expr = printer->VarGet(some_obj);
+ * // expr.has_value() == true, renders as IdAST("x")
+ * Optional<ExprAST> missing = printer->VarGet(unknown_obj);
+ * // missing.has_value() == false
+ * printer->FramePop();
+ * \endcode
+ */
+ Optional<ExprAST> VarGet(const ObjectRef& obj);
+ /*!
+ * \brief Convert a source value to a text format AST node using registered
+ * __ffi_text_print__ dispatch.
+ *
+ * For primitive types (None, bool, int, float, string), returns the
+ * corresponding LiteralAST directly. For Object types, dispatches to
+ * the __ffi_text_print__ method registered for that type, which should return
+ * a NodeAST.
+ *
+ * \param source The IR value to print (may be a primitive or an Object).
+ * \param path The access path identifying \p source within the IR tree.
+ * \return A NodeAST (or LiteralAST) representing the printed value.
+ *
+ * \code{.cpp}
+ * IRPrinter printer(PrinterConfig());
+ * DefaultFrame frame;
+ * printer->FramePush(frame);
+ * // Print an IR object; dispatches to its __ffi_text_print__ method
+ * Any doc = printer->operator()(Any(some_ir_obj), AccessPath::Root());
+ * // Print a primitive value; returns a LiteralAST directly
+ * Any lit = printer->operator()(Any(42), AccessPath::Root().Attr("value"));
+ * printer->FramePop();
+ * \endcode
+ */
+ Any operator()(Any source, AccessPath path) const;
+
+ /*!
+ * \brief Apply this printer to each element of a list.
+ *
+ * Iterates over \p list, calling `operator()` on each element with
+ * an ArrayItem access path derived from \p p, and collects the results
+ * into a typed list.
+ *
+ * \tparam T The element type for the output list (e.g., ExprAST).
+ * \param list The list of IR values to print.
+ * \param p The parent access path; each element gets `p->ArrayItem(i)`.
+ * \return A list of printed AST nodes, one per input element.
+ *
+ * \code{.cpp}
+ * IRPrinter printer(PrinterConfig());
+ * DefaultFrame frame;
+ * printer->FramePush(frame);
+ * List<Any> ir_args = {Any(arg0), Any(arg1), Any(arg2)};
+ * AccessPath args_path = AccessPath::Root().Attr("args");
+ * List<ExprAST> printed = printer->ApplyToList<ExprAST>(ir_args, args_path);
+ * // printed[0] was printed with path Root().Attr("args").ArrayItem(0)
+ * // printed[1] was printed with path Root().Attr("args").ArrayItem(1)
+ * printer->FramePop();
+ * \endcode
+ */
+ template <typename T>
+ List<T> ApplyToList(const List<Any>& list, const AccessPath& p) const {
+ int64_t n = static_cast<int64_t>(list.size());
+ List<T> result;
+ result.reserve(n);
+ for (int64_t i = 0; i < n; ++i) {
+ result.push_back(this->operator()(list[i], p->ArrayItem(i)));
+ }
+ return result;
+ }
+
+ /*!
+ * \brief Push a scoping frame onto the frame stack.
+ *
+ * Variables defined after this call (until the matching FramePop) are
+ * associated with \p frame. The frame becomes the new top of the stack.
+ *
+ * \param frame The frame to push (typically a DefaultFrame).
+ *
+ * \code{.cpp}
+ * IRPrinter printer(PrinterConfig());
+ * DefaultFrame frame;
+ * printer->FramePush(frame);
+ * // ... define variables and emit statements ...
+ * printer->FramePop();
+ * \endcode
+ */
+ void FramePush(const ObjectRef& frame);
+ /*!
+ * \brief Pop the top frame and remove all variables defined in it.
+ *
+ * Removes every variable binding that was registered to the top frame
+ * (freeing their names), then removes the frame from the stack. Must
+ * be paired with a preceding FramePush call.
+ *
+ * \code{.cpp}
+ * IRPrinter printer(PrinterConfig());
+ * DefaultFrame outer;
+ * printer->FramePush(outer);
+ * printer->VarDef("x", obj_x, {});
+ * {
+ * DefaultFrame inner;
+ * printer->FramePush(inner);
+ * printer->VarDef("y", obj_y, {});
+ * printer->FramePop(); // removes "y", inner frame popped
+ * }
+ * // "x" is still defined; "y" is gone
+ * printer->FramePop(); // removes "x", outer frame popped
+ * \endcode
+ */
+ void FramePop();
+
+ /*! \brief Print an Array as a ListAST. */
+ template <typename T>
+ ListAST PrintList(const Array<T>& arr, const AccessPath& path) const {
+ List<ExprAST> elts;
+ for (int i = 0; i < static_cast<int>(arr.size()); ++i) {
+ elts.push_back(this->operator()(arr[i], path->ArrayItem(i)).template cast<ExprAST>());
+ }
+ return ListAST({}, std::move(elts));
+ }
+
+ /*! \brief Print an Array as a TupleAST. */
+ template <typename T>
+ TupleAST PrintTuple(const Array<T>& arr, const AccessPath& path) const {
+ List<ExprAST> elts;
+ for (int i = 0; i < static_cast<int>(arr.size()); ++i) {
+ elts.push_back(this->operator()(arr[i], path->ArrayItem(i)).template cast<ExprAST>());
+ }
+ return TupleAST({}, std::move(elts));
+ }
+
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ffi.pyast.IRPrinter", IRPrinterObj, Object);
+ /// \endcond
+
+ private:
+ /*! \brief Internal: register a VarInfo for \p obj in the given frame. */
+ void VarDefInternal(VarInfo var_info, const ObjectRef& obj, const Optional<ObjectRef>& frame);
+};
+
+/*!
+ * \brief Reference wrapper for IRPrinterObj.
+ *
+ * Constructed from a PrinterConfig. Use the underlying object's methods
+ * (via operator->) to define variables, push/pop frames, and dispatch
+ * printing.
+ *
+ * \code{.cpp}
+ * IRPrinter printer(PrinterConfig());
+ * // Convenient one-shot printing is available via the ToPython free function:
+ * String code = ToPython(some_ir_obj, printer->cfg);
+ * \endcode
+ *
+ * \sa IRPrinterObj
+ */
+struct IRPrinter : public ObjectRef {
+ /// \cond Doxygen_Suppress
+ explicit IRPrinter(PrinterConfig cfg) : IRPrinter(make_object<IRPrinterObj>(std::move(cfg))) {}
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(IRPrinter, ObjectRef, IRPrinterObj);
+ /// \endcond
+ /// \cond Doxygen_Suppress
+ explicit IRPrinter(ObjectPtr<IRPrinterObj> ptr) : ObjectRef(std::move(ptr)) {}
+ /// \endcond
+};
+
+namespace details {
+/*! \brief Internal dispatch for __ffi_text_print__. Used by IRPrinterObj::operator(). */
+TVM_FFI_EXTRA_CXX_API NodeAST IRPrintDispatch(AnyView obj, AnyView printer, AnyView path);
+/*! \brief Convert a text format AST node to a Python-style source string. */
+TVM_FFI_EXTRA_CXX_API String PyAST2Str(NodeAST node, PrinterConfig cfg);
+} // namespace details
+
+/************** Inline: NodeASTObj::ToPython **************/
+
+inline String NodeASTObj::ToPython(const PrinterConfig& cfg) const {
+ return details::PyAST2Str(GetRef<NodeAST>(this), cfg);
+}
+
+/************** Inline: IRPrinterObj methods **************/
+
+inline IdAST IRPrinterObj::VarDef(String name_hint, const ObjectRef& obj,
+ const Optional<ObjectRef>& frame) {
+ if (auto it = obj2info.find(obj); it != obj2info.end()) {
+ Optional<String> name = (*it).second->name;
+ return IdAST(name.value());
+ }
+ bool needs_normalize = std::any_of(name_hint.data(), name_hint.data() + name_hint.size(),
+ [](char c) { return c != '_' && !std::isalnum(c); });
+ if (needs_normalize) {
+ std::string buf(name_hint.data(), name_hint.size());
+ for (char& c : buf) {
+ if (c != '_' && !std::isalnum(c)) {
+ c = '_';
+ }
+ }
+ name_hint = String(buf);
+ }
+ std::string name_hint_str(name_hint.data(), name_hint.size());
+ String name(name_hint_str);
+ if (defined_names.count(name)) {
+ if (this->cfg->print_addr_on_dup_var) {
+ std::ostringstream os;
+ os << name_hint_str << "_0x" << std::setfill('0') << std::setw(12) << std::hex
+ << reinterpret_cast<uintptr_t>(obj.get());
+ name = String(os.str());
+ } else {
+ for (int i = 1; defined_names.count(name) > 0; ++i) {
+ name = String(name_hint_str + '_' + std::to_string(i));
+ }
+ }
+ }
+ defined_names.Set(name, 1);
+ String captured_name = name;
+ this->VarDefInternal(VarInfo(name, Function::FromTyped([captured_name]() -> IdAST {
+ return IdAST(captured_name);
+ })),
+ obj, frame);
+ return IdAST(name);
+}
+
+inline void IRPrinterObj::VarDefNoName(const Function& creator, const ObjectRef& obj,
+ const Optional<ObjectRef>& frame) {
+ if (obj2info.count(obj) > 0) {
+ TVM_FFI_THROW(KeyError) << "Variable already defined: " << obj.get()->GetTypeKey();
+ }
+ this->VarDefInternal(VarInfo(Optional<String>{}, creator), obj, frame);
+}
+
+inline void IRPrinterObj::VarDefInternal(VarInfo var_info, // NOLINT(*-value-param)
+ const ObjectRef& obj, const Optional<ObjectRef>& _frame) {
+ ObjectRef frame_ref = _frame.has_value() ? _frame.value() : this->frames.back().cast<ObjectRef>();
+ obj2info.Set(obj, var_info);
+ auto it = frame_vars.find(frame_ref);
+ if (it == frame_vars.end()) {
+ TVM_FFI_THROW(KeyError) << "Frame is not pushed to IRPrinter: "
+ << frame_ref.get()->GetTypeKey();
+ } else {
+ frame_vars[frame_ref].cast<List<Any>>().push_back(obj);
+ }
+}
+
+inline void IRPrinterObj::VarRemove(const ObjectRef& obj) {
+ auto it = obj2info.find(obj);
+ if (it == obj2info.end()) {
+ TVM_FFI_THROW(KeyError) << "No such object: " << obj.get()->GetTypeKey();
+ }
+ Optional<String> name = (*it).second->name;
+ if (name.has_value()) {
+ defined_names.erase(name.value());
+ }
+ obj2info.erase(obj);
+}
+
+inline Optional<ExprAST> IRPrinterObj::VarGet(const ObjectRef& obj) {
+ auto it = obj2info.find(obj);
+ if (it == obj2info.end()) {
+ return Optional<ExprAST>{};
+ }
+ return (*it).second->creator().cast<ExprAST>();
+}
+
+inline Any IRPrinterObj::operator()(Any source, AccessPath path) const { // NOLINT(*-value-param)
+ int32_t ti = source.type_index();
+ if (ti == TypeIndex::kTVMFFINone) {
+ return LiteralAST::Null({path});
+ }
+ if (ti == TypeIndex::kTVMFFIBool) {
+ return LiteralAST::Bool(source.cast<bool>(), {path});
+ }
+ if (ti == TypeIndex::kTVMFFIInt) {
+ return LiteralAST::Int(source.cast<int64_t>(), {path});
+ }
+ if (ti == TypeIndex::kTVMFFIStr || ti == TypeIndex::kTVMFFISmallStr ||
+ ti == TypeIndex::kTVMFFIRawStr) {
+ return LiteralAST::Str(source.cast<String>(), {path});
+ }
+ if (ti == TypeIndex::kTVMFFIFloat) {
+ return LiteralAST::Float(source.cast<double>(), {path});
+ }
+ if (ti == TypeIndex::kTVMFFIDataType) {
+ DLDataType dtype = source.cast<DLDataType>();
+ std::string dtype_str =
+ (dtype.bits == 0 && dtype.lanes == 0) ? "void" : DLDataTypeToString(dtype);
+ return LiteralAST::Str(String(dtype_str), {path});
+ }
+ if (ti < TypeIndex::kTVMFFIStaticObjectBegin) {
+ TVM_FFI_THROW(ValueError) << "Unsupported type index: " << ti;
+ }
+ NodeAST ret = details::IRPrintDispatch(source, this, path);
+ ret->source_paths.push_back(path);
+ return ret;
+}
+
+inline void IRPrinterObj::FramePush(const ObjectRef& frame) {
+ frames.push_back(frame);
+ frame_vars.Set(frame, List<Any>());
+}
+
+inline void IRPrinterObj::FramePop() {
+ ObjectRef frame = frames.back().cast<ObjectRef>();
+ for (Any var_any : frame_vars[frame].cast<List<Any>>()) {
+ this->VarRemove(var_any.cast<ObjectRef>());
+ }
+ frame_vars.erase(frame);
+ frames.pop_back();
+}
+
+} // namespace pyast
+} // namespace ffi
+} // namespace tvm
+
+#endif // TVM_FFI_EXTRA_PYAST_H_
diff --git a/include/tvm/ffi/object.h b/include/tvm/ffi/object.h
index c95f2bd..9b22636 100644
--- a/include/tvm/ffi/object.h
+++ b/include/tvm/ffi/object.h
@@ -1178,7 +1178,7 @@ struct ObjectUnsafe {
}
TVM_FFI_INLINE static void DecRefObjectHandle(TVMFFIObjectHandle handle) {
- reinterpret_cast<Object*>(handle)->DecRef();
+ if (handle) reinterpret_cast<Object*>(handle)->DecRef();
}
TVM_FFI_INLINE static void IncRefObjectHandle(TVMFFIObjectHandle handle) {
diff --git a/include/tvm/ffi/reflection/creator.h b/include/tvm/ffi/reflection/creator.h
index 977e6de..5ff361d 100644
--- a/include/tvm/ffi/reflection/creator.h
+++ b/include/tvm/ffi/reflection/creator.h
@@ -63,6 +63,7 @@ inline ObjectPtr<Object> CreateEmptyObject(const TVMFFITypeInfo* type_info) {
TVM_FFI_THROW(RuntimeError) << "Type `" << TypeIndexToTypeKey(type_info->type_index)
<< "` does not support reflection creation"
<< " (no native creator or __ffi_new__ type attr)";
+ TVM_FFI_UNREACHABLE();
}
/*!
diff --git a/include/tvm/ffi/reflection/init.h b/include/tvm/ffi/reflection/init.h
index 369be7c..b3e754c 100644
--- a/include/tvm/ffi/reflection/init.h
+++ b/include/tvm/ffi/reflection/init.h
@@ -60,6 +60,7 @@ TObjectRef FFIConvertFromAnyViewToObjectRef(AnyView input) {
}
TVM_FFI_THROW(TypeError) << "Cannot cast from `" << TypeIndexToTypeKey(input_pod.type_index)
<< "` to `" << TypeTraits<TObjectRef>::TypeStr() << "`";
+ TVM_FFI_UNREACHABLE();
}
/*!
diff --git a/include/tvm/ffi/reflection/registry.h b/include/tvm/ffi/reflection/registry.h
index 92379a1..00de1fc 100644
--- a/include/tvm/ffi/reflection/registry.h
+++ b/include/tvm/ffi/reflection/registry.h
@@ -799,6 +799,24 @@ class ObjectDef : public ReflectionDefBase {
return *this;
}
+ /*!
+ * \brief Register an IR semantic trait (__ffi_ir_traits__) for this type.
+ * \tparam TraitType The trait object type (e.g. ir::traits::BinOpObj).
+ * \tparam Args Constructor argument types.
+ * \param args Arguments forwarded to make_object<TraitType>(...).
+ * \return Reference to this ObjectDef for chaining.
+ */
+ template <typename TraitType, typename... Args>
+ ObjectDef& def_ir_traits(Args&&... args) {
+ static const char kName[] = "__ffi_ir_traits__";
+ TVMFFIByteArray name_arr = {kName, sizeof(kName) - 1};
+ ObjectRef trait(make_object<TraitType>(std::forward<Args>(args)...));
+ Any val(std::move(trait));
+ TVMFFIAny* raw = reinterpret_cast<TVMFFIAny*>(&val);
+ TVM_FFI_CHECK_SAFE_CALL(TVMFFITypeRegisterAttr(type_index_, &name_arr, raw));
+ return *this;
+ }
+
/*!
* \brief Define a static method.
*
diff --git a/include/tvm/ffi/string.h b/include/tvm/ffi/string.h
index 3a3ffcd..3875ef5 100644
--- a/include/tvm/ffi/string.h
+++ b/include/tvm/ffi/string.h
@@ -30,12 +30,15 @@
#include <tvm/ffi/object.h>
#include <tvm/ffi/type_traits.h>
+#include <cctype>
#include <cstddef>
#include <cstring>
+#include <iomanip>
#include <sstream>
#include <string>
#include <string_view>
#include <utility>
+#include <vector>
// Note: We place string in tvm/ffi instead of tvm/ffi/container
// because string itself needs special handling and is an inherent
@@ -736,6 +739,26 @@ class String {
return std::string{data(), size()};
}
+ /*!
+ * \brief Split the string by a delimiter character.
+ * \param delim The delimiter character.
+ * \return A vector of string_views pointing into this string's data.
+ * \note The returned string_views are only valid while this String is alive.
+ */
+ std::vector<std::string_view> Split(char delim) const {
+ std::vector<std::string_view> ret;
+ const char* start = data();
+ const char* end = start + size();
+ for (const char* p = start; p < end; ++p) {
+ if (*p == delim) {
+ ret.emplace_back(start, static_cast<size_t>(p - start));
+ start = p + 1;
+ }
+ }
+ ret.emplace_back(start, static_cast<size_t>(end - start));
+ return ret;
+ }
+
private:
template <typename, typename>
friend struct TypeTraits;
@@ -847,6 +870,99 @@ inline String EscapeString(const String& value) {
return String(oss.str());
}
+/*!
+ * \brief Write a Python-style escaped string representation to an output stream.
+ *
+ * Handles ANSI escape sequences, UTF-8 multibyte characters, and standard
+ * C escape sequences (\\n, \\t, \\r, \\\\, \\"). The output is double-quoted.
+ *
+ * \param oss The output stream to write to.
+ * \param value The input string to escape.
+ */
+inline void PrintEscapeString(std::ostream& oss, const String& value) {
+ const char* data = value.data();
+ const size_t length = value.size();
+ oss << '"';
+ for (size_t i = 0; i < length;) {
+ unsigned char c = static_cast<unsigned char>(data[i]);
+ unsigned char d = (i + 1 < length) ? static_cast<unsigned char>(data[i + 1]) : 0;
+ // Detect ANSI escape sequences
+ if (c == '\x1b' && d == '[') {
+ size_t j = i + 2;
+ while (j < length && (std::isdigit(data[j]) || data[j] == ';')) {
+ ++j;
+ }
+ if (j < length && (data[j] == 'm' || data[j] == 'K')) {
+ oss << "\\u001b[";
+ for (i += 2; i <= j; ++i) {
+ oss << data[i];
+ }
+ continue;
+ }
+ }
+ // Handle ASCII C escape sequences
+ switch (c) {
+ case '\n':
+ oss << "\\n";
+ ++i;
+ continue;
+ case '\t':
+ oss << "\\t";
+ ++i;
+ continue;
+ case '\r':
+ oss << "\\r";
+ ++i;
+ continue;
+ case '\\':
+ oss << "\\\\";
+ ++i;
+ continue;
+ case '\"':
+ oss << "\\\"";
+ ++i;
+ continue;
+ default:
+ break;
+ }
+ // Handle ASCII
+ if ((c & 0x80) == 0) {
+ if (c < 0x20 || c == 0x7f) {
+ // Escape control characters as \xNN
+ char buf[5];
+ snprintf(buf, sizeof(buf), "\\x%02x", static_cast<unsigned>(c));
+ oss << buf;
+ } else {
+ oss << static_cast<char>(c);
+ }
+ ++i;
+ continue;
+ }
+ if ((c & 0xE0) == 0xC0 && i + 1 < length) {
+ int32_t codepoint = ((c & 0x1F) << 6) | (d & 0x3F);
+ oss << "\\u" << std::hex << std::setw(4) << std::setfill('0') << codepoint;
+ i += 2;
+ } else if ((c & 0xF0) == 0xE0 && i + 2 < length) {
+ unsigned char e = static_cast<unsigned char>(data[i + 2]);
+ int32_t codepoint = ((c & 0x0F) << 12) | ((d & 0x3F) << 6) | (e & 0x3F);
+ oss << "\\u" << std::hex << std::setw(4) << std::setfill('0') << codepoint;
+ i += 3;
+ } else if ((c & 0xF8) == 0xF0 && i + 3 < length) {
+ unsigned char e = static_cast<unsigned char>(data[i + 2]);
+ unsigned char f = static_cast<unsigned char>(data[i + 3]);
+ int32_t codepoint = ((c & 0x07) << 18) | ((d & 0x3F) << 12) | ((e & 0x3F) << 6) | (f & 0x3F);
+ oss << "\\U" << std::hex << std::setw(8) << std::setfill('0') << codepoint;
+ i += 4;
+ } else {
+ oss << "\\x" << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(c);
+ ++i;
+ }
+ oss.unsetf(std::ios::adjustfield | std::ios::basefield | std::ios::floatfield);
+ oss.fill(' ');
+ }
+ oss << '"';
+}
+
/*! \brief Convert TVMFFIByteArray to std::string_view */
TVM_FFI_INLINE std::string_view ToStringView(TVMFFIByteArray str) {
return std::string_view(str.data, str.size);
diff --git a/include/tvm/ffi/type_traits.h b/include/tvm/ffi/type_traits.h
index e832559..ad00bf8 100644
--- a/include/tvm/ffi/type_traits.h
+++ b/include/tvm/ffi/type_traits.h
@@ -290,7 +290,12 @@ struct TypeTraits<Int, std::enable_if_t<std::is_integral_v<Int>>> : public TypeT
}
result->type_index = TypeIndex::kTVMFFIInt;
result->zero_padding = 0;
- result->v_int64 = static_cast<int64_t>(src);
+ // Cast through unsigned char for signed char to avoid bugprone-signed-char-misuse
+ if constexpr (std::is_same_v<std::remove_cv_t<Int>, signed char>) {
+ result->v_int64 = static_cast<int64_t>(static_cast<unsigned char>(src));
+ } else {
+ result->v_int64 = static_cast<int64_t>(src);
+ }
}
TVM_FFI_INLINE static void MoveToAny(Int src, TVMFFIAny* result) { CopyToAnyView(src, result); }
diff --git a/pyproject.toml b/pyproject.toml
index 5e69c6c..a2d4531 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -60,7 +60,7 @@ dev = [
"ipdb",
"ipython",
"cython>=3.0",
- "cmake!=4.3.1",
+ "cmake",
"scikit-build-core",
"tomli",
"setuptools-scm",
@@ -260,7 +260,7 @@ extra-paths = ["python", "examples", "tests/python"]
[tool.ty.src]
include = ["python/tvm_ffi/**", "examples/**", "tests/python/**"]
-exclude = [".venv/**", "build/**", "dist/**"]
+exclude = [".venv/**", "build/**", "dist/**", "**/testdata/**"]
[tool.ty.rules]
unused-ignore-comment = "ignore"
@@ -284,6 +284,9 @@ allowed-unresolved-imports = [
"torch_c_dlpack_ext",
]
+[tool.uv]
+exclude-newer = "30 days"
+
[tool.uv.dependency-groups]
docs = { requires-python = ">=3.13" }
diff --git a/python/tvm_ffi/_ffi_api.py b/python/tvm_ffi/_ffi_api.py
index 1da4c69..a7e47d1 100644
--- a/python/tvm_ffi/_ffi_api.py
+++ b/python/tvm_ffi/_ffi_api.py
@@ -24,6 +24,7 @@ from .registry import init_ffi_api as _FFI_INIT_FUNC
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Mapping, MutableMapping, MutableSequence, Sequence
+ from ctypes import c_void_p
from tvm_ffi import Module, Object, StructuralKey as _StructuralKey
from tvm_ffi.access_path import AccessPath
from typing import Any, Callable
@@ -52,8 +53,10 @@ if TYPE_CHECKING:
def DictSize(_0: MutableMapping[Any, Any], /) -> int: ...
def FromJSONGraph(_0: Any, /) -> Any: ...
def FromJSONGraphString(_0: str, /) -> Any: ...
+ def FunctionFromExternC(_0: c_void_p, _1: c_void_p, _2: c_void_p, /) -> Callable[..., Any]: ...
def FunctionListGlobalNamesFunctor() -> Callable[..., Any]: ...
def FunctionRemoveGlobal(_0: str, /) -> bool: ...
+ def GetFieldGetter(_0: int, /) -> int: ...
def GetFirstStructuralMismatch(_0: Any, _1: Any, _2: bool, _3: bool, /) -> tuple[AccessPath, AccessPath] | None: ...
def GetGlobalFuncMetadata(_0: str, /) -> str: ...
def GetInvalidObject() -> Object: ...
@@ -72,6 +75,8 @@ if TYPE_CHECKING:
def ListReverse(_0: MutableSequence[Any], /) -> None: ...
def ListSetItem(_0: MutableSequence[Any], _1: int, _2: Any, /) -> None: ...
def ListSize(_0: MutableSequence[Any], /) -> int: ...
+ def MakeFFINew(_0: int, _1: int, /) -> None: ...
+ def MakeFieldSetter(_0: int, _1: int, _2: int, /) -> Callable[..., Any]: ...
def MakeInit(_0: int, /) -> Callable[..., Any]: ...
def MakeObjectFromPackedArgs(*args: Any) -> Any: ...
def Map(*args: Any) -> Any: ...
@@ -100,6 +105,7 @@ if TYPE_CHECKING:
def RecursiveHash(_0: Any, /) -> int: ...
def RecursiveLe(_0: Any, _1: Any, /) -> bool: ...
def RecursiveLt(_0: Any, _1: Any, /) -> bool: ...
+ def RegisterAutoInit(_0: int, /) -> None: ...
def ReprPrint(_0: Any, /) -> str: ...
def Shape(*args: Any) -> Any: ...
def String(_0: str, /) -> str: ...
@@ -133,8 +139,10 @@ __all__ = [
"DictSize",
"FromJSONGraph",
"FromJSONGraphString",
+ "FunctionFromExternC",
"FunctionListGlobalNamesFunctor",
"FunctionRemoveGlobal",
+ "GetFieldGetter",
"GetFirstStructuralMismatch",
"GetGlobalFuncMetadata",
"GetInvalidObject",
@@ -153,6 +161,8 @@ __all__ = [
"ListReverse",
"ListSetItem",
"ListSize",
+ "MakeFFINew",
+ "MakeFieldSetter",
"MakeInit",
"MakeObjectFromPackedArgs",
"Map",
@@ -181,6 +191,7 @@ __all__ = [
"RecursiveHash",
"RecursiveLe",
"RecursiveLt",
+ "RegisterAutoInit",
"ReprPrint",
"Shape",
"String",
diff --git a/python/tvm_ffi/_pyast_colored_print.py b/python/tvm_ffi/_pyast_colored_print.py
new file mode 100644
index 0000000..b5c0670
--- /dev/null
+++ b/python/tvm_ffi/_pyast_colored_print.py
@@ -0,0 +1,160 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Syntax-highlighted printing for Python-style AST output.
+
+Uses Pygments when available. Falls back to plain ``print()`` with a one-time
+warning suggesting ``pip install pygments``.
+"""
+
+from __future__ import annotations
+
+import sys
+import typing
+import warnings
+
+if typing.TYPE_CHECKING:
+ from pygments.style import Style
+
+_PYGMENTS_WARNED = False
+
+
+def cprint(text: str, style: str | None = None) -> None:
+ """Print Python source with Pygments syntax highlighting.
+
+ Parameters
+ ----------
+ text
+ The source code string to print.
+ style
+ Pygments style name or one of the built-in aliases ``"light"``,
+ ``"dark"``, ``"ansi"``. When ``None``, ``"light"`` is used inside
+ Jupyter notebooks and ``"ansi"`` in terminals.
+
+ Notes
+ -----
+ When the optional ``pygments`` package is not installed, plain text is
+ printed with a one-time warning suggesting installation. Additional
+ Pygments styles are listed at https://pygments.org/styles/.
+
+ """
+ is_notebook = "ipykernel" in sys.modules
+ pygment_style = _resolve_style(style, is_notebook)
+ if pygment_style is None:
+ print(text)
+ return
+ from pygments import highlight # noqa: PLC0415
+ from pygments.formatters import ( # noqa: PLC0415
+ HtmlFormatter, # ty: ignore[unresolved-import]
+ Terminal256Formatter, # ty: ignore[unresolved-import]
+ )
+ from pygments.lexers.python import Python3Lexer # noqa: PLC0415
+
+ if is_notebook:
+ from IPython import display # noqa: PLC0415
+
+ formatter = HtmlFormatter(style=pygment_style, noclasses=True)
+ display.display(display.HTML(highlight(text, Python3Lexer(), formatter)))
+ else:
+ print(highlight(text, Python3Lexer(), Terminal256Formatter(style=pygment_style)))
+
+
+def _resolve_style(
+ style: str | None,
+ is_notebook: bool,
+) -> type[Style] | str | None:
+ """Return a Pygments style class/name, or ``None`` if Pygments is missing."""
+ global _PYGMENTS_WARNED # noqa: PLW0603
+ try:
+ from pygments.style import Style # noqa: PLC0415
+ from pygments.token import ( # noqa: PLC0415
+ Comment,
+ Keyword,
+ Name,
+ Number,
+ Operator,
+ String,
+ )
+ except ModuleNotFoundError:
+ if not _PYGMENTS_WARNED:
+ _PYGMENTS_WARNED = True
+ warnings.warn(
+ "pygments is not installed; falling back to plain text. "
+ "Install it for syntax-highlighted output: pip install pygments",
+ stacklevel=3,
+ )
+ return None
+
+ class _JupyterLight(Style):
+ """Jupyter-Notebook-like Pygments style (alias: ``"light"``)."""
+
+ background_color = ""
+ styles: typing.ClassVar = {
+ Keyword: "bold #008000",
+ Keyword.Type: "nobold #008000",
+ Name.Function: "#0000FF",
+ Name.Class: "bold #0000FF",
+ Name.Decorator: "#AA22FF",
+ String: "#BA2121",
+ Number: "#008000",
+ Operator: "bold #AA22FF",
+ Operator.Word: "bold #008000",
+ Comment: "italic #007979",
+ }
+
+ class _VSCDark(Style):
+ """VSCode-Dark-like Pygments style (alias: ``"dark"``)."""
+
+ background_color = ""
+ styles: typing.ClassVar = {
+ Keyword: "bold #c586c0",
+ Keyword.Type: "#82aaff",
+ Keyword.Namespace: "#4ec9b0",
+ Name.Class: "bold #569cd6",
+ Name.Function: "bold #dcdcaa",
+ Name.Decorator: "italic #fe4ef3",
+ String: "#ce9178",
+ Number: "#b5cea8",
+ Operator: "#bbbbbb",
+ Operator.Word: "#569cd6",
+ Comment: "italic #6a9956",
+ }
+
+ class _AnsiTerminal(Style):
+ """ANSI terminal Pygments style (alias: ``"ansi"``)."""
+
+ background_color = ""
+ styles: typing.ClassVar = {
+ Keyword: "bold ansigreen",
+ Keyword.Type: "nobold ansigreen",
+ Name.Class: "bold ansiblue",
+ Name.Function: "bold ansiblue",
+ Name.Decorator: "italic ansibrightmagenta",
+ String: "ansiyellow",
+ Number: "ansibrightgreen",
+ Operator: "bold ansimagenta",
+ Operator.Word: "bold ansigreen",
+ Comment: "italic ansibrightblack",
+ }
+
+ _BUILTIN_STYLES: dict[str, type[Style]] = {
+ "light": _JupyterLight,
+ "dark": _VSCDark,
+ "ansi": _AnsiTerminal,
+ }
+ if style is not None:
+ return _BUILTIN_STYLES.get(style, style)
+ return _JupyterLight if is_notebook else _AnsiTerminal
diff --git a/python/tvm_ffi/_pyast_translator.py b/python/tvm_ffi/_pyast_translator.py
new file mode 100644
index 0000000..9405adb
--- /dev/null
+++ b/python/tvm_ffi/_pyast_translator.py
@@ -0,0 +1,770 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Internal: convert Python standard-library ``ast`` nodes to TVM-FFI text AST nodes.
+
+This module is not part of the public API. Use :func:`tvm_ffi.pyast.from_py`
+as the public entry point.
+"""
+
+from __future__ import annotations
+
+import ast
+import math
+import textwrap
+from typing import Callable
+
+from tvm_ffi import pyast as tast
+
+# ---------------------------------------------------------------------------
+# Operator mapping tables
+# ---------------------------------------------------------------------------
+
+_UNARY_OP: dict[type, int] = {
+ ast.USub: tast.OperationKind.USub,
+ ast.UAdd: tast.OperationKind.UAdd,
+ ast.Invert: tast.OperationKind.Invert,
+ ast.Not: tast.OperationKind.Not,
+}
+
+_BINOP: dict[type, int] = {
+ ast.Add: tast.OperationKind.Add,
+ ast.Sub: tast.OperationKind.Sub,
+ ast.Mult: tast.OperationKind.Mult,
+ ast.Div: tast.OperationKind.Div,
+ ast.FloorDiv: tast.OperationKind.FloorDiv,
+ ast.Mod: tast.OperationKind.Mod,
+ ast.Pow: tast.OperationKind.Pow,
+ ast.LShift: tast.OperationKind.LShift,
+ ast.RShift: tast.OperationKind.RShift,
+ ast.BitAnd: tast.OperationKind.BitAnd,
+ ast.BitOr: tast.OperationKind.BitOr,
+ ast.BitXor: tast.OperationKind.BitXor,
+ ast.MatMult: tast.OperationKind.MatMult,
+}
+
+_CMPOP: dict[type, int] = {
+ ast.Lt: tast.OperationKind.Lt,
+ ast.LtE: tast.OperationKind.LtE,
+ ast.Gt: tast.OperationKind.Gt,
+ ast.GtE: tast.OperationKind.GtE,
+ ast.Eq: tast.OperationKind.Eq,
+ ast.NotEq: tast.OperationKind.NotEq,
+ ast.Is: tast.OperationKind.Is,
+ ast.IsNot: tast.OperationKind.IsNot,
+ ast.In: tast.OperationKind.In,
+ ast.NotIn: tast.OperationKind.NotIn,
+}
+
+_BOOLOP: dict[type, int] = {
+ ast.And: tast.OperationKind.And,
+ ast.Or: tast.OperationKind.Or,
+}
+
+
+# ---------------------------------------------------------------------------
+# _Converter — stateless recursive converter
+# ---------------------------------------------------------------------------
+
+
+class _Converter:
+ """Converts Python ``ast`` nodes to TVM-FFI text AST nodes."""
+
+ def __init__(self) -> None:
+ self._expr_dispatch: dict[type, Callable[..., tast.Expr]] = {
+ ast.Constant: self._convert_constant,
+ ast.Name: self._convert_name,
+ ast.Attribute: self._convert_attribute,
+ ast.Subscript: self._convert_subscript,
+ ast.Call: self._convert_call,
+ ast.UnaryOp: self._convert_unaryop,
+ ast.BinOp: self._convert_binop,
+ ast.BoolOp: self._convert_boolop,
+ ast.Compare: self._convert_compare,
+ ast.IfExp: self._convert_ifexp,
+ ast.Lambda: self._convert_lambda,
+ ast.Tuple: self._convert_tuple,
+ ast.List: self._convert_list,
+ ast.Dict: self._convert_dict,
+ ast.Slice: self._convert_slice,
+ ast.Starred: self._convert_starred,
+ ast.Set: self._convert_set,
+ ast.ListComp: self._convert_listcomp,
+ ast.SetComp: self._convert_setcomp,
+ ast.DictComp: self._convert_dictcomp,
+ ast.GeneratorExp: self._convert_generatorexp,
+ ast.Yield: self._convert_yield,
+ ast.YieldFrom: self._convert_yieldfrom,
+ ast.JoinedStr: self._convert_joinedstr,
+ ast.FormattedValue: self._convert_formattedvalue,
+ ast.NamedExpr: self._convert_namedexpr,
+ ast.Await: self._convert_await,
+ }
+ self._stmt_dispatch: dict[type, Callable[..., tast.Stmt | list[tast.Stmt]]] = {
+ ast.Module: self._convert_module,
+ ast.Assign: self._convert_assign,
+ ast.AnnAssign: self._convert_annassign,
+ ast.AugAssign: self._convert_augassign,
+ ast.Expr: self._convert_expr_stmt,
+ ast.If: self._convert_if,
+ ast.While: self._convert_while,
+ ast.For: self._convert_for,
+ ast.AsyncFor: self._convert_for,
+ ast.With: self._convert_with,
+ ast.AsyncWith: self._convert_with,
+ ast.FunctionDef: self._convert_functiondef,
+ ast.AsyncFunctionDef: self._convert_functiondef,
+ ast.ClassDef: self._convert_classdef,
+ ast.Return: self._convert_return,
+ ast.Assert: self._convert_assert,
+ ast.Pass: self._convert_pass,
+ ast.Break: self._convert_break,
+ ast.Continue: self._convert_continue,
+ ast.Import: self._convert_import,
+ ast.ImportFrom: self._convert_importfrom,
+ ast.Delete: self._convert_delete,
+ ast.Raise: self._convert_raise,
+ ast.Global: self._convert_global,
+ ast.Nonlocal: self._convert_nonlocal,
+ ast.Try: self._convert_try,
+ }
+ if hasattr(ast, "TryStar"):
+ self._stmt_dispatch[ast.TryStar] = self._convert_try
+ if hasattr(ast, "Match"):
+ self._stmt_dispatch[ast.Match] = self._convert_match
+ if hasattr(ast, "TypeAlias"):
+ self._stmt_dispatch[ast.TypeAlias] = self._convert_typealias # ty: ignore[unresolved-attribute]
+
+ # -- span helper --------------------------------------------------------
+
+ @staticmethod
+ def _set_span(result: tast.Node, source: ast.AST) -> None:
+ """Copy source location from a Python AST node to a TVM-FFI AST node."""
+ result.lineno = getattr(source, "lineno", -1) or -1
+ result.col_offset = getattr(source, "col_offset", -1)
+ if result.col_offset is None:
+ result.col_offset = -1
+ result.end_lineno = getattr(source, "end_lineno", -1) or -1
+ result.end_col_offset = getattr(source, "end_col_offset", -1)
+ if result.end_col_offset is None:
+ result.end_col_offset = -1
+
+ # -- public entry points ------------------------------------------------
+
+ def convert(self, node: ast.AST) -> tast.Node:
+ """Convert a Python AST node to a TVM-FFI AST node."""
+ if isinstance(node, ast.expr):
+ return self.convert_expr(node)
+ if isinstance(node, ast.stmt):
+ result = self._dispatch_stmt(node)
+ if isinstance(result, list):
+ return tast.StmtBlock(result) # ty: ignore[invalid-argument-type]
+ return result
+ if isinstance(node, ast.Module):
+ return self._convert_module(node)
+ if isinstance(node, ast.Expression):
+ return self.convert_expr(node.body)
+ if isinstance(node, ast.Interactive):
+ stmts = self._convert_body(node.body)
+ return tast.StmtBlock(stmts)
+ raise NotImplementedError(f"Unsupported top-level AST node type: {type(node).__name__}")
+
+ def convert_expr(self, node: ast.expr) -> tast.Expr:
+ """Convert a Python expression AST node to a TVM-FFI Expr."""
+ handler = self._expr_dispatch.get(type(node))
+ if handler is None:
+ raise NotImplementedError(
+ f"Unsupported expression AST node type: {type(node).__name__}"
+ )
+ result = handler(node)
+ self._set_span(result, node)
+ return result
+
+ # -- expression handlers ------------------------------------------------
+
+ def _convert_constant(self, node: ast.Constant) -> tast.Expr: # noqa: PLR0911
+ value = node.value
+ if isinstance(value, float) and math.isinf(value):
+ return tast.Id("-1e999" if value < 0 else "1e999")
+ if isinstance(value, float) and math.isnan(value):
+ return tast.Id('float("nan")')
+ if value is None or isinstance(value, (bool, float, str)):
+ return tast.Literal(value)
+ if isinstance(value, int):
+ # int64 range check: FFI stores integers as int64_t
+ if -(2**63) <= value < 2**63:
+ return tast.Literal(value)
+ return tast.Id(repr(value))
+ if value is ...:
+ return tast.Id("...")
+ # For unsupported literal types (bytes, complex, tuple, frozenset),
+ # fall back to rendering via repr
+ return tast.Id(repr(value))
+
+ def _convert_name(self, node: ast.Name) -> tast.Expr:
+ return tast.Id(node.id)
+
+ def _convert_attribute(self, node: ast.Attribute) -> tast.Expr:
+ return tast.Attr(self.convert_expr(node.value), node.attr)
+
+ def _convert_subscript(self, node: ast.Subscript) -> tast.Expr:
+ obj = self.convert_expr(node.value)
+ slc = node.slice
+ has_starred = isinstance(slc, ast.Tuple) and any(
+ isinstance(e, ast.Starred) for e in slc.elts
+ )
+ if isinstance(slc, ast.Tuple) and len(slc.elts) != 1 and not has_starred:
+ # Multi-element tuple without Starred: x[a, b] → Index(obj, [a, b])
+ indices = [self.convert_expr(e) for e in slc.elts]
+ else:
+ # Single value, single-element tuple, or tuple with Starred: keep as one index.
+ # For Starred in subscript, preserving the Tuple wrapper renders as
+ # x[(*a, b)] which is valid on Python 3.9+, unlike x[*a, b] (3.11+).
+ # For x[1,] (single-element tuple), this becomes Index(obj, [Tuple([1])])
+ # which renders as x[(1,)] — semantically equivalent, roundtrips correctly.
+ indices = [self.convert_expr(slc)]
+ return tast.Index(obj, indices)
+
+ def _convert_call(self, node: ast.Call) -> tast.Expr:
+ callee = self.convert_expr(node.func)
+ args = [self.convert_expr(a) for a in node.args]
+ kwargs_keys: list[str] = []
+ kwargs_values: list[tast.Expr] = []
+ for kw in node.keywords:
+ kwargs_keys.append(kw.arg if kw.arg is not None else "")
+ kwargs_values.append(self.convert_expr(kw.value))
+ return tast.Call(callee, args, kwargs_keys, kwargs_values)
+
+ def _convert_unaryop(self, node: ast.UnaryOp) -> tast.Expr:
+ operand = self.convert_expr(node.operand)
+ kind = _UNARY_OP.get(type(node.op))
+ if kind is None:
+ raise NotImplementedError(f"Unsupported unary operator: {type(node.op).__name__}")
+ return tast.Operation(kind, [operand])
+
+ def _convert_binop(self, node: ast.BinOp) -> tast.Expr:
+ kind = _BINOP.get(type(node.op))
+ if kind is None:
+ raise NotImplementedError(f"Unsupported binary operator: {type(node.op).__name__}")
+ left = self.convert_expr(node.left)
+ right = self.convert_expr(node.right)
+ return tast.Operation(kind, [left, right])
+
+ def _convert_boolop(self, node: ast.BoolOp) -> tast.Expr:
+ kind = _BOOLOP[type(node.op)]
+ values: list[tast.Expr] = []
+ for v in node.values:
+ converted = self.convert_expr(v)
+ # Wrap nested same-operator BoolOps in Parens to preserve grouping.
+ # Without parens, "a and b and c" re-parses as flat And([a,b,c]),
+ # losing the nested And([And([a,b]), c]) structure.
+ if isinstance(v, ast.BoolOp) and type(v.op) is type(node.op):
+ converted = tast.Operation(tast.OperationKind.Parens, [converted])
+ values.append(converted)
+ return tast.Operation(kind, values)
+
+ def _convert_compare(self, node: ast.Compare) -> tast.Expr:
+ left = self.convert_expr(node.left)
+ # Wrap Compare left in parens if it's itself a Compare, to prevent
+ # (a == b) == c from becoming the chained a == b == c.
+ if isinstance(node.left, ast.Compare):
+ left = tast.Operation(tast.OperationKind.Parens, [left])
+ if len(node.ops) == 1:
+ right = self.convert_expr(node.comparators[0])
+ kind = _CMPOP.get(type(node.ops[0]))
+ if kind is None:
+ raise NotImplementedError(
+ f"Unsupported comparison operator: {type(node.ops[0]).__name__}"
+ )
+ return tast.Operation(kind, [left, right])
+ # Chained comparison: a < b < c -> Operation(ChainedCompare, [a, Literal(Lt), b, ...])
+ operands: list[tast.Expr] = [left]
+ for op, comparator in zip(node.ops, node.comparators):
+ kind = _CMPOP.get(type(op))
+ if kind is None:
+ raise NotImplementedError(f"Unsupported comparison operator: {type(op).__name__}")
+ operands.append(tast.Literal(kind))
+ operands.append(self.convert_expr(comparator))
+ return tast.Operation(tast.OperationKind.ChainedCompare, operands)
+
+ def _convert_ifexp(self, node: ast.IfExp) -> tast.Expr:
+ test = self.convert_expr(node.test)
+ body = self.convert_expr(node.body)
+ orelse = self.convert_expr(node.orelse)
+ # Wrap body in Parens if it is itself a ternary, because without parens
+ # "B if A else C if X else Z" parses as "B if A else (C if X else Z)"
+ # which is a different structure from "(B if A else C) if X else Z".
+ if isinstance(node.body, ast.IfExp):
+ body = tast.Operation(tast.OperationKind.Parens, [body])
+ return tast.Operation(tast.OperationKind.IfThenElse, [test, body, orelse])
+
+ def _convert_lambda(self, node: ast.Lambda) -> tast.Expr:
+ converted_args = self._convert_arguments(node.args)
+ args: list[tast.Expr] = []
+ for a in converted_args:
+ if a.rhs is not None or a.annotation is not None:
+ # Render "name: ann = default" or "name=default" as a text Id
+ # since Lambda args are List<ExprAST> (can't hold Assign stmts).
+ parts = a.lhs.to_python()
+ if a.annotation is not None:
+ parts += ": " + a.annotation.to_python()
+ if a.rhs is not None:
+ parts += "=" + a.rhs.to_python()
+ args.append(tast.Id(parts))
+ else:
+ args.append(a.lhs)
+ body = self.convert_expr(node.body)
+ return tast.Lambda(args, body)
+
+ def _convert_tuple(self, node: ast.Tuple) -> tast.Expr:
+ return tast.Tuple([self.convert_expr(e) for e in node.elts])
+
+ def _convert_list(self, node: ast.List) -> tast.Expr:
+ return tast.List([self.convert_expr(e) for e in node.elts])
+
+ def _convert_dict(self, node: ast.Dict) -> tast.Expr:
+ keys: list[tast.Expr] = []
+ values: list[tast.Expr] = []
+ for k, v in zip(node.keys, node.values):
+ if k is None:
+ # Dictionary unpacking: {**d} → use StarredExpr as a sentinel key
+ keys.append(tast.StarredExpr(tast.StarredExpr(self.convert_expr(v))))
+ else:
+ keys.append(self.convert_expr(k))
+ values.append(self.convert_expr(v))
+ return tast.Dict(keys, values)
+
+ def _convert_slice(self, node: ast.Slice) -> tast.Expr:
+ start = self.convert_expr(node.lower) if node.lower else None
+ stop = self.convert_expr(node.upper) if node.upper else None
+ step = self.convert_expr(node.step) if node.step else None
+ return tast.Slice(start, stop, step)
+
+ def _convert_starred(self, node: ast.Starred) -> tast.Expr:
+ value = self.convert_expr(node.value)
+ # Wrap ternary values in parens: *([x] if c else []) must keep parens
+ if isinstance(node.value, ast.IfExp):
+ value = tast.Operation(tast.OperationKind.Parens, [value])
+ return tast.StarredExpr(value)
+
+ def _convert_set(self, node: ast.Set) -> tast.Expr:
+ return tast.Set([self.convert_expr(e) for e in node.elts])
+
+ def _convert_comprehension_iters(
+ self, generators: list[ast.comprehension]
+ ) -> list[tast.ComprehensionIter]:
+ result: list[tast.ComprehensionIter] = []
+ for gen in generators:
+ target = self.convert_expr(gen.target)
+ iter_expr = self.convert_expr(gen.iter)
+ # Wrap ternary iters in parens to avoid ambiguity with filter `if`
+ if isinstance(gen.iter, ast.IfExp):
+ iter_expr = tast.Operation(tast.OperationKind.Parens, [iter_expr])
+ ifs = [self.convert_expr(c) for c in gen.ifs]
+ result.append(tast.ComprehensionIter(target, iter_expr, ifs))
+ return result
+
+ def _convert_listcomp(self, node: ast.ListComp) -> tast.Expr:
+ elt = self.convert_expr(node.elt)
+ iters = self._convert_comprehension_iters(node.generators)
+ return tast.Comprehension(tast.ComprehensionKind.List, elt, None, iters)
+
+ def _convert_setcomp(self, node: ast.SetComp) -> tast.Expr:
+ elt = self.convert_expr(node.elt)
+ iters = self._convert_comprehension_iters(node.generators)
+ return tast.Comprehension(tast.ComprehensionKind.Set, elt, None, iters)
+
+ def _convert_dictcomp(self, node: ast.DictComp) -> tast.Expr:
+ key = self.convert_expr(node.key)
+ value = self.convert_expr(node.value)
+ iters = self._convert_comprehension_iters(node.generators)
+ return tast.Comprehension(tast.ComprehensionKind.Dict, key, value, iters)
+
+ def _convert_generatorexp(self, node: ast.GeneratorExp) -> tast.Expr:
+ elt = self.convert_expr(node.elt)
+ iters = self._convert_comprehension_iters(node.generators)
+ return tast.Comprehension(tast.ComprehensionKind.Generator, elt, None, iters)
+
+ def _convert_yield(self, node: ast.Yield) -> tast.Expr:
+ value = self.convert_expr(node.value) if node.value else None
+ return tast.Yield(value)
+
+ def _convert_yieldfrom(self, node: ast.YieldFrom) -> tast.Expr:
+ return tast.YieldFrom(self.convert_expr(node.value))
+
+ def _convert_joinedstr(self, node: ast.JoinedStr) -> tast.Expr:
+ values: list[tast.Expr] = []
+ for v in node.values:
+ values.append(self.convert_expr(v))
+ return tast.FStr(values)
+
+ def _convert_formattedvalue(self, node: ast.FormattedValue) -> tast.Expr:
+ value = self.convert_expr(node.value)
+ conversion = node.conversion
+ format_spec = self.convert_expr(node.format_spec) if node.format_spec else None
+ return tast.FStrValue(value, conversion, format_spec)
+
+ def _convert_namedexpr(self, node: ast.NamedExpr) -> tast.Expr:
+ return tast.WalrusExpr(self.convert_expr(node.target), self.convert_expr(node.value))
+
+ def _convert_await(self, node: ast.Await) -> tast.Expr:
+ return tast.AwaitExpr(self.convert_expr(node.value))
+
+ # -- statement helpers --------------------------------------------------
+
+ def _dispatch_stmt(self, node: ast.stmt) -> tast.Stmt | list[tast.Stmt]:
+ handler = self._stmt_dispatch.get(type(node))
+ if handler is None:
+ raise NotImplementedError(f"Unsupported statement AST node type: {type(node).__name__}")
+ result = handler(node)
+ if isinstance(result, list):
+ for r in result:
+ self._set_span(r, node) # ty: ignore[invalid-argument-type]
+ else:
+ self._set_span(result, node)
+ return result
+
+ def _convert_body(
+ self, stmts: list[ast.stmt], *, detect_docstring: bool = False
+ ) -> list[tast.Stmt]:
+ result: list[tast.Stmt] = []
+ for i, stmt in enumerate(stmts):
+ if (
+ detect_docstring
+ and i == 0
+ and isinstance(stmt, ast.Expr)
+ and isinstance(stmt.value, ast.Constant)
+ and isinstance(stmt.value.value, str)
+ ):
+ result.append(tast.DocString(stmt.value.value))
+ continue
+ converted = self._dispatch_stmt(stmt)
+ if isinstance(converted, list):
+ result.extend(converted) # ty: ignore[invalid-argument-type]
+ else:
+ result.append(converted)
+ return result
+
+ # -- statement handlers -------------------------------------------------
+
+ def _convert_module(self, node: ast.Module) -> tast.Stmt:
+ stmts = self._convert_body(node.body, detect_docstring=True)
+ return tast.StmtBlock(stmts)
+
+ def _convert_assign(self, node: ast.Assign) -> tast.Stmt:
+ rhs = self.convert_expr(node.value)
+ if len(node.targets) == 1:
+ return tast.Assign(lhs=self._convert_target(node.targets[0]), rhs=rhs)
+ # Multi-target: a = b = c → Assign(lhs=Parens(Tuple([a, b])), rhs=c)
+ targets = [self._convert_target(t) for t in node.targets]
+ lhs = tast.Operation(tast.OperationKind.Parens, [tast.Tuple(targets)])
+ return tast.Assign(lhs=lhs, rhs=rhs)
+
+ def _convert_target(self, node: ast.expr) -> tast.Expr:
+ """Convert an assignment target, preserving List vs Tuple distinction."""
+ if isinstance(node, ast.List):
+ return tast.List([self._convert_target(e) for e in node.elts])
+ if isinstance(node, ast.Tuple):
+ return tast.Tuple([self._convert_target(e) for e in node.elts])
+ if isinstance(node, ast.Starred):
+ return tast.StarredExpr(self._convert_target(node.value))
+ return self.convert_expr(node)
+
+ def _convert_annassign(self, node: ast.AnnAssign) -> tast.Stmt:
+ lhs = self.convert_expr(node.target)
+ annotation = self.convert_expr(node.annotation)
+ rhs = self.convert_expr(node.value) if node.value else None
+ return tast.Assign(lhs=lhs, rhs=rhs, annotation=annotation)
+
+ def _convert_augassign(self, node: ast.AugAssign) -> tast.Stmt:
+ kind = _BINOP.get(type(node.op))
+ if kind is None:
+ raise NotImplementedError(
+ f"Unsupported augmented assignment operator: {type(node.op).__name__}"
+ )
+ lhs = self.convert_expr(node.target)
+ rhs = self.convert_expr(node.value)
+ return tast.Assign(lhs=lhs, rhs=rhs, aug_op=kind)
+
+ def _convert_expr_stmt(self, node: ast.Expr) -> tast.Stmt:
+ return tast.ExprStmt(self.convert_expr(node.value))
+
+ def _convert_if(self, node: ast.If) -> tast.Stmt:
+ cond = self.convert_expr(node.test)
+ then_branch = self._convert_body(node.body)
+ else_branch = self._convert_body(node.orelse)
+ return tast.If(cond, then_branch, else_branch)
+
+ def _convert_while(self, node: ast.While) -> tast.Stmt:
+ cond = self.convert_expr(node.test)
+ body = self._convert_body(node.body)
+ orelse = self._convert_body(node.orelse) if node.orelse else []
+ return tast.While(cond, body, orelse)
+
+ def _convert_for(self, node: ast.For | ast.AsyncFor) -> tast.Stmt:
+ lhs = self.convert_expr(node.target)
+ rhs = self.convert_expr(node.iter)
+ body = self._convert_body(node.body)
+ is_async = isinstance(node, ast.AsyncFor)
+ orelse = self._convert_body(node.orelse) if node.orelse else []
+ return tast.For(lhs, rhs, body, is_async, orelse)
+
+ def _convert_with(self, node: ast.With | ast.AsyncWith) -> tast.Stmt:
+ is_async = isinstance(node, ast.AsyncWith)
+ body_stmts = self._convert_body(node.body)
+ if len(node.items) == 1:
+ item = node.items[0]
+ rhs = self.convert_expr(item.context_expr)
+ lhs = self.convert_expr(item.optional_vars) if item.optional_vars else None
+ return tast.With(lhs, rhs, body_stmts, is_async)
+ # Multi-item with: encode as Tuple of context exprs / targets
+ rhs_elts = [self.convert_expr(item.context_expr) for item in node.items]
+ lhs_elts = [
+ self.convert_expr(item.optional_vars) if item.optional_vars else tast.Id("")
+ for item in node.items
+ ]
+ return tast.With(tast.Tuple(lhs_elts), tast.Tuple(rhs_elts), body_stmts, is_async)
+
+ @staticmethod
+ def _make_name_with_type_params(name: str, type_params: list) -> tast.Id:
+ """Build an Id with type params appended, e.g. 'Foo[T, U: int]'."""
+ if not type_params:
+ return tast.Id(name)
+ parts: list[str] = []
+ for tp in type_params:
+ if isinstance(tp, ast.TypeVar): # ty: ignore[unresolved-attribute]
+ s = tp.name
+ if tp.bound:
+ s += ": " + ast.unparse(tp.bound)
+ parts.append(s)
+ elif isinstance(tp, ast.TypeVarTuple): # ty: ignore[unresolved-attribute]
+ parts.append("*" + tp.name)
+ elif isinstance(tp, ast.ParamSpec): # ty: ignore[unresolved-attribute]
+ parts.append("**" + tp.name)
+ else:
+ parts.append(str(tp.name)) # pragma: no cover
+ return tast.Id(name + "[" + ", ".join(parts) + "]")
+
+ def _convert_functiondef(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> tast.Stmt:
+ name = self._make_name_with_type_params(node.name, getattr(node, "type_params", []))
+ args = self._convert_arguments(node.args)
+ decorators = [self.convert_expr(d) for d in node.decorator_list]
+ return_type = self.convert_expr(node.returns) if node.returns else None
+ body = self._convert_body(node.body, detect_docstring=True)
+ is_async = isinstance(node, ast.AsyncFunctionDef)
+ return tast.Function(name, args, decorators, return_type, body, is_async)
+
+ def _convert_arguments(self, args: ast.arguments) -> list[tast.Assign]:
+ result: list[tast.Assign] = []
+ # Positional-only args first, then a / separator
+ all_args = list(args.posonlyargs) + list(args.args)
+ posonly_count = len(args.posonlyargs)
+ # Defaults are right-aligned to args
+ num_defaults = len(args.defaults)
+ num_no_default = len(all_args) - num_defaults
+ for i, arg in enumerate(all_args):
+ lhs = tast.Id(arg.arg)
+ annotation = self.convert_expr(arg.annotation) if arg.annotation else None
+ default_idx = i - num_no_default
+ rhs = self.convert_expr(args.defaults[default_idx]) if default_idx >= 0 else None
+ result.append(tast.Assign(lhs=lhs, rhs=rhs, annotation=annotation))
+ # Insert / separator after the last positional-only arg
+ if posonly_count > 0 and i == posonly_count - 1:
+ result.append(tast.Assign(lhs=tast.Id("/")))
+ # *args or bare * separator
+ if args.vararg or args.kwonlyargs:
+ if args.vararg:
+ vararg_name = tast.StarredExpr(tast.Id(args.vararg.arg))
+ ann = self.convert_expr(args.vararg.annotation) if args.vararg.annotation else None
+ result.append(tast.Assign(lhs=vararg_name, annotation=ann))
+ else:
+ # bare * separator for keyword-only args
+ result.append(tast.Assign(lhs=tast.StarredExpr(tast.Id(""))))
+ # Keyword-only args
+ for i, arg in enumerate(args.kwonlyargs):
+ lhs = tast.Id(arg.arg)
+ annotation = self.convert_expr(arg.annotation) if arg.annotation else None
+ default = args.kw_defaults[i]
+ rhs = self.convert_expr(default) if default else None
+ result.append(tast.Assign(lhs=lhs, rhs=rhs, annotation=annotation))
+ # **kwargs
+ if args.kwarg:
+ kwarg_name = tast.StarredExpr(tast.StarredExpr(tast.Id(args.kwarg.arg)))
+ ann = self.convert_expr(args.kwarg.annotation) if args.kwarg.annotation else None
+ result.append(tast.Assign(lhs=kwarg_name, annotation=ann))
+ return result
+
+ def _convert_classdef(self, node: ast.ClassDef) -> tast.Stmt:
+ name = self._make_name_with_type_params(node.name, getattr(node, "type_params", []))
+ bases = [self.convert_expr(b) for b in node.bases]
+ decorators = [self.convert_expr(d) for d in node.decorator_list]
+ body = self._convert_body(node.body, detect_docstring=True)
+ kwargs_keys = [kw.arg for kw in node.keywords if kw.arg is not None]
+ kwargs_values = [self.convert_expr(kw.value) for kw in node.keywords if kw.arg is not None]
+ return tast.Class(name, bases, decorators, body, kwargs_keys, kwargs_values)
+
+ def _convert_return(self, node: ast.Return) -> tast.Stmt:
+ value = self.convert_expr(node.value) if node.value else None
+ return tast.Return(value)
+
+ def _convert_assert(self, node: ast.Assert) -> tast.Stmt:
+ cond = self.convert_expr(node.test)
+ msg = self.convert_expr(node.msg) if node.msg else None
+ return tast.Assert(cond, msg)
+
+ def _convert_pass(self, node: ast.Pass) -> tast.Stmt:
+ return tast.ExprStmt(tast.Id("pass"))
+
+ def _convert_break(self, node: ast.Break) -> tast.Stmt:
+ return tast.ExprStmt(tast.Id("break"))
+
+ def _convert_continue(self, node: ast.Continue) -> tast.Stmt:
+ return tast.ExprStmt(tast.Id("continue"))
+
+ def _convert_import(self, node: ast.Import) -> tast.Stmt:
+ parts: list[str] = []
+ for alias in node.names:
+ if alias.asname:
+ parts.append(f"{alias.name} as {alias.asname}")
+ else:
+ parts.append(alias.name)
+ return tast.ExprStmt(tast.Id(f"import {', '.join(parts)}"))
+
+ def _convert_importfrom(self, node: ast.ImportFrom) -> tast.Stmt:
+ module = node.module or ""
+ prefix = "." * (node.level or 0)
+ names: list[str] = []
+ for alias in node.names:
+ if alias.asname:
+ names.append(f"{alias.name} as {alias.asname}")
+ else:
+ names.append(alias.name)
+ return tast.ExprStmt(tast.Id(f"from {prefix}{module} import {', '.join(names)}"))
+
+ def _convert_delete(self, node: ast.Delete) -> tast.Stmt:
+ targets_str = ", ".join(ast.unparse(t) for t in node.targets)
+ return tast.ExprStmt(tast.Id(f"del {targets_str}"))
+
+ def _convert_raise(self, node: ast.Raise) -> tast.Stmt:
+ if node.exc is None:
+ return tast.ExprStmt(tast.Id("raise"))
+ if node.cause:
+ return tast.ExprStmt(
+ tast.Id(f"raise {ast.unparse(node.exc)} from {ast.unparse(node.cause)}")
+ )
+ return tast.ExprStmt(tast.Id(f"raise {ast.unparse(node.exc)}"))
+
+ def _convert_global(self, node: ast.Global) -> tast.Stmt:
+ return tast.ExprStmt(tast.Id(f"global {', '.join(node.names)}"))
+
+ def _convert_nonlocal(self, node: ast.Nonlocal) -> tast.Stmt:
+ return tast.ExprStmt(tast.Id(f"nonlocal {', '.join(node.names)}"))
+
+ def _convert_try(self, node: ast.Try) -> tast.Stmt:
+ body = self._convert_body(node.body)
+ handlers: list[tast.ExceptHandler] = []
+ for h in node.handlers:
+ h_type = self.convert_expr(h.type) if h.type else None
+ h_body = self._convert_body(h.body)
+ handlers.append(tast.ExceptHandler(h_type, h.name, h_body))
+ orelse = self._convert_body(node.orelse) if node.orelse else []
+ finalbody = self._convert_body(node.finalbody) if node.finalbody else []
+ return tast.Try(body, handlers, orelse, finalbody)
+
+ def _convert_match(self, node: ast.Match) -> tast.Stmt: # ty: ignore[unresolved-attribute]
+ subject = self.convert_expr(node.subject)
+ cases: list[tast.MatchCase] = []
+ for case in node.cases:
+ pattern = self._convert_match_pattern(case.pattern)
+ guard = self.convert_expr(case.guard) if case.guard else None
+ case_body = self._convert_body(case.body)
+ cases.append(tast.MatchCase(pattern, guard, case_body))
+ return tast.Match(subject, cases)
+
+ def _convert_match_pattern(self, node: ast.pattern) -> tast.Expr: # ty: ignore[unresolved-attribute]
+ """Convert match patterns to expression AST using best-effort mapping."""
+ # Use ast.unparse for a faithful text representation
+ return tast.Id(ast.unparse(node))
+
+ def _convert_typealias(self, node: ast.TypeAlias) -> tast.Stmt: # ty: ignore[unresolved-attribute]
+ """Convert ``type X = ...`` (PEP 695) to an Assign with ``type`` prefix."""
+ type_params = getattr(node, "type_params", [])
+ name_str = node.name.id # ty: ignore[unresolved-attribute]
+ if type_params:
+ name_id = self._make_name_with_type_params(name_str, type_params)
+ else:
+ name_id = tast.Id(name_str)
+ # Render as "type X = value" by prefixing "type " in the lhs name
+ lhs = tast.Id("type " + name_id.name)
+ rhs = self.convert_expr(node.value)
+ return tast.Assign(lhs=lhs, rhs=rhs)
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+_converter = _Converter()
+
+
+def ast_translate(source: str | ast.AST) -> tast.Node:
+ """Convert a Python source string or ``ast.AST`` node to a TVM-FFI AST node.
+
+ Parameters
+ ----------
+ source
+ Either a Python source-code string (parsed with ``ast.parse``) or an
+ already-parsed ``ast.AST`` node.
+
+ Returns
+ -------
+ node
+ The corresponding TVM-FFI text AST node.
+
+ Raises
+ ------
+ NotImplementedError
+ If the source contains Python constructs that have no TVM-FFI AST
+ equivalent (e.g. ``try``/``except``, f-strings, comprehensions).
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi.pyast.ast import from_py
+
+ # From source string
+ node = from_py("x + 1")
+ print(node.to_python()) # x + 1
+
+ # From ast node
+ import ast
+
+ tree = ast.parse("y = 42")
+ node = from_py(tree)
+ node.print_python() # y = 42
+
+ Note
+ ----
+ This function is internal. The public entry point is
+ :func:`tvm_ffi.pyast.from_py`.
+
+ """
+ if isinstance(source, str):
+ source = textwrap.dedent(source)
+ tree = ast.parse(source)
+ return _converter.convert(tree)
+ return _converter.convert(source)
diff --git a/python/tvm_ffi/cython/type_info.pxi b/python/tvm_ffi/cython/type_info.pxi
index 7a19590..5263f3b 100644
--- a/python/tvm_ffi/cython/type_info.pxi
+++ b/python/tvm_ffi/cython/type_info.pxi
@@ -745,6 +745,17 @@ class TypeInfo:
_register_py_methods(self.type_index, py_methods)
self._read_back_methods()
+ def _register_py_attrs(self, py_attrs=None):
+ """Register class-level attributes as TypeAttr only (not TypeMethod).
+
+ Parameters
+ ----------
+ py_attrs : list[tuple[str, Any]] | None
+ Each entry is ``(name, value)``.
+ """
+ if py_attrs:
+ _register_py_attrs(self.type_index, py_attrs)
+
def _read_back_methods(self):
"""Read methods from the C type table into self.methods.
@@ -1109,6 +1120,48 @@ cdef _register_py_methods(int32_t type_index, list py_methods):
TVMFFIObjectDecRef(<TVMFFIObjectHandle>func_any.v_obj)
+cdef _register_py_attrs(int32_t type_index, list py_attrs):
+ """Register class-level attributes as TypeAttr only (no TypeMethod).
+
+ Parameters
+ ----------
+ type_index : int
+ The runtime type index of the type.
+ py_attrs : list[tuple[str, Any]]
+ Each entry is ``(name, value)``.
+ """
+ cdef TVMFFIAny val_any
+ cdef TVMFFIAny sentinel_any
+ cdef int c_api_ret_code
+ cdef ByteArrayArg name_arg
+
+ sentinel_any.type_index = kTVMFFINone
+ sentinel_any.v_int64 = 0
+
+ for name, value in py_attrs:
+ val_any.type_index = kTVMFFINone
+ val_any.v_int64 = 0
+ try:
+ name_arg = ByteArrayArg(c_str(name))
+
+ # Convert Python object -> TVMFFIAny
+ TVMFFIPyPyObjectToFFIAny(
+ TVMFFIPyArgSetterFactory_,
+ <PyObject*>value,
+ &val_any,
+ &c_api_ret_code,
+ )
+ CHECK_CALL(c_api_ret_code)
+
+ # Ensure type-attr column exists (sentinel: kTVMFFINone)
+ CHECK_CALL(TVMFFITypeRegisterAttr(kTVMFFINone, &name_arg.cdata, &sentinel_any))
+ # Register as TypeAttr
+ CHECK_CALL(TVMFFITypeRegisterAttr(type_index, &name_arg.cdata, &val_any))
+ finally:
+ if val_any.type_index >= kTVMFFIStaticObjectBegin and val_any.v_obj != NULL:
+ TVMFFIObjectDecRef(<TVMFFIObjectHandle>val_any.v_obj)
+
+
def _member_method_wrapper(method_func: Callable[..., Any]) -> Callable[..., Any]:
def wrapper(self: Any, *args: Any) -> Any:
return method_func(self, *args)
diff --git a/python/tvm_ffi/dataclasses/py_class.py b/python/tvm_ffi/dataclasses/py_class.py
index 2d3d287..a438b48 100644
--- a/python/tvm_ffi/dataclasses/py_class.py
+++ b/python/tvm_ffi/dataclasses/py_class.py
@@ -226,6 +226,23 @@ def _collect_py_methods(cls: type) -> list[tuple[str, Any, bool]] | None:
return methods if methods else None
+#: Class-level attributes that ``@py_class`` registers as TypeAttr
+#: (via ``TVMFFITypeRegisterAttr``) but NOT as TypeMethod.
+_FFI_RECOGNIZED_ATTRS: frozenset[str] = frozenset({"__ffi_ir_traits__"})
+
+
+def _collect_py_attrs(cls: type) -> list[tuple[str, Any]] | None:
+ """Extract recognized FFI class attributes (non-methods).
+
+ Returns a list of ``(name, value)`` tuples, or ``None`` if empty.
+ """
+ attrs: list[tuple[str, Any]] = []
+ for name in _FFI_RECOGNIZED_ATTRS:
+ if name in cls.__dict__:
+ attrs.append((name, cls.__dict__[name]))
+ return attrs if attrs else None
+
+
def _phase2_register_fields(
cls: type,
type_info: Any,
@@ -249,12 +266,15 @@ def _phase2_register_fields(
own_fields = _collect_own_fields(cls, hints, params["kw_only"])
py_methods = _collect_py_methods(cls)
+ py_attrs = _collect_py_attrs(cls)
# Register fields and type-level structural eq/hash kind with the C layer.
structure_kind = _STRUCTURE_KIND_MAP.get(params.get("structural_eq"))
type_info._register_fields(own_fields, structure_kind)
# Register user-defined dunder methods and read back system-generated ones.
type_info._register_py_methods(py_methods)
+ # Register recognized class-level attributes as TypeAttr.
+ type_info._register_py_attrs(py_attrs)
_add_class_attrs(cls, type_info)
# Remove deferred __init__ and restore user-defined __init__ if saved
@@ -396,6 +416,8 @@ _FFI_RECOGNIZED_METHODS: frozenset[str] = frozenset(
# Serialization (ToJSONGraph, FromJSONGraph)
"__data_to_json__",
"__data_from_json__",
+ # IR printing (text printer dispatch)
+ "__ffi_text_print__",
}
)
diff --git a/python/tvm_ffi/ir_traits.py b/python/tvm_ffi/ir_traits.py
new file mode 100644
index 0000000..7190bf3
--- /dev/null
+++ b/python/tvm_ffi/ir_traits.py
@@ -0,0 +1,306 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Semantic trait types for IR nodes.
+
+Traits describe WHAT each IR node IS (a loop, a value, a function)
+and are consumed by the text printer, optimizers, and other tools.
+"""
+
+from __future__ import annotations
+
+from tvm_ffi import Object
+from tvm_ffi.core import _lookup_type_attr
+from tvm_ffi.dataclasses import c_class
+
+# ---- Region ----
+
+
+# ---- Base trait ----
+
+
+@c_class("ffi.ir_traits.IRTraits", init=False)
+class IRTraits(Object):
+ """Base class for all semantic traits."""
+
+
+Trait = IRTraits # backward compatibility alias
+
+
+@c_class("ffi.ir_traits.ExprTraits", init=False)
+class ExprTraits(IRTraits):
+ """Base class for expression-level traits (produce a value)."""
+
+
+@c_class("ffi.ir_traits.StmtTraits", init=False)
+class StmtTraits(IRTraits):
+ """Base class for statement-level traits (side effects, control flow, scope)."""
+
+
+# ---- Region ----
+
+
+@c_class("ffi.ir_traits.RegionTraits")
+class RegionTraits(IRTraits):
+ """A region describes a scoped body with optional defs and return."""
+
+ body: str
+ def_values: str | None
+ def_expr: str | None
+ ret: str | None
+
+
+# ---- Expression traits ----
+
+
+@c_class("ffi.ir_traits.BinOpTraits")
+class BinOpTraits(ExprTraits):
+ """Binary operation trait (e.g. add, sub, mul)."""
+
+ lhs: str
+ rhs: str
+ op: str
+ text_printer_sugar_check: str | None
+ text_printer_func_name: str | None
+
+
+@c_class("ffi.ir_traits.UnaryOpTraits")
+class UnaryOpTraits(ExprTraits):
+ """Unary operation trait (e.g. neg, not)."""
+
+ operand: str
+ op: str
+
+
+@c_class("ffi.ir_traits.ValueTraits")
+class ValueTraits(ExprTraits):
+ """Named value trait with optional type annotation."""
+
+ name: str
+ ty: str | None
+ text_printer_type: str | None
+
+
+@c_class("ffi.ir_traits.LiteralTraits")
+class LiteralTraits(ExprTraits):
+ """Literal / leaf value trait."""
+
+ value: str
+ format: str | None
+
+
+@c_class("ffi.ir_traits.CallTraits")
+class CallTraits(ExprTraits):
+ """Call expression trait (function call with op and args)."""
+
+ op: str
+ args: str
+ attrs: str | None
+ kwargs: str | None
+ text_printer_callee: str | None
+
+
+@c_class("ffi.ir_traits.LoadTraits")
+class LoadTraits(ExprTraits):
+ """Load trait for reading from a source with optional indices."""
+
+ source: str
+ indices: str | None
+ predicate: str | None
+
+
+# ---- Statement traits ----
+
+
+@c_class("ffi.ir_traits.AssignTraits")
+class AssignTraits(StmtTraits):
+ """Assignment / expression-statement trait.
+
+ When def_values is set: renders as ``def_values = rhs`` (assignment).
+ When def_values is absent: renders ``rhs`` as a statement (expression-statement).
+ """
+
+ def_values: str | None
+ rhs: str
+ text_printer_pre: str | None
+ text_printer_post: str | None
+ text_printer_kind: str | None
+ text_printer_return_check: str | None
+
+
+@c_class("ffi.ir_traits.StoreTraits")
+class StoreTraits(StmtTraits):
+ """Store trait for writing a value to a target with optional indices."""
+
+ target: str
+ value: str
+ indices: str | None
+ predicate: str | None
+
+
+@c_class("ffi.ir_traits.AssertTraits")
+class AssertTraits(StmtTraits):
+ """Assertion trait with a condition and optional message."""
+
+ cond: str
+ message: str | None
+
+
+@c_class("ffi.ir_traits.ReturnTraits")
+class ReturnTraits(StmtTraits):
+ """Return trait carrying a value."""
+
+ value: str
+
+
+@c_class("ffi.ir_traits.FuncTraits")
+class FuncTraits(StmtTraits):
+ """Function definition trait with symbol name and body region."""
+
+ symbol: str
+ region: RegionTraits
+ attrs: str | None
+ text_printer_kind: str | None
+ text_printer_pre: str | None
+
+
+@c_class("ffi.ir_traits.ForTraits")
+class ForTraits(StmtTraits):
+ """For-loop trait with iteration range and body region."""
+
+ region: RegionTraits
+ start: str | None
+ end: str | None
+ step: str | None
+ def_carry: str | None
+ carry_init: str | None
+ attrs: str | None
+ text_printer_kind: str | None
+
+
+@c_class("ffi.ir_traits.WithTraits")
+class WithTraits(StmtTraits):
+ """Context-manager / sequence trait.
+
+ When text_printer_kind is set: renders as ``with kind(...) as var:`` block.
+ When text_printer_kind is absent and region has no defs: renders as inline sequence.
+ """
+
+ region: RegionTraits
+ def_carry: str | None
+ carry_init: str | None
+ text_printer_kind: str | None
+ text_printer_pre: str | None
+ text_printer_post: str | None
+ text_printer_no_frame: bool | None
+
+
+@c_class("ffi.ir_traits.WhileTraits")
+class WhileTraits(StmtTraits):
+ """While-loop trait with condition and body region."""
+
+ cond: str
+ region: RegionTraits
+
+
+@c_class("ffi.ir_traits.IfTraits")
+class IfTraits(StmtTraits):
+ """If-else conditional trait with then/else regions."""
+
+ cond: str
+ then_region: RegionTraits
+ else_region: RegionTraits | None
+
+
+# ---- Type traits ----
+
+
+@c_class("ffi.ir_traits.TyTraits", init=False)
+class TyTraits(IRTraits):
+ """Base class for type-level traits."""
+
+
+@c_class("ffi.ir_traits.TensorTyTraits")
+class TensorTyTraits(TyTraits):
+ """Tensor type trait with shape, dtype, and device."""
+
+ shape: str | None
+ dtype: str | None
+ device: str | None
+
+
+@c_class("ffi.ir_traits.BufferTyTraits")
+class BufferTyTraits(TyTraits):
+ """Buffer type trait with shape, dtype, strides, offset, and scope."""
+
+ shape: str
+ dtype: str
+ strides: str | None
+ offset: str | None
+ scope: str | None
+
+
+@c_class("ffi.ir_traits.PrimTyTraits")
+class PrimTyTraits(TyTraits):
+ """Primitive scalar type trait with dtype."""
+
+ dtype: str
+
+
+@c_class("ffi.ir_traits.FuncTyTraits")
+class FuncTyTraits(TyTraits):
+ """Function type trait with parameter and return types."""
+
+ params: str | None
+ ret: str | None
+
+
+@c_class("ffi.ir_traits.TupleTyTraits")
+class TupleTyTraits(TyTraits):
+ """Tuple type trait with field types."""
+
+ fields: str
+
+
+@c_class("ffi.ir_traits.ShapeTyTraits")
+class ShapeTyTraits(TyTraits):
+ """Shape type trait with dimension info."""
+
+ dims: str | None
+ ndim: str | None
+
+
+# ---- Query helpers ----
+
+
+def get_trait(obj: Object) -> IRTraits | None:
+ """Retrieve the semantic trait for an IR object, or None."""
+ info = type(obj).__tvm_ffi_type_info__ # type: ignore[attr-defined]
+ return _lookup_type_attr(info.type_index, "__ffi_ir_traits__")
+
+
+def has_trait(obj: Object, trait_cls: type[IRTraits] | None = None) -> bool:
+ """Check if obj has a trait (optionally of a specific type)."""
+ t = get_trait(obj)
+ if t is None:
+ return False
+ return trait_cls is None or isinstance(t, trait_cls)
+
+
+def get_type_trait(obj: Object) -> TyTraits | None:
+ """Return the Ty-family trait, or None."""
+ t = get_trait(obj)
+ return t if isinstance(t, TyTraits) else None
diff --git a/python/tvm_ffi/pyast.py b/python/tvm_ffi/pyast.py
new file mode 100644
index 0000000..2a610c5
--- /dev/null
+++ b/python/tvm_ffi/pyast.py
@@ -0,0 +1,2340 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Python-style AST node definitions, printer classes, and rendering utilities.
+
+This module defines the abstract syntax tree (AST) used by the text printer to
+represent Python-style source code. The hierarchy is:
+
+* ``Node`` -- base class for all AST nodes, providing ``to_python()`` and
+ ``print_python()`` methods as well as source-path tracking.
+* ``Expr(Node)`` -- base class for expression nodes (literals, identifiers,
+ attribute access, indexing, calls, operations, etc.). Supports Python
+ operator overloading so that AST fragments can be composed with ``+``,
+ ``-``, ``*``, comparison operators, and more.
+* ``Stmt(Node)`` -- base class for statement nodes (assignments, control flow,
+ function/class definitions, comments, etc.).
+
+Concrete node types correspond closely to the Python AST: ``Literal``, ``Id``,
+``Attr``, ``Index``, ``Call``, ``Operation``, ``Lambda``, ``Tuple``, ``List``,
+``Dict``, ``Slice`` (expressions) and ``StmtBlock``, ``Assign``, ``If``,
+``While``, ``For``, ``With``, ``ExprStmt``, ``Assert``, ``Return``,
+``Function``, ``Class``, ``Comment``, ``DocString`` (statements).
+"""
+
+# ruff: noqa: D102
+# tvm-ffi-stubgen(begin): import-section
+# fmt: off
+# isort: off
+from __future__ import annotations
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+ from collections.abc import MutableMapping, MutableSequence
+ from tvm_ffi import Object
+ from tvm_ffi.access_path import AccessPath
+ from typing import Any, Callable
+# isort: on
+# fmt: on
+# tvm-ffi-stubgen(end)
+
+import contextlib
+from collections.abc import Generator, Sequence
+from typing import Any, TypeVar
+
+from tvm_ffi import Object
+from tvm_ffi.access_path import AccessPath
+from tvm_ffi.dataclasses import c_class
+
+
+@c_class("ffi.pyast.PrinterConfig", init=False)
+class PrinterConfig(Object):
+ """Configuration for the Python-style text printer.
+
+ Controls formatting behavior such as indentation, line numbering, and
+ how free variables and duplicate variable names are handled.
+
+ Attributes
+ ----------
+ def_free_var
+ Whether to automatically define free variables that
+ appear in the output. Default ``True``.
+ indent_spaces
+ Number of spaces per indentation level. Default ``2``.
+ print_line_numbers
+ If greater than zero, prefix each output line with
+ its line number. ``0`` disables line numbers (default).
+ num_context_lines
+ Number of context lines to show around underlined
+ regions when ``path_to_underline`` is set. ``-1`` means show all
+ lines (default).
+ print_addr_on_dup_var
+ When ``True``, append an object address suffix
+ to disambiguate variables that share the same name. Default
+ ``False``.
+ path_to_underline
+ A list of ``AccessPath`` instances identifying
+ sub-expressions to underline in the printed output. Default
+ is an empty list.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ cfg = ast.PrinterConfig(indent_spaces=4, print_line_numbers=1)
+ node = ast.Id(name="x")
+ print(node.to_python(cfg))
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.PrinterConfig
+ # fmt: off
+ def_free_var: bool
+ indent_spaces: int
+ print_line_numbers: int
+ num_context_lines: int
+ print_addr_on_dup_var: bool
+ path_to_underline: MutableSequence[AccessPath]
+ if TYPE_CHECKING:
+ def __init__(self, _0: bool, _1: int, _2: int, _3: int, _4: bool, _5: MutableSequence[AccessPath], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: bool, _1: int, _2: int, _3: int, _4: bool, _5: MutableSequence[AccessPath], /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+ def __init__(
+ self,
+ def_free_var: bool = True,
+ indent_spaces: int = 2,
+ print_line_numbers: int = 0,
+ num_context_lines: int = -1,
+ print_addr_on_dup_var: bool = False,
+ path_to_underline: list[AccessPath] | None = None,
+ ) -> None:
+ """Initialize a PrinterConfig.
+
+ Parameters
+ ----------
+ def_free_var
+ Whether to automatically define free variables. Default ``True``.
+ indent_spaces
+ Number of spaces per indentation level. Default ``2``.
+ print_line_numbers
+ If greater than zero, prefix each output line with its line
+ number. Default ``0``.
+ num_context_lines
+ Number of context lines to show around underlined regions.
+ ``-1`` means show all lines. Default ``-1``.
+ print_addr_on_dup_var
+ When ``True``, append an object address suffix to disambiguate
+ variables that share the same name. Default ``False``.
+ path_to_underline
+ A list of ``AccessPath`` instances identifying sub-expressions
+ to underline. Default ``None`` (empty list).
+
+ """
+ if path_to_underline is None:
+ path_to_underline = []
+ self.__ffi_init__(
+ def_free_var,
+ indent_spaces,
+ print_line_numbers,
+ num_context_lines,
+ print_addr_on_dup_var,
+ path_to_underline,
+ )
+
+
+@c_class("ffi.pyast.Node", init=False)
+class Node(Object):
+ """Base class for all text-printer AST nodes.
+
+ Every AST node carries an optional list of ``source_paths`` that trace
+ the node back to the original IR object it was derived from. The two
+ main entry points for rendering are ``to_python()`` (returns a string)
+ and ``print_python()`` (prints to stdout).
+
+ Attributes
+ ----------
+ source_paths
+ Access paths linking this node to the original IR
+ objects it represents. Default is an empty list.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ node = ast.Id(name="x")
+ source = node.to_python() # "x"
+ node.print_python() # prints "x" to stdout
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Node
+ # fmt: off
+ source_paths: MutableSequence[AccessPath]
+ lineno: int
+ col_offset: int
+ end_lineno: int
+ end_col_offset: int
+ if TYPE_CHECKING:
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ def _to_python(self, _1: PrinterConfig, /) -> str: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+ def to_python(self, config: PrinterConfig | None = None) -> str:
+ """Render this AST node as Python-style source code.
+
+ Parameters
+ ----------
+ config
+ Printer configuration. Uses default settings when ``None``.
+
+ Returns
+ -------
+ source
+ The rendered source code as a string.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ node = ast.Id(name="my_var")
+ node.to_python() # "my_var"
+
+ """
+ if config is None:
+ config = PrinterConfig()
+ return self._to_python(config)
+
+ def print_python(
+ self,
+ config: PrinterConfig | None = None,
+ style: str | None = None,
+ ) -> None:
+ """Print this AST node as Python-style source code to stdout.
+
+ Uses Pygments syntax highlighting when available.
+
+ Parameters
+ ----------
+ config
+ Printer configuration. Uses default settings when ``None``.
+ style
+ Pygments style name or one of ``"light"``, ``"dark"``,
+ ``"ansi"``. Defaults to ``"light"`` in notebooks, ``"ansi"``
+ in terminals.
+
+ """
+ from ._pyast_colored_print import cprint # noqa: PLC0415
+
+ cprint(self.to_python(config), style=style)
+
+ def add_path(self, path: Any) -> Node:
+ """Append a source path to this node and return the node itself.
+
+ This allows chaining, e.g. ``node.add_path(p1).add_path(p2)``.
+
+ Parameters
+ ----------
+ path
+ The access path to append.
+
+ Returns
+ -------
+ self
+ ``self``, for fluent chaining.
+
+ """
+ self.source_paths.append(path)
+ return self
+
+
+@c_class("ffi.pyast.Expr", init=False)
+class Expr(Node):
+ """Base class for expression AST nodes.
+
+ ``Expr`` extends ``Node`` with Python operator overloading and builder
+ methods so that AST fragments can be composed using natural syntax:
+
+ * **Arithmetic**: ``+``, ``-``, ``*``, ``/``, ``//``, ``%``, ``**``
+ * **Bitwise**: ``&``, ``|``, ``^``, ``~``, ``<<``, ``>>``
+ * **Comparison**: ``<``, ``<=``, ``>``, ``>=``, ``.eq()``, ``.ne()``
+ * **Logical**: ``.logical_and()``, ``.logical_or()``
+ * **Ternary**: ``.if_then_else(then, else_)``
+ * **Access**: ``.attr("name")``, ``.index([...])``, ``[...]``
+ * **Calls**: ``.call(*args)``, ``.call_kw(args, keys, values)``
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ x = ast.Id(name="x")
+ y = ast.Id(name="y")
+ expr = (x + y).attr("shape").call(ast.Literal(0))
+ expr.print_python() # (x + y).shape(0)
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Expr
+ # fmt: off
+ source_paths: MutableSequence[AccessPath]
+ if TYPE_CHECKING:
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+ def __neg__(self) -> Expr:
+ return Operation(OperationKind.USub, [self])
+
+ def __invert__(self) -> Expr:
+ return Operation(OperationKind.Invert, [self])
+
+ def __add__(self, other: Expr) -> Expr:
+ return Operation(OperationKind.Add, [self, other])
+
+ def __sub__(self, other: Expr) -> Expr:
+ return Operation(OperationKind.Sub, [self, other])
+
+ def __mul__(self, other: Expr) -> Expr:
+ return Operation(OperationKind.Mult, [self, other])
+
+ def __truediv__(self, other: Expr) -> Expr:
+ return Operation(OperationKind.Div, [self, other])
+
+ def __floordiv__(self, other: Expr) -> Expr:
+ return Operation(OperationKind.FloorDiv, [self, other])
+
+ def __mod__(self, other: Expr) -> Expr:
+ return Operation(OperationKind.Mod, [self, other])
+
+ def __pow__(self, other: Expr) -> Expr:
+ return Operation(OperationKind.Pow, [self, other])
+
+ def __lshift__(self, other: Expr) -> Expr:
+ return Operation(OperationKind.LShift, [self, other])
+
+ def __rshift__(self, other: Expr) -> Expr:
+ return Operation(OperationKind.RShift, [self, other])
+
+ def __and__(self, other: Expr) -> Expr:
+ return Operation(OperationKind.BitAnd, [self, other])
+
+ def __or__(self, other: Expr) -> Expr:
+ return Operation(OperationKind.BitOr, [self, other])
+
+ def __xor__(self, other: Expr) -> Expr:
+ return Operation(OperationKind.BitXor, [self, other])
+
+ def __lt__(self, other: Expr) -> Expr:
+ return Operation(OperationKind.Lt, [self, other])
+
+ def __le__(self, other: Expr) -> Expr:
+ return Operation(OperationKind.LtE, [self, other])
+
+ def __gt__(self, other: Expr) -> Expr:
+ return Operation(OperationKind.Gt, [self, other])
+
+ def __ge__(self, other: Expr) -> Expr:
+ return Operation(OperationKind.GtE, [self, other])
+
+ def logical_and(self, other: Expr) -> Expr:
+ """Build a logical ``and`` operation (``self and other``).
+
+ Python's ``and`` operator cannot be overloaded, so this explicit
+ method is provided instead.
+
+ Parameters
+ ----------
+ other
+ The right-hand operand.
+
+ Returns
+ -------
+ result
+ An ``Operation`` node representing ``self and other``.
+
+ """
+ return Operation(OperationKind.And, [self, other])
+
+ def logical_or(self, other: Expr) -> Expr:
+ """Build a logical ``or`` operation (``self or other``).
+
+ Python's ``or`` operator cannot be overloaded, so this explicit
+ method is provided instead.
+
+ Parameters
+ ----------
+ other
+ The right-hand operand.
+
+ Returns
+ -------
+ result
+ An ``Operation`` node representing ``self or other``.
+
+ """
+ return Operation(OperationKind.Or, [self, other])
+
+ def if_then_else(self, then: Expr, else_: Expr) -> Expr:
+ """Build a ternary conditional expression (``then if self else else_``).
+
+ Parameters
+ ----------
+ then
+ The value when the condition is true.
+ else_
+ The value when the condition is false.
+
+ Returns
+ -------
+ result
+ An ``Operation`` node representing the ternary expression.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ cond = ast.Id(name="flag")
+ result = cond.if_then_else(ast.Literal(1), ast.Literal(0))
+ result.print_python() # 1 if flag else 0
+
+ """
+ return Operation(OperationKind.IfThenElse, [self, then, else_])
+
+ def eq(self, other: Expr) -> Expr:
+ """Build an equality comparison (``self == other``).
+
+ Python's ``__eq__`` is not overloaded to preserve standard object
+ identity semantics, so this explicit method is provided instead.
+
+ Parameters
+ ----------
+ other
+ The right-hand operand.
+
+ Returns
+ -------
+ result
+ An ``Operation`` node representing ``self == other``.
+
+ """
+ return Operation(OperationKind.Eq, [self, other])
+
+ def ne(self, other: Expr) -> Expr:
+ """Build an inequality comparison (``self != other``).
+
+ Python's ``__ne__`` is not overloaded to preserve standard object
+ identity semantics, so this explicit method is provided instead.
+
+ Parameters
+ ----------
+ other
+ The right-hand operand.
+
+ Returns
+ -------
+ result
+ An ``Operation`` node representing ``self != other``.
+
+ """
+ return Operation(OperationKind.NotEq, [self, other])
+
+ def attr(self, name: str) -> Expr:
+ """Build an attribute access expression (``self.name``).
+
+ Parameters
+ ----------
+ name
+ The attribute name.
+
+ Returns
+ -------
+ result
+ An ``Attr`` node representing ``self.name``.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ obj = ast.Id(name="module")
+ obj.attr("forward").print_python() # module.forward
+
+ """
+ return Attr(self, name)
+
+ def index(self, indices: MutableSequence[Expr]) -> Expr:
+ """Build a subscript/index expression (``self[indices]``).
+
+ Parameters
+ ----------
+ indices
+ A sequence of index expressions.
+
+ Returns
+ -------
+ result
+ An ``Index`` node representing ``self[indices]``.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ arr = ast.Id(name="arr")
+ arr.index([ast.Literal(0)]).print_python() # arr[0]
+
+ """
+ return Index(self, indices)
+
+ def call(self, *args: Expr) -> Expr:
+ """Build a positional-only call expression (``self(args...)``).
+
+ Parameters
+ ----------
+ *args
+ Positional argument expressions.
+
+ Returns
+ -------
+ result
+ A ``Call`` node representing ``self(*args)``.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ fn = ast.Id(name="relu")
+ fn.call(ast.Id(name="x")).print_python() # relu(x)
+
+ """
+ return Call(
+ self,
+ args, # ty: ignore[invalid-argument-type]
+ [],
+ [],
+ )
+
+ def call_kw(
+ self,
+ args: Sequence[Expr],
+ kwargs_keys: Sequence[str],
+ kwargs_values: Sequence[Expr],
+ ) -> Expr:
+ """Build a call expression with keyword arguments.
+
+ Renders as ``self(*args, key0=val0, key1=val1, ...)``.
+
+ Parameters
+ ----------
+ args
+ Positional argument expressions.
+ kwargs_keys
+ Keyword argument names.
+ kwargs_values
+ Keyword argument value expressions, in the same
+ order as *kwargs_keys*.
+
+ Returns
+ -------
+ result
+ A ``Call`` node representing the keyword call.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ fn = ast.Id(name="conv2d")
+ fn.call_kw(
+ args=[ast.Id(name="x")],
+ kwargs_keys=["stride"],
+ kwargs_values=[ast.Literal(2)],
+ ).print_python() # conv2d(x, stride=2)
+
+ """
+ if not isinstance(args, Sequence):
+ args = (args,)
+ if not isinstance(kwargs_keys, Sequence):
+ kwargs_keys = (kwargs_keys,)
+ if not isinstance(kwargs_values, Sequence):
+ kwargs_values = (kwargs_values,)
+ return Call(
+ self,
+ args, # ty: ignore[invalid-argument-type]
+ kwargs_keys, # ty: ignore[invalid-argument-type]
+ kwargs_values, # ty: ignore[invalid-argument-type]
+ )
+
+ def __getitem__(self, indices: Expr | Sequence[Expr]) -> Expr:
+ """Build a subscript expression via Python's ``[]`` syntax.
+
+ Delegates to ``self.index()``, wrapping a single index in a tuple
+ if necessary.
+
+ Parameters
+ ----------
+ indices
+ One or more index expressions.
+
+ Returns
+ -------
+ result
+ An ``Index`` node representing ``self[indices]``.
+
+ """
+ if isinstance(indices, Sequence):
+ return self.index(indices) # ty: ignore[invalid-argument-type]
+ return self.index([indices])
+
+
+@c_class("ffi.pyast.Stmt", init=False)
+class Stmt(Node):
+ """Base class for statement AST nodes.
+
+ Statements represent executable constructs (assignments, loops,
+ conditionals, etc.). Every statement may carry an optional trailing
+ ``comment`` that is rendered as ``# comment`` after the statement.
+
+ Attributes
+ ----------
+ comment
+ An optional inline comment string. Default ``None``.
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Stmt
+ # fmt: off
+ source_paths: MutableSequence[AccessPath]
+ comment: str | None
+ if TYPE_CHECKING:
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.StmtBlock")
+class StmtBlock(Stmt):
+ """A sequence of statements rendered as a block.
+
+ Represents a group of statements that are printed together, typically
+ as the body of a function, class, loop, or conditional.
+
+ Attributes
+ ----------
+ stmts
+ The list of statements in this block.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ block = ast.StmtBlock(stmts=[ast.ExprStmt(expr=ast.Id(name="x"))])
+ block.print_python() # x
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.StmtBlock
+ # fmt: off
+ stmts: MutableSequence[Stmt]
+ if TYPE_CHECKING:
+ def __init__(self, _0: MutableSequence[Stmt], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: MutableSequence[Stmt], /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.Literal")
+class Literal(Expr):
+ """A literal value expression (``42``, ``3.14``, ``"hello"``, ``True``, ``None``).
+
+ Wraps an arbitrary Python value and renders it using its ``repr()``.
+
+ Attributes
+ ----------
+ value
+ The literal Python value.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.Literal(42).print_python() # 42
+ ast.Literal("hello").print_python() # "hello"
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Literal
+ # fmt: off
+ value: Any
+ if TYPE_CHECKING:
+ def __init__(self, _0: Any, /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Any, /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.Id")
+class Id(Expr):
+ """An identifier / variable name expression.
+
+ Renders as the bare name string.
+
+ Attributes
+ ----------
+ name
+ The identifier string.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.Id(name="x").print_python() # x
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Id
+ # fmt: off
+ name: str
+ if TYPE_CHECKING:
+ def __init__(self, _0: str, /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: str, /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.Attr")
+class Attr(Expr):
+ """An attribute access expression (``obj.name``).
+
+ Attributes
+ ----------
+ obj
+ The object expression being accessed.
+ name
+ The attribute name.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.Attr(obj=ast.Id(name="self"), name="weight").print_python() # self.weight
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Attr
+ # fmt: off
+ obj: Expr
+ name: str
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr, _1: str, /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr, _1: str, /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.Index")
+class Index(Expr):
+ """A subscript / index expression (``obj[idx0, idx1, ...]``).
+
+ Attributes
+ ----------
+ obj
+ The object expression being indexed.
+ idx
+ A list of index expressions.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.Index(obj=ast.Id(name="x"), idx=[ast.Literal(0)]).print_python() # x[0]
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Index
+ # fmt: off
+ obj: Expr
+ idx: MutableSequence[Expr]
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr, _1: MutableSequence[Expr], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr, _1: MutableSequence[Expr], /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.Call")
+class Call(Expr):
+ """A function call expression (``callee(args..., key=val, ...)``).
+
+ Attributes
+ ----------
+ callee
+ The callable expression.
+ args
+ Positional argument expressions.
+ kwargs_keys
+ Keyword argument names.
+ kwargs_values
+ Keyword argument value expressions, aligned with
+ *kwargs_keys*.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.Call(
+ callee=ast.Id(name="f"),
+ args=[ast.Literal(1)],
+ kwargs_keys=["dim"],
+ kwargs_values=[ast.Literal(0)],
+ ).print_python() # f(1, dim=0)
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Call
+ # fmt: off
+ callee: Expr
+ args: MutableSequence[Expr]
+ kwargs_keys: MutableSequence[str]
+ kwargs_values: MutableSequence[Expr]
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr, _1: MutableSequence[Expr], _2: MutableSequence[str], _3: MutableSequence[Expr], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr, _1: MutableSequence[Expr], _2: MutableSequence[str], _3: MutableSequence[Expr], /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+class OperationKind:
+ """Enum-like class defining operation kinds for ``Operation`` nodes.
+
+ Integer constants are grouped into three ranges:
+
+ * **Unary** (``_UnaryStart`` .. ``_UnaryEnd``): ``USub`` (``-x``),
+ ``Invert`` (``~x``), ``Not`` (``not x``).
+ * **Binary** (``_BinaryStart`` .. ``_BinaryEnd``): arithmetic
+ (``Add``, ``Sub``, ``Mult``, ``Div``, ``FloorDiv``, ``Mod``,
+ ``Pow``), bitwise (``LShift``, ``RShift``, ``BitAnd``, ``BitOr``,
+ ``BitXor``), comparison (``Lt``, ``LtE``, ``Eq``, ``NotEq``,
+ ``Gt``, ``GtE``), and logical (``And``, ``Or``).
+ * **Special** (``_SpecialStart`` .. ``SpecialEnd``): ``IfThenElse``
+ (ternary conditional ``a if cond else b``).
+
+ These constants are used as the ``op`` field of ``Operation`` nodes.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ x = ast.Id(name="x")
+ y = ast.Id(name="y")
+ add_op = ast.Operation(ast.OperationKind.Add, [x, y])
+ add_op.print_python() # x + y
+
+ """
+
+ Undefined = -1
+ _UnaryStart = 0
+ USub = 1
+ Invert = 2
+ Not = 3
+ UAdd = 4
+ _UnaryEnd = 5
+ _BinaryStart = 5
+ Add = 6
+ Sub = 7
+ Mult = 8
+ Div = 9
+ FloorDiv = 10
+ Mod = 11
+ Pow = 12
+ LShift = 13
+ RShift = 14
+ BitAnd = 15
+ BitOr = 16
+ BitXor = 17
+ Lt = 18
+ LtE = 19
+ Eq = 20
+ NotEq = 21
+ Gt = 22
+ GtE = 23
+ And = 24
+ Or = 25
+ MatMult = 26
+ Is = 27
+ IsNot = 28
+ In = 29
+ NotIn = 30
+ _BinaryEnd = 31
+ _SpecialStart = 32
+ IfThenElse = 33
+ ChainedCompare = 34
+ Parens = 35
+ SpecialEnd = 36
+
+
+@c_class("ffi.pyast.Operation")
+class Operation(Expr):
+ """A unary, binary, or special operation expression.
+
+ The ``op`` field is one of the integer constants defined in
+ ``OperationKind``. The ``operands`` list contains one element for
+ unary ops, two for binary ops, or three for ``IfThenElse``.
+
+ Attributes
+ ----------
+ op
+ The operation kind (an ``OperationKind`` constant).
+ operands
+ The operand expressions.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ x = ast.Id(name="x")
+ y = ast.Id(name="y")
+ expr = ast.Operation(ast.OperationKind.Add, [x, y])
+ expr.print_python() # x + y
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Operation
+ # fmt: off
+ op: int
+ operands: MutableSequence[Expr]
+ if TYPE_CHECKING:
+ def __init__(self, _0: int, _1: MutableSequence[Expr], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: int, _1: MutableSequence[Expr], /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.Lambda")
+class Lambda(Expr):
+ """A lambda expression (``lambda args: body``).
+
+ Attributes
+ ----------
+ args
+ The parameter identifiers.
+ body
+ The body expression.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.Lambda(args=[ast.Id(name="x")], body=ast.Id(name="x")).print_python()
+ # lambda x: x
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Lambda
+ # fmt: off
+ args: MutableSequence[Expr]
+ body: Expr
+ if TYPE_CHECKING:
+ def __init__(self, _0: MutableSequence[Expr], _1: Expr, /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: MutableSequence[Expr], _1: Expr, /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.Tuple")
+class Tuple(Expr):
+ """A tuple expression (``(a, b, c)``).
+
+ Attributes
+ ----------
+ values
+ The element expressions.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.Tuple(values=[ast.Literal(1), ast.Literal(2)]).print_python() # (1, 2)
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Tuple
+ # fmt: off
+ values: MutableSequence[Expr]
+ if TYPE_CHECKING:
+ def __init__(self, _0: MutableSequence[Expr], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: MutableSequence[Expr], /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.List")
+class List(Expr):
+ """A list expression (``[a, b, c]``).
+
+ Attributes
+ ----------
+ values
+ The element expressions.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.List(values=[ast.Literal(1), ast.Literal(2)]).print_python() # [1, 2]
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.List
+ # fmt: off
+ values: MutableSequence[Expr]
+ if TYPE_CHECKING:
+ def __init__(self, _0: MutableSequence[Expr], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: MutableSequence[Expr], /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.Dict")
+class Dict(Expr):
+ """A dictionary expression (``{k0: v0, k1: v1, ...}``).
+
+ Attributes
+ ----------
+ keys
+ The key expressions.
+ values
+ The value expressions, aligned with *keys*.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.Dict(
+ keys=[ast.Literal("a")],
+ values=[ast.Literal(1)],
+ ).print_python() # {"a": 1}
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Dict
+ # fmt: off
+ keys: MutableSequence[Expr]
+ values: MutableSequence[Expr]
+ if TYPE_CHECKING:
+ def __init__(self, _0: MutableSequence[Expr], _1: MutableSequence[Expr], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: MutableSequence[Expr], _1: MutableSequence[Expr], /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.Slice", init=False)
+class Slice(Expr):
+ """A slice expression (``start:stop:step``).
+
+ All three components are optional. A ``None`` component is omitted
+ from the rendered output.
+
+ Attributes
+ ----------
+ start
+ The start expression, or ``None``.
+ stop
+ The stop expression, or ``None``.
+ step
+ The step expression, or ``None``.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.Slice(start=ast.Literal(0), stop=ast.Literal(10)).print_python() # 0:10
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Slice
+ # fmt: off
+ start: Expr | None
+ stop: Expr | None
+ step: Expr | None
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr | None, _1: Expr | None, _2: Expr | None, /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr | None, _1: Expr | None, _2: Expr | None, /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+ def __init__(
+ self,
+ start: Expr | None = None,
+ stop: Expr | None = None,
+ step: Expr | None = None,
+ ) -> None:
+ """Initialize a Slice expression.
+
+ Parameters
+ ----------
+ start
+ The start expression, or ``None``. Default ``None``.
+ stop
+ The stop expression, or ``None``. Default ``None``.
+ step
+ The step expression, or ``None``. Default ``None``.
+
+ """
+ self.__ffi_init__(start, stop, step)
+
+
+@c_class("ffi.pyast.Assign", init=False)
+class Assign(Stmt):
+ """An assignment statement (``lhs = rhs`` or ``lhs: annotation = rhs``).
+
+ When ``rhs`` is ``None`` the statement renders as a bare declaration
+ (``lhs: annotation``). When ``annotation`` is ``None`` the type
+ annotation is omitted.
+
+ Attributes
+ ----------
+ lhs
+ The left-hand-side target expression.
+ rhs
+ The right-hand-side value expression, or ``None``.
+ annotation
+ An optional type annotation expression.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.Assign(lhs=ast.Id(name="x"), rhs=ast.Literal(42)).print_python() # x = 42
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Assign
+ # fmt: off
+ lhs: Expr
+ rhs: Expr | None
+ annotation: Expr | None
+ aug_op: int
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr, _1: Expr | None, _2: Expr | None, _3: int, /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr, _1: Expr | None, _2: Expr | None, _3: int, /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+ def __init__(
+ self,
+ lhs: Expr,
+ rhs: Expr | None = None,
+ annotation: Expr | None = None,
+ aug_op: int = -1,
+ ) -> None:
+ """Initialize an Assign statement.
+
+ Parameters
+ ----------
+ lhs
+ The left-hand-side target expression.
+ rhs
+ The right-hand-side value expression, or ``None``.
+ Default ``None``.
+ annotation
+ An optional type annotation expression. Default ``None``.
+ aug_op
+ Augmented-assignment operator kind (``OperationKind`` value),
+ or -1 for plain assignment. Default -1.
+
+ """
+ self.__ffi_init__(lhs, rhs, annotation, aug_op)
+
+
+@c_class("ffi.pyast.If")
+class If(Stmt):
+ """An ``if / elif / else`` conditional statement.
+
+ Attributes
+ ----------
+ cond
+ The condition expression.
+ then_branch
+ Statements executed when the condition is true.
+ else_branch
+ Statements executed when the condition is false
+ (may be empty).
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.If(
+ cond=ast.Id(name="flag"),
+ then_branch=[ast.ExprStmt(expr=ast.Id(name="a"))],
+ else_branch=[ast.ExprStmt(expr=ast.Id(name="b"))],
+ ).print_python()
+ # if flag:
+ # a
+ # else:
+ # b
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.If
+ # fmt: off
+ cond: Expr
+ then_branch: MutableSequence[Stmt]
+ else_branch: MutableSequence[Stmt]
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr, _1: MutableSequence[Stmt], _2: MutableSequence[Stmt], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr, _1: MutableSequence[Stmt], _2: MutableSequence[Stmt], /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.While", init=False)
+class While(Stmt):
+ """A ``while`` loop statement.
+
+ Attributes
+ ----------
+ cond
+ The loop condition expression.
+ body
+ The loop body statements.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.While(
+ cond=ast.Id(name="running"),
+ body=[ast.ExprStmt(expr=ast.Id(name="step"))],
+ ).print_python()
+ # while running:
+ # step
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.While
+ # fmt: off
+ cond: Expr
+ body: MutableSequence[Stmt]
+ orelse: MutableSequence[Stmt]
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr, _1: MutableSequence[Stmt], _2: MutableSequence[Stmt], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr, _1: MutableSequence[Stmt], _2: MutableSequence[Stmt], /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+ def __init__(
+ self,
+ cond: Expr,
+ body: MutableSequence[Stmt],
+ orelse: MutableSequence[Stmt] | None = None,
+ ) -> None:
+ if orelse is None:
+ orelse = []
+ self.__ffi_init__(cond, body, orelse)
+
+
+@c_class("ffi.pyast.For", init=False)
+class For(Stmt):
+ """A ``for`` loop statement (``for lhs in rhs: body``).
+
+ Attributes
+ ----------
+ lhs
+ The loop variable expression.
+ rhs
+ The iterable expression.
+ body
+ The loop body statements.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.For(
+ lhs=ast.Id(name="i"),
+ rhs=ast.Id(name="items"),
+ body=[ast.ExprStmt(expr=ast.Id(name="process"))],
+ ).print_python()
+ # for i in items:
+ # process
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.For
+ # fmt: off
+ lhs: Expr
+ rhs: Expr
+ body: MutableSequence[Stmt]
+ is_async: bool
+ orelse: MutableSequence[Stmt]
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr, _1: Expr, _2: MutableSequence[Stmt], _3: bool, _4: MutableSequence[Stmt], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr, _1: Expr, _2: MutableSequence[Stmt], _3: bool, _4: MutableSequence[Stmt], /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+ def __init__(
+ self,
+ lhs: Expr,
+ rhs: Expr,
+ body: MutableSequence[Stmt],
+ is_async: bool = False,
+ orelse: MutableSequence[Stmt] | None = None,
+ ) -> None:
+ if orelse is None:
+ orelse = []
+ self.__ffi_init__(lhs, rhs, body, is_async, orelse)
+
+
+@c_class("ffi.pyast.With", init=False)
+class With(Stmt):
+ """A ``with`` context-manager statement (``with rhs as lhs: body``).
+
+ When ``lhs`` is ``None``, the ``as lhs`` clause is omitted.
+
+ Attributes
+ ----------
+ lhs
+ The optional target expression (``as`` variable), or ``None``.
+ rhs
+ The context-manager expression.
+ body
+ The body statements.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.With(
+ lhs=ast.Id(name="f"),
+ rhs=ast.Id(name="open_file"),
+ body=[ast.ExprStmt(expr=ast.Id(name="read"))],
+ ).print_python()
+ # with open_file as f:
+ # read
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.With
+ # fmt: off
+ lhs: Expr | None
+ rhs: Expr
+ body: MutableSequence[Stmt]
+ is_async: bool
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr | None, _1: Expr, _2: MutableSequence[Stmt], _3: bool, /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr | None, _1: Expr, _2: MutableSequence[Stmt], _3: bool, /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+ def __init__(
+ self,
+ lhs: Expr | None,
+ rhs: Expr,
+ body: MutableSequence[Stmt],
+ is_async: bool = False,
+ ) -> None:
+ self.__ffi_init__(lhs, rhs, body, is_async)
+
+
+@c_class("ffi.pyast.ExprStmt")
+class ExprStmt(Stmt):
+ """An expression used as a statement (e.g. a bare function call).
+
+ Attributes
+ ----------
+ expr
+ The expression to evaluate as a statement.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.ExprStmt(expr=ast.Id(name="do_something")).print_python() # do_something
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.ExprStmt
+ # fmt: off
+ expr: Expr
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr, /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr, /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.Assert", init=False)
+class Assert(Stmt):
+ """An ``assert`` statement (``assert cond, msg``).
+
+ When ``msg`` is ``None``, only the condition is rendered.
+
+ Attributes
+ ----------
+ cond
+ The condition expression.
+ msg
+ An optional message expression, or ``None``.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.Assert(
+ cond=ast.Id(name="x"), msg=ast.Literal("x must be set")
+ ).print_python()
+ # assert x, "x must be set"
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Assert
+ # fmt: off
+ cond: Expr
+ msg: Expr | None
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr, _1: Expr | None, /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr, _1: Expr | None, /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+ def __init__(
+ self,
+ cond: Expr,
+ msg: Expr | None = None,
+ ) -> None:
+ """Initialize an Assert statement.
+
+ Parameters
+ ----------
+ cond
+ The condition expression.
+ msg
+ An optional message expression, or ``None``. Default ``None``.
+
+ """
+ self.__ffi_init__(cond, msg)
+
+
+@c_class("ffi.pyast.Return")
+class Return(Stmt):
+ """A ``return`` statement.
+
+ When ``value`` is ``None``, renders as a bare ``return``.
+
+ Attributes
+ ----------
+ value
+ The return value expression, or ``None``.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.Return(value=ast.Literal(42)).print_python() # return 42
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Return
+ # fmt: off
+ value: Expr | None
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr | None, /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr | None, /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.Function", init=False)
+class Function(Stmt):
+ """A ``def`` function definition statement.
+
+ Attributes
+ ----------
+ name
+ The function name identifier.
+ args
+ The parameter list, each represented as an ``Assign`` node
+ (the ``lhs`` is the parameter name; ``annotation`` and ``rhs``
+ provide type hints and default values).
+ decorators
+ Decorator expressions applied above the function.
+ return_type
+ An optional return-type annotation expression.
+ body
+ The function body statements.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.Function(
+ name=ast.Id(name="add"),
+ args=[
+ ast.Assign(lhs=ast.Id(name="a")),
+ ast.Assign(lhs=ast.Id(name="b")),
+ ],
+ decorators=[],
+ return_type=None,
+ body=[ast.Return(value=ast.Id(name="a") + ast.Id(name="b"))],
+ ).print_python()
+ # def add(a, b):
+ # return a + b
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Function
+ # fmt: off
+ name: Id
+ args: MutableSequence[Assign]
+ decorators: MutableSequence[Expr]
+ return_type: Expr | None
+ body: MutableSequence[Stmt]
+ is_async: bool
+ if TYPE_CHECKING:
+ def __init__(self, _0: Id, _1: MutableSequence[Assign], _2: MutableSequence[Expr], _3: Expr | None, _4: MutableSequence[Stmt], _5: bool, /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Id, _1: MutableSequence[Assign], _2: MutableSequence[Expr], _3: Expr | None, _4: MutableSequence[Stmt], _5: bool, /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+ def __init__(
+ self,
+ name: Id,
+ args: MutableSequence[Assign],
+ decorators: MutableSequence[Expr],
+ return_type: Expr | None,
+ body: MutableSequence[Stmt],
+ is_async: bool = False,
+ ) -> None:
+ self.__ffi_init__(name, args, decorators, return_type, body, is_async)
+
+
+@c_class("ffi.pyast.Class", init=False)
+class Class(Stmt):
+ """A ``class`` definition statement.
+
+ Attributes
+ ----------
+ name
+ The class name identifier.
+ decorators
+ Decorator expressions applied above the class.
+ body
+ The class body statements.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.Class(
+ name=ast.Id(name="MyClass"),
+ decorators=[],
+ body=[ast.ExprStmt(expr=ast.Id(name="pass"))],
+ ).print_python()
+ # class MyClass:
+ # pass
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Class
+ # fmt: off
+ name: Id
+ bases: MutableSequence[Expr]
+ decorators: MutableSequence[Expr]
+ body: MutableSequence[Stmt]
+ kwargs_keys: MutableSequence[str]
+ kwargs_values: MutableSequence[Expr]
+ if TYPE_CHECKING:
+ def __init__(self, _0: Id, _1: MutableSequence[Expr], _2: MutableSequence[Expr], _3: MutableSequence[Stmt], _4: MutableSequence[str], _5: MutableSequence[Expr], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Id, _1: MutableSequence[Expr], _2: MutableSequence[Expr], _3: MutableSequence[Stmt], _4: MutableSequence[str], _5: MutableSequence[Expr], /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+ def __init__(
+ self,
+ name: Id,
+ bases: MutableSequence[Expr] | None = None,
+ decorators: MutableSequence[Expr] | None = None,
+ body: MutableSequence[Stmt] | None = None,
+ kwargs_keys: MutableSequence[str] | None = None,
+ kwargs_values: MutableSequence[Expr] | None = None,
+ ) -> None:
+ if bases is None:
+ bases = []
+ if decorators is None:
+ decorators = []
+ if body is None:
+ body = []
+ if kwargs_keys is None:
+ kwargs_keys = []
+ if kwargs_values is None:
+ kwargs_values = []
+ self.__ffi_init__(name, bases, decorators, body, kwargs_keys, kwargs_values)
+
+
+@c_class("ffi.pyast.Comment", init=False)
+class Comment(Stmt):
+ """A standalone ``# comment`` line.
+
+ The ``comment`` field (inherited from ``Stmt``) holds the comment text.
+ It is rendered as a full-line comment rather than an inline comment.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.Comment("TODO: refactor this").print_python() # # TODO: refactor this
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Comment
+ # fmt: off
+ if TYPE_CHECKING:
+ def __init__(self, _0: str | None, /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: str | None, /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+ def __init__(self, comment: str | None) -> None:
+ """Initialize a Comment statement.
+
+ Parameters
+ ----------
+ comment
+ The comment text, or ``None``.
+
+ """
+ self.__ffi_init__(comment)
+
+
+@c_class("ffi.pyast.DocString", init=False)
+class DocString(Stmt):
+ r"""A triple-quoted docstring statement.
+
+ Renders as a ``\"\"\"...\"\"\"``. The ``comment`` field (inherited from
+ ``Stmt``) holds the docstring text.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ ast.DocString("This is a docstring.").print_python()
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.DocString
+ # fmt: off
+ if TYPE_CHECKING:
+ def __init__(self, _0: str | None, /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: str | None, /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+ def __init__(self, comment: str | None) -> None:
+ """Initialize a DocString statement.
+
+ Parameters
+ ----------
+ comment
+ The docstring text, or ``None``.
+
+ """
+ self.__ffi_init__(comment)
+
+
+@c_class("ffi.pyast.Set")
+class Set(Expr):
+ """A set expression (``{a, b, c}``).
+
+ Attributes
+ ----------
+ values
+ The element expressions.
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Set
+ # fmt: off
+ values: MutableSequence[Expr]
+ if TYPE_CHECKING:
+ def __init__(self, _0: MutableSequence[Expr], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: MutableSequence[Expr], /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.ComprehensionIter")
+class ComprehensionIter(Node):
+ """One ``for target in iter [if cond]...`` clause in a comprehension.
+
+ Attributes
+ ----------
+ target
+ The loop variable expression.
+ iter
+ The iterable expression.
+ ifs
+ Zero or more filter-condition expressions.
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.ComprehensionIter
+ # fmt: off
+ target: Expr
+ iter: Expr
+ ifs: MutableSequence[Expr]
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr, _1: Expr, _2: MutableSequence[Expr], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr, _1: Expr, _2: MutableSequence[Expr], /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+class ComprehensionKind:
+ """Enum-like class for comprehension kinds."""
+
+ List = 0
+ Set = 1
+ Dict = 2
+ Generator = 3
+
+
+@c_class("ffi.pyast.Comprehension")
+class Comprehension(Expr):
+ """A comprehension expression.
+
+ Covers list comprehensions (``[elt for ...]``), set comprehensions
+ (``{elt for ...}``), dict comprehensions (``{key: value for ...}``),
+ and generator expressions (``(elt for ...)``).
+
+ Attributes
+ ----------
+ kind
+ The comprehension kind (a ``ComprehensionKind`` constant).
+ elt
+ The element expression (or key for dict comprehensions).
+ value
+ The value expression (only for dict comprehensions; ``None`` otherwise).
+ iters
+ The list of ``ComprehensionIter`` clauses.
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Comprehension
+ # fmt: off
+ kind: int
+ elt: Expr
+ value: Expr | None
+ iters: MutableSequence[ComprehensionIter]
+ if TYPE_CHECKING:
+ def __init__(self, _0: int, _1: Expr, _2: Expr | None, _3: MutableSequence[ComprehensionIter], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: int, _1: Expr, _2: Expr | None, _3: MutableSequence[ComprehensionIter], /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.Yield", init=False)
+class Yield(Expr):
+ """A yield expression (``yield value``).
+
+ Attributes
+ ----------
+ value
+ The yielded value, or ``None`` for bare ``yield``.
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Yield
+ # fmt: off
+ value: Expr | None
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr | None, /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr | None, /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+ def __init__(self, value: Expr | None = None) -> None:
+ """Initialize a Yield expression."""
+ self.__ffi_init__(value)
+
+
+@c_class("ffi.pyast.YieldFrom")
+class YieldFrom(Expr):
+ """A yield-from expression (``yield from iterable``).
+
+ Attributes
+ ----------
+ value
+ The iterable to yield from.
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.YieldFrom
+ # fmt: off
+ value: Expr
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr, /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr, /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.StarredExpr")
+class StarredExpr(Expr):
+ """A starred expression (``*value``)."""
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.StarredExpr
+ # fmt: off
+ value: Expr
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr, /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr, /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.Await")
+class AwaitExpr(Expr):
+ """An await expression (``await value``)."""
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Await
+ # fmt: off
+ value: Expr
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr, /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr, /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.WalrusExpr")
+class WalrusExpr(Expr):
+ """A walrus / named expression (``target := value``)."""
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.WalrusExpr
+ # fmt: off
+ target: Expr
+ value: Expr
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr, _1: Expr, /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr, _1: Expr, /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.FStr")
+class FStr(Expr):
+ """An f-string expression (``f"...{x}..."``).
+
+ ``values`` is a list of ``Literal(str)`` for text parts and
+ ``FStrValue`` for interpolated expressions.
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.FStr
+ # fmt: off
+ values: MutableSequence[Expr]
+ if TYPE_CHECKING:
+ def __init__(self, _0: MutableSequence[Expr], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: MutableSequence[Expr], /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.FStrValue", init=False)
+class FStrValue(Expr):
+ """A formatted value inside an f-string (``{value!r:.2f}``)."""
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.FStrValue
+ # fmt: off
+ value: Expr
+ conversion: int
+ format_spec: Expr | None
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr, _1: int, _2: Expr | None, /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr, _1: int, _2: Expr | None, /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+ def __init__(
+ self,
+ value: Expr,
+ conversion: int = -1,
+ format_spec: Expr | None = None,
+ ) -> None:
+ self.__ffi_init__(value, conversion, format_spec)
+
+
+@c_class("ffi.pyast.ExceptHandler")
+class ExceptHandler(Node):
+ """One ``except [Type [as name]]:`` clause in a try statement."""
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.ExceptHandler
+ # fmt: off
+ type: Expr | None
+ name: str | None
+ body: MutableSequence[Stmt]
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr | None, _1: str | None, _2: MutableSequence[Stmt], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr | None, _1: str | None, _2: MutableSequence[Stmt], /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.Try", init=False)
+class Try(Stmt):
+ """A ``try / except / else / finally`` statement."""
+
+ body: MutableSequence[Stmt]
+ handlers: MutableSequence[ExceptHandler]
+ orelse: MutableSequence[Stmt]
+ finalbody: MutableSequence[Stmt]
+
+ def __init__(
+ self,
+ body: MutableSequence[Stmt],
+ handlers: MutableSequence[ExceptHandler],
+ orelse: MutableSequence[Stmt] | None = None,
+ finalbody: MutableSequence[Stmt] | None = None,
+ ) -> None:
+ if orelse is None:
+ orelse = []
+ if finalbody is None:
+ finalbody = []
+ self.__ffi_init__(body, handlers, orelse, finalbody)
+
+
+@c_class("ffi.pyast.MatchCase")
+class MatchCase(Node):
+ """One ``case pattern [if guard]:`` clause in a match statement."""
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.MatchCase
+ # fmt: off
+ pattern: Expr
+ guard: Expr | None
+ body: MutableSequence[Stmt]
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr, _1: Expr | None, _2: MutableSequence[Stmt], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr, _1: Expr | None, _2: MutableSequence[Stmt], /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+@c_class("ffi.pyast.Match")
+class Match(Stmt):
+ """A ``match / case`` statement."""
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.Match
+ # fmt: off
+ subject: Expr
+ cases: MutableSequence[MatchCase]
+ if TYPE_CHECKING:
+ def __init__(self, _0: Expr, _1: MutableSequence[MatchCase], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: Expr, _1: MutableSequence[MatchCase], /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+def from_py(source: Any) -> Node:
+ """Convert a Python source string or ``ast.AST`` node to a TVM-FFI text AST node.
+
+ Parameters
+ ----------
+ source : str | ast.AST
+ Either a Python source string or a Python standard-library ``ast``
+ node to convert.
+
+ Returns
+ -------
+ Node
+ The corresponding TVM-FFI text AST node.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi import pyast
+
+ node = ast.from_py("x + 1")
+ node.print_python() # x + 1
+
+ """
+ from ._pyast_translator import ast_translate # noqa: PLC0415
+
+ return ast_translate(source)
+
+
+@c_class("ffi.pyast.VarInfo")
+class VarInfo(Object):
+ """Metadata for a variable tracked by ``IRPrinter``.
+
+ Attributes
+ ----------
+ name
+ The display name assigned to the variable, or ``None`` if
+ a name has not yet been chosen (see ``var_def_no_name``).
+ creator
+ A ``Function`` callable that, when invoked by the printer,
+ produces the definition site AST for this variable.
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.VarInfo
+ # fmt: off
+ name: str | None
+ creator: Callable[..., Any]
+ if TYPE_CHECKING:
+ def __init__(self, _0: str | None, _1: Callable[..., Any], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: str | None, _1: Callable[..., Any], /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+
+FrameType = TypeVar("FrameType", bound=Object)
+
+
+@c_class("ffi.pyast.DefaultFrame", init=False)
+class DefaultFrame(Object):
+ """The default scoping frame used by ``IRPrinter``.
+
+ A frame collects statements emitted while it is active on the printer's
+ frame stack. ``DefaultFrame`` is the simplest frame type and simply
+ holds a mutable list of ``Stmt`` nodes.
+
+ Attributes
+ ----------
+ stmts
+ The list of statements accumulated in this frame.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ printer = IRPrinter()
+ with printer.with_frame(DefaultFrame()) as frame:
+ # ... emit statements ...
+ pass
+ print(frame.stmts)
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.DefaultFrame
+ # fmt: off
+ stmts: MutableSequence[Stmt]
+ if TYPE_CHECKING:
+ def __init__(self, _0: MutableSequence[Stmt], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: MutableSequence[Stmt], /) -> Object: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+ def __init__(self, stmts: list[Stmt] | None = None) -> None:
+ if stmts is None:
+ stmts = []
+ self.__ffi_init__(stmts)
+
+
+@c_class("ffi.pyast.IRPrinter", init=False)
+class IRPrinter(Object):
+ """Stateful printer that converts TVM FFI objects into text-printer AST nodes.
+
+ ``IRPrinter`` manages variable bindings and a stack of scoping frames.
+ When called on an object, it dispatches to the object's registered
+ printer handler to produce AST nodes, automatically defining and
+ referencing variables as needed.
+
+ Attributes
+ ----------
+ cfg
+ The ``PrinterConfig`` controlling output formatting.
+ obj2info
+ Mapping from IR objects to their ``VarInfo`` metadata.
+ defined_names
+ Mapping from variable name strings to usage counts
+ (used for de-duplication).
+ frames
+ The current stack of scoping frames.
+ frame_vars
+ Mapping from frame objects to the set of variables
+ defined within that frame.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi.pyast import IRPrinter
+ from tvm_ffi.pyast import PrinterConfig
+ from tvm_ffi.access_path import AccessPath
+
+ printer = IRPrinter(PrinterConfig(indent_spaces=4))
+ node = printer(my_obj, AccessPath.root())
+ print(node.to_python())
+
+ """
+
+ # tvm-ffi-stubgen(begin): object/ffi.pyast.IRPrinter
+ # fmt: off
+ cfg: PrinterConfig
+ obj2info: MutableMapping[Any, VarInfo]
+ defined_names: MutableMapping[str, int]
+ frames: MutableSequence[Any]
+ frame_vars: MutableMapping[Any, Any]
+ if TYPE_CHECKING:
+ def __init__(self, _0: PrinterConfig, _1: MutableMapping[Any, VarInfo], _2: MutableMapping[str, int], _3: MutableSequence[Any], _4: MutableMapping[Any, Any], /) -> None: ...
+ def __ffi_shallow_copy__(self, /) -> Object: ...
+ @staticmethod
+ def __c_ffi_init__(_0: PrinterConfig, _1: MutableMapping[Any, VarInfo], _2: MutableMapping[str, int], _3: MutableSequence[Any], _4: MutableMapping[Any, Any], /) -> Object: ...
+ def var_is_defined(self, _1: Object, /) -> bool: ...
+ def var_def(self, _1: str, _2: Object, _3: Object | None, /) -> Id: ...
+ def var_def_no_name(self, _1: Callable[..., Any], _2: Object, _3: Object | None, /) -> None: ...
+ def var_remove(self, _1: Object, /) -> None: ...
+ def var_get(self, _1: Object, /) -> Expr | None: ...
+ def frame_push(self, _1: Object, /) -> None: ...
+ def frame_pop(self, /) -> None: ...
+ def __call__(self, _1: Any, _2: AccessPath, /) -> Any: ...
+ # fmt: on
+ # tvm-ffi-stubgen(end)
+
+ def __init__(self, cfg: PrinterConfig | None = None) -> None:
+ if cfg is None:
+ cfg = PrinterConfig()
+ self.__ffi_init__(cfg, {}, {}, [], {})
+
+ def __call__(self, obj: Any, path: AccessPath) -> Any:
+ """Convert *obj* to a text format AST node using this printer's state.
+
+ Parameters
+ ----------
+ obj
+ The TVM FFI object to convert.
+ path
+ The access path describing how *obj* was reached.
+
+ Returns
+ -------
+ Any
+ The resulting AST node.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ from tvm_ffi.access_path import AccessPath
+
+ printer = IRPrinter()
+ node = printer(my_obj, AccessPath.root())
+
+ """
+ info = type(self).__tvm_ffi_type_info__ # type: ignore[attr-defined]
+ call_fn = next(m.func for m in info.methods if m.name == "__call__")
+ return call_fn(self, obj, path)
+
+ @contextlib.contextmanager
+ def with_frame(self, frame: FrameType) -> Generator[FrameType, None, None]:
+ """Context manager that pushes *frame* and pops it on exit.
+
+ Any variables defined while the frame is active are associated with
+ it and cleaned up when the frame is popped.
+
+ Parameters
+ ----------
+ frame
+ The frame object to activate.
+
+ Yields
+ ------
+ FrameType
+ The same *frame* object, for convenience.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ printer = IRPrinter()
+ with printer.with_frame(DefaultFrame()) as f:
+ # statements emitted here go into f.stmts
+ pass
+
+ """
+ self.frame_push(frame)
+ try:
+ yield frame
+ finally:
+ self.frame_pop()
+
+
+def to_python(obj: Any, cfg: PrinterConfig | None = None) -> str:
+ """Convert any TVM FFI object to Python-style source code."""
+ if cfg is None:
+ cfg = PrinterConfig()
+ printer = IRPrinter(cfg)
+ with printer.with_frame(DefaultFrame()) as frame:
+ ret = printer(obj, AccessPath.root())
+ if not frame.stmts:
+ return ret.to_python(cfg)
+ if isinstance(ret, StmtBlock):
+ frame.stmts.extend(ret.stmts)
+ elif isinstance(ret, Expr):
+ frame.stmts.append(ExprStmt(ret))
+ elif isinstance(ret, Stmt):
+ frame.stmts.append(ret)
+ return StmtBlock(frame.stmts).to_python(cfg)
diff --git a/python/tvm_ffi/testing/testing.py b/python/tvm_ffi/testing/testing.py
index 3cdc288..a62702c 100644
--- a/python/tvm_ffi/testing/testing.py
+++ b/python/tvm_ffi/testing/testing.py
@@ -30,18 +30,44 @@ if TYPE_CHECKING:
# fmt: on
# tvm-ffi-stubgen(end)
-from typing import ClassVar
+import sys
+from typing import Any, ClassVar, List, Optional
+
+import pytest
+
+from tvm_ffi import Object, get_global_func
+from tvm_ffi import ir_traits as traits
+from tvm_ffi import pyast as text
+from tvm_ffi.access_path import AccessPath
+from tvm_ffi.dataclasses import c_class, py_class
+from tvm_ffi.dataclasses import field as dc_field
from .. import _ffi_api
-from ..core import Object
-from ..dataclasses import c_class
-from ..registry import get_global_func
+
+requires_py39 = pytest.mark.skipif(
+ sys.version_info < (3, 9),
+ reason="requires Python 3.9+",
+)
+requires_py310 = pytest.mark.skipif(
+ sys.version_info < (3, 10),
+ reason="requires Python 3.10+",
+)
+requires_py312 = pytest.mark.skipif(
+ sys.version_info < (3, 12),
+ reason="requires Python 3.12+",
+)
+requires_py313 = pytest.mark.skipif(
+ sys.version_info < (3, 13),
+ reason="requires Python 3.13+",
+)
@c_class("testing.TestObjectBase")
class TestObjectBase(Object):
"""Test object base class."""
+ __test__: ClassVar[bool] = False
+
# tvm-ffi-stubgen(begin): object/testing.TestObjectBase
# fmt: off
v_i64: int
@@ -61,7 +87,7 @@ class TestObjectBase(Object):
class TestIntPair(Object):
"""Test Int Pair."""
- __test__ = False
+ __test__: ClassVar[bool] = False
# tvm-ffi-stubgen(begin): object/testing.TestIntPair
# fmt: off
@@ -81,6 +107,8 @@ class TestIntPair(Object):
class TestObjectDerived(TestObjectBase):
"""Test object derived class."""
+ __test__: ClassVar[bool] = False
+
# tvm-ffi-stubgen(begin): object/testing.TestObjectDerived
# fmt: off
v_map: Mapping[Any, Any]
@@ -98,6 +126,8 @@ class TestObjectDerived(TestObjectBase):
class TestNonCopyable(Object):
"""Test object with deleted copy constructor."""
+ __test__: ClassVar[bool] = False
+
# tvm-ffi-stubgen(begin): object/testing.TestNonCopyable
# fmt: off
value: int
@@ -505,3 +535,685 @@ class _TestCxxAutoInitChild(_TestCxxAutoInitParent):
def __c_ffi_init__(*args: Any) -> Any: ...
# fmt: on
# tvm-ffi-stubgen(end)
+
+
+# ============================================================================
+# Toy IR types for text printer tests
+# ============================================================================
+
+
+@py_class("testing.text.toy_ir.Node")
+class ToyNode(Object):
+ """Base class for all toy IR nodes."""
+
+
+@py_class("testing.text.toy_ir.Expr")
+class ToyExpr(ToyNode):
+ """Base class for toy IR expression nodes."""
+
+
+@py_class("testing.text.toy_ir.Stmt")
+class ToyStmt(ToyNode):
+ """Base class for toy IR statement nodes."""
+
+
+@py_class("testing.text.toy_ir.Var", structural_eq="var")
+class ToyVar(ToyExpr):
+ """A variable reference in the toy IR."""
+
+ name: str = dc_field(structural_eq="ignore")
+
+ def __add__(self, other: ToyVar) -> ToyAdd:
+ return ToyAdd(lhs=self, rhs=other)
+
+ def __ffi_text_print__(self, printer: text.IRPrinter, path: AccessPath) -> Any:
+ if not printer.var_is_defined(self):
+ printer.var_def(self.name, self, None)
+ ret = printer.var_get(self)
+ assert ret is not None
+ return ret
+
+
+@py_class("testing.text.toy_ir.Add", structural_eq="dag")
+class ToyAdd(ToyExpr):
+ """Binary addition expression in the toy IR."""
+
+ lhs: ToyExpr
+ rhs: ToyExpr
+
+ def __ffi_text_print__(self, printer: text.IRPrinter, path: AccessPath) -> Any:
+ lhs = printer(self.lhs, path=path.attr("lhs"))
+ rhs = printer(self.rhs, path=path.attr("rhs"))
+ return lhs + rhs
+
+
+@py_class("testing.text.toy_ir.Assign", structural_eq="tree")
+class ToyAssign(ToyStmt):
+ """Assignment statement in the toy IR."""
+
+ rhs: ToyExpr
+ lhs: ToyVar = dc_field(structural_eq="def")
+
+ def __ffi_text_print__(self, printer: text.IRPrinter, path: AccessPath) -> Any:
+ rhs = printer(self.rhs, path=path.attr("rhs"))
+ printer.var_def(self.lhs.name, self.lhs, None)
+ lhs = printer(self.lhs, path=path.attr("lhs"))
+ return text.Assign(lhs, rhs)
+
+
+@py_class("testing.text.toy_ir.Func", structural_eq="tree")
+class ToyFunc(ToyNode):
+ """A function definition in the toy IR."""
+
+ name: str = dc_field(structural_eq="ignore")
+ args: List[ToyVar] = dc_field(structural_eq="def") # noqa: UP006
+ stmts: List[ToyStmt] # noqa: UP006
+ ret: ToyVar
+
+ def __ffi_text_print__(self, printer: text.IRPrinter, path: AccessPath) -> Any:
+ with printer.with_frame(text.DefaultFrame()):
+ for arg in self.args:
+ printer.var_def(arg.name, arg, None)
+ args = [
+ printer(arg, path=path.attr("args").array_item(i))
+ for i, arg in enumerate(self.args)
+ ]
+ stmts = [
+ printer(stmt, path=path.attr("stmts").array_item(i))
+ for i, stmt in enumerate(self.stmts)
+ ]
+ ret_stmt = text.Return(printer(self.ret, path=path.attr("ret")))
+ return text.Function(
+ text.Id(self.name),
+ [text.Assign(arg, None) for arg in args],
+ [],
+ None,
+ [*stmts, ret_stmt],
+ )
+
+
+# ============================================================================
+# Trait-based IR types for trait-driven text printer tests
+# ============================================================================
+
+
+def _trait_region(
+ body: str,
+ def_values: str | None = None,
+ def_expr: str | None = None,
+ ret: str | None = None,
+) -> traits.RegionTraits:
+ """Create a Region with positional convenience."""
+ return traits.RegionTraits(body, def_values, def_expr, ret)
+
+
+@py_class("testing.ir_traits.Expr")
+class TraitToyExpr(Object):
+ """Base expression type for trait tests."""
+
+ __test__: ClassVar[bool] = False
+
+
+@py_class("testing.ir_traits.Stmt")
+class TraitToyStmt(Object):
+ """Base statement type for trait tests."""
+
+ __test__: ClassVar[bool] = False
+
+
+@py_class("testing.ir_traits.Var", structural_eq="var")
+class TraitToyVar(TraitToyExpr):
+ """Variable with Value trait."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.ValueTraits("$field:name", None, None)
+ name: str = dc_field(structural_eq="ignore")
+
+
+@py_class("testing.ir_traits.TypedVar", structural_eq="var")
+class TraitToyTypedVar(TraitToyExpr):
+ """Variable with type annotation."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.ValueTraits("$field:name", "$field:ty", None)
+ name: str = dc_field(structural_eq="ignore")
+ ty: Optional[str] = dc_field(default=None, structural_eq="ignore") # noqa: UP045
+
+
+@py_class("testing.ir_traits.Add", structural_eq="dag")
+class TraitToyAdd(TraitToyExpr):
+ """Binary add expression."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.BinOpTraits("$field:lhs", "$field:rhs", "+", None, None)
+ lhs: TraitToyExpr
+ rhs: TraitToyExpr
+
+
+@py_class("testing.ir_traits.Sub", structural_eq="dag")
+class TraitToySub(TraitToyExpr):
+ """Binary subtract expression."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.BinOpTraits("$field:lhs", "$field:rhs", "-", None, None)
+ lhs: TraitToyExpr
+ rhs: TraitToyExpr
+
+
+@py_class("testing.ir_traits.Mul", structural_eq="dag")
+class TraitToyMul(TraitToyExpr):
+ """Binary multiply expression."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.BinOpTraits("$field:lhs", "$field:rhs", "*", None, None)
+ lhs: TraitToyExpr
+ rhs: TraitToyExpr
+
+
+@py_class("testing.ir_traits.Div", structural_eq="dag")
+class TraitToyDiv(TraitToyExpr):
+ """Binary divide expression."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.BinOpTraits("$field:lhs", "$field:rhs", "/", None, None)
+ lhs: TraitToyExpr
+ rhs: TraitToyExpr
+
+
+@py_class("testing.ir_traits.FloorDiv", structural_eq="dag")
+class TraitToyFloorDiv(TraitToyExpr):
+ """Floor division expression."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.BinOpTraits("$field:lhs", "$field:rhs", "//", None, None)
+ lhs: TraitToyExpr
+ rhs: TraitToyExpr
+
+
+@py_class("testing.ir_traits.Mod", structural_eq="dag")
+class TraitToyMod(TraitToyExpr):
+ """Modulo expression."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.BinOpTraits("$field:lhs", "$field:rhs", "%", None, None)
+ lhs: TraitToyExpr
+ rhs: TraitToyExpr
+
+
+@py_class("testing.ir_traits.Pow", structural_eq="dag")
+class TraitToyPow(TraitToyExpr):
+ """Power expression."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.BinOpTraits("$field:lhs", "$field:rhs", "**", None, None)
+ lhs: TraitToyExpr
+ rhs: TraitToyExpr
+
+
+@py_class("testing.ir_traits.LShift", structural_eq="dag")
+class TraitToyLShift(TraitToyExpr):
+ """Left shift expression."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.BinOpTraits("$field:lhs", "$field:rhs", "<<", None, None)
+ lhs: TraitToyExpr
+ rhs: TraitToyExpr
+
+
+@py_class("testing.ir_traits.RShift", structural_eq="dag")
+class TraitToyRShift(TraitToyExpr):
+ """Right shift expression."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.BinOpTraits("$field:lhs", "$field:rhs", ">>", None, None)
+ lhs: TraitToyExpr
+ rhs: TraitToyExpr
+
+
+@py_class("testing.ir_traits.BitAnd", structural_eq="dag")
+class TraitToyBitAnd(TraitToyExpr):
+ """Bitwise AND expression."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.BinOpTraits("$field:lhs", "$field:rhs", "&", None, None)
+ lhs: TraitToyExpr
+ rhs: TraitToyExpr
+
+
+@py_class("testing.ir_traits.BitOr", structural_eq="dag")
+class TraitToyBitOr(TraitToyExpr):
+ """Bitwise OR expression."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.BinOpTraits("$field:lhs", "$field:rhs", "|", None, None)
+ lhs: TraitToyExpr
+ rhs: TraitToyExpr
+
+
+@py_class("testing.ir_traits.BitXor", structural_eq="dag")
+class TraitToyBitXor(TraitToyExpr):
+ """Bitwise XOR expression."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.BinOpTraits("$field:lhs", "$field:rhs", "^", None, None)
+ lhs: TraitToyExpr
+ rhs: TraitToyExpr
+
+
+@py_class("testing.ir_traits.Lt", structural_eq="dag")
+class TraitToyLt(TraitToyExpr):
+ """Less-than comparison."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.BinOpTraits("$field:lhs", "$field:rhs", "<", None, None)
+ lhs: TraitToyExpr
+ rhs: TraitToyExpr
+
+
+@py_class("testing.ir_traits.LtE", structural_eq="dag")
+class TraitToyLtE(TraitToyExpr):
+ """Less-than-or-equal comparison."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.BinOpTraits("$field:lhs", "$field:rhs", "<=", None, None)
+ lhs: TraitToyExpr
+ rhs: TraitToyExpr
+
+
+@py_class("testing.ir_traits.Eq", structural_eq="dag")
+class TraitToyEq(TraitToyExpr):
+ """Equality comparison."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.BinOpTraits("$field:lhs", "$field:rhs", "==", None, None)
+ lhs: TraitToyExpr
+ rhs: TraitToyExpr
+
+
+@py_class("testing.ir_traits.NotEq", structural_eq="dag")
+class TraitToyNotEq(TraitToyExpr):
+ """Not-equal comparison."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.BinOpTraits("$field:lhs", "$field:rhs", "!=", None, None)
+ lhs: TraitToyExpr
+ rhs: TraitToyExpr
+
+
+@py_class("testing.ir_traits.Gt", structural_eq="dag")
+class TraitToyGt(TraitToyExpr):
+ """Greater-than comparison."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.BinOpTraits("$field:lhs", "$field:rhs", ">", None, None)
+ lhs: TraitToyExpr
+ rhs: TraitToyExpr
+
+
+@py_class("testing.ir_traits.GtE", structural_eq="dag")
+class TraitToyGtE(TraitToyExpr):
+ """Greater-than-or-equal comparison."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.BinOpTraits("$field:lhs", "$field:rhs", ">=", None, None)
+ lhs: TraitToyExpr
+ rhs: TraitToyExpr
+
+
+@py_class("testing.ir_traits.And", structural_eq="dag")
+class TraitToyAnd(TraitToyExpr):
+ """Logical AND expression."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.BinOpTraits("$field:lhs", "$field:rhs", "and", None, None)
+ lhs: TraitToyExpr
+ rhs: TraitToyExpr
+
+
+@py_class("testing.ir_traits.Or", structural_eq="dag")
+class TraitToyOr(TraitToyExpr):
+ """Logical OR expression."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.BinOpTraits("$field:lhs", "$field:rhs", "or", None, None)
+ lhs: TraitToyExpr
+ rhs: TraitToyExpr
+
+
+@py_class("testing.ir_traits.Neg", structural_eq="dag")
+class TraitToyNeg(TraitToyExpr):
+ """Unary negation."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.UnaryOpTraits("$field:x", "-")
+ x: TraitToyExpr
+
+
+@py_class("testing.ir_traits.Invert", structural_eq="dag")
+class TraitToyInvert(TraitToyExpr):
+ """Bitwise invert."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.UnaryOpTraits("$field:x", "~")
+ x: TraitToyExpr
+
+
+@py_class("testing.ir_traits.Not", structural_eq="dag")
+class TraitToyNot(TraitToyExpr):
+ """Logical not."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.UnaryOpTraits("$field:x", "not")
+ x: TraitToyExpr
+
+
+@py_class("testing.ir_traits.Assign", structural_eq="tree")
+class TraitToyAssign(TraitToyStmt):
+ """Assignment statement."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.AssignTraits("$field:target", "$field:value", None, None, None, None)
+ value: TraitToyExpr
+ target: TraitToyVar = dc_field(structural_eq="def")
+
+
+@py_class("testing.ir_traits.TypedAssign", structural_eq="tree")
+class TraitToyTypedAssign(TraitToyStmt):
+ """Assignment with typed variable."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.AssignTraits("$field:target", "$field:value", None, None, None, None)
+ value: TraitToyExpr
+ target: TraitToyTypedVar = dc_field(structural_eq="def")
+
+
+@py_class("testing.ir_traits.Load", structural_eq="dag")
+class TraitToyLoad(TraitToyExpr):
+ """Load from buffer with indices."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.LoadTraits("$field:buf", "$field:indices", None)
+ buf: TraitToyVar
+ indices: List[TraitToyExpr] # noqa: UP006
+
+
+@py_class("testing.ir_traits.ScalarLoad", structural_eq="dag")
+class TraitToyScalarLoad(TraitToyExpr):
+ """Scalar load (no indices)."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.LoadTraits("$field:buf", None, None)
+ buf: TraitToyVar
+
+
+@py_class("testing.ir_traits.Store", structural_eq="tree")
+class TraitToyStore(TraitToyStmt):
+ """Store to buffer with indices."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.StoreTraits("$field:buf", "$field:val", "$field:indices", None)
+ buf: TraitToyVar
+ val: TraitToyExpr
+ indices: List[TraitToyExpr] # noqa: UP006
+
+
+@py_class("testing.ir_traits.ScalarStore", structural_eq="tree")
+class TraitToyScalarStore(TraitToyStmt):
+ """Scalar store (no indices)."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.StoreTraits("$field:buf", "$field:val", None, None)
+ buf: TraitToyVar
+ val: TraitToyExpr
+
+
+@py_class("testing.ir_traits.AssertNode", structural_eq="tree")
+class TraitToyAssertNode(TraitToyStmt):
+ """Assert statement."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.AssertTraits("$field:cond", "$field:msg")
+ cond: TraitToyExpr
+ msg: Optional[str] = None # noqa: UP045
+
+
+@py_class("testing.ir_traits.ReturnNode", structural_eq="tree")
+class TraitToyReturnNode(TraitToyStmt):
+ """Return statement."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.ReturnTraits("$field:val")
+ val: TraitToyExpr
+
+
+@py_class("testing.ir_traits.IfNode", structural_eq="tree")
+class TraitToyIfNode(TraitToyStmt):
+ """If statement."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.IfTraits(
+ "$field:cond",
+ _trait_region("$field:then_body"),
+ None,
+ )
+ cond: TraitToyExpr
+ then_body: List[TraitToyStmt] # noqa: UP006
+
+
+@py_class("testing.ir_traits.IfElseNode", structural_eq="tree")
+class TraitToyIfElseNode(TraitToyStmt):
+ """If-else statement."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.IfTraits(
+ "$field:cond",
+ _trait_region("$field:then_body"),
+ _trait_region("$field:else_body"),
+ )
+ cond: TraitToyExpr
+ then_body: List[TraitToyStmt] # noqa: UP006
+ else_body: List[TraitToyStmt] # noqa: UP006
+
+
+@py_class("testing.ir_traits.ForNode", structural_eq="tree")
+class TraitToyForNode(TraitToyStmt):
+ """For loop statement."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.ForTraits(
+ _trait_region("$field:body", "$field:loop_var"), # region
+ None, # start
+ "$field:extent", # end
+ None, # step
+ None, # def_carry
+ None, # carry_init
+ None, # attrs
+ None, # text_printer_kind
+ )
+ loop_var: TraitToyVar = dc_field(structural_eq="def")
+ extent: int
+ body: List[TraitToyStmt] # noqa: UP006
+
+
+@py_class("testing.ir_traits.ForRangeNode", structural_eq="tree")
+class TraitToyForRangeNode(TraitToyStmt):
+ """For loop with start, end, step."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.ForTraits(
+ _trait_region("$field:body", "$field:loop_var"), # region
+ "$field:start", # start
+ "$field:end", # end
+ "$field:step", # step
+ None, # def_carry
+ None, # carry_init
+ None, # attrs
+ None, # text_printer_kind
+ )
+ loop_var: TraitToyVar = dc_field(structural_eq="def")
+ start: int
+ end: int
+ step: int
+ body: List[TraitToyStmt] # noqa: UP006
+
+
+@py_class("testing.ir_traits.WhileNode", structural_eq="tree")
+class TraitToyWhileNode(TraitToyStmt):
+ """While loop statement."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.WhileTraits(
+ "$field:cond",
+ _trait_region("$field:body"),
+ )
+ cond: TraitToyExpr
+ body: List[TraitToyStmt] # noqa: UP006
+
+
+@py_class("testing.ir_traits.FuncNode", structural_eq="tree")
+class TraitToyFuncNode(Object):
+ """Function definition."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.FuncTraits(
+ "$field:name", # symbol
+ _trait_region("$field:body", "$field:params", None, "$field:ret"), # region
+ None, # attrs
+ None, # text_printer_kind
+ None, # text_printer_pre
+ )
+ name: str = dc_field(structural_eq="ignore")
+ params: List[TraitToyVar] = dc_field(structural_eq="def") # noqa: UP006
+ body: List[TraitToyStmt] # noqa: UP006
+ ret: Optional[TraitToyExpr] = None # noqa: UP045
+
+
+@py_class("testing.ir_traits.DecoratedFunc", structural_eq="tree")
+class TraitToyDecoratedFunc(Object):
+ """Function with decorator (text_printer_kind)."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.FuncTraits(
+ "$field:name", # symbol
+ _trait_region("$field:body", "$field:params"), # region
+ None, # attrs
+ "prim_func", # text_printer_kind (literal)
+ None, # text_printer_pre
+ )
+ name: str = dc_field(structural_eq="ignore")
+ params: List[TraitToyVar] = dc_field(structural_eq="def") # noqa: UP006
+ body: List[TraitToyStmt] # noqa: UP006
+
+
+@py_class("testing.ir_traits.WithNode", structural_eq="tree")
+class TraitToyWithNode(TraitToyStmt):
+ """With statement."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.WithTraits(
+ _trait_region("$field:body", "$field:as_var"), # region
+ None, # def_carry
+ None, # carry_init
+ "launch", # text_printer_kind (literal)
+ None, # text_printer_pre
+ None, # text_printer_post
+ None, # text_printer_no_frame
+ )
+ as_var: TraitToyVar = dc_field(structural_eq="def")
+ body: List[TraitToyStmt] # noqa: UP006
+
+
+@py_class("testing.ir_traits.ModuleNode", structural_eq="tree")
+class TraitToyModuleNode(Object):
+ """Module container."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.FuncTraits(
+ "$field:name", # symbol
+ _trait_region("$field:body"), # region
+ None, # attrs
+ None, # text_printer_kind
+ None, # text_printer_pre
+ )
+ name: str = dc_field(structural_eq="ignore")
+ body: List[Object] # noqa: UP006
+
+
+@py_class("testing.ir_traits.DecoratedModule", structural_eq="tree")
+class TraitToyDecoratedModule(Object):
+ """Module with decorator."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.FuncTraits(
+ "$field:name", # symbol
+ _trait_region("$field:body"), # region
+ None, # attrs
+ "ir_module", # text_printer_kind (literal)
+ None, # text_printer_pre
+ )
+ name: str = dc_field(structural_eq="ignore")
+ body: List[Object] # noqa: UP006
+
+
+@py_class("testing.ir_traits.ClassNode", structural_eq="tree")
+class TraitToyClassNode(Object):
+ """Class definition."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.FuncTraits(
+ "$field:name", # symbol
+ _trait_region("$field:body"), # region
+ None, # bases
+ None, # text_printer_kind
+ None, # text_printer_pre
+ )
+ name: str = dc_field(structural_eq="ignore")
+ body: List[Object] # noqa: UP006
+
+
+# A type with NO trait and NO __ffi_text_print__ (for default/Tier 3)
+@py_class("testing.ir_traits.PlainObj")
+class TraitToyPlainObj(Object):
+ """Object with no trait, for testing Tier 3 default printing."""
+
+ __test__: ClassVar[bool] = False
+ x: int
+ y: str
+
+
+# A type with BOTH __ffi_text_print__ AND __ffi_ir_traits__ (for Tier 1 priority)
+@py_class("testing.ir_traits.OverrideObj", structural_eq="dag")
+class TraitToyOverrideObj(TraitToyExpr):
+ """Object with both manual print and trait -- manual should win."""
+
+ __test__: ClassVar[bool] = False
+ __ffi_ir_traits__ = traits.BinOpTraits("$field:lhs", "$field:rhs", "+", None, None)
+ lhs: TraitToyExpr
+ rhs: TraitToyExpr
+
+ def __ffi_text_print__(self, printer: text.IRPrinter, path: AccessPath) -> Any:
+ lhs = printer(self.lhs, path=path.attr("lhs"))
+ rhs = printer(self.rhs, path=path.attr("rhs"))
+ return lhs + rhs
+
+
+def ast_roundtrip(node: Any) -> str:
+ """Convert a Python AST to TVM-FFI AST and render back to source.
+
+ This function is used by the ``ast-testsuite`` roundtrip checker to
+ validate that ``ast_translate`` + ``to_python()`` produce
+ Python source whose AST matches the original.
+
+ Parameters
+ ----------
+ node
+ A Python ``ast.AST`` node (typically an ``ast.Module``).
+
+ Returns
+ -------
+ source
+ The rendered Python source code.
+
+ """
+ tvm_node = text.from_py(node)
+ return tvm_node.to_python()
diff --git a/src/ffi/extra/pyast_printer.cc b/src/ffi/extra/pyast_printer.cc
new file mode 100644
index 0000000..82640c0
--- /dev/null
+++ b/src/ffi/extra/pyast_printer.cc
@@ -0,0 +1,1942 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/*!
+ * \file src/ffi/extra/pyast_printer.cc
+ * \brief Python-style text printer: converts text format AST to Python source.
+ */
+#include <tvm/ffi/base_details.h>
+#include <tvm/ffi/cast.h>
+#include <tvm/ffi/container/array.h>
+#include <tvm/ffi/container/map.h>
+#include <tvm/ffi/extra/ir_traits.h>
+#include <tvm/ffi/extra/pyast.h>
+#include <tvm/ffi/reflection/accessor.h>
+#include <tvm/ffi/reflection/registry.h>
+#include <tvm/ffi/string.h>
+
+#include <algorithm>
+#include <cctype>
+#include <cmath>
+#include <iomanip>
+#include <map>
+#include <sstream>
+#include <string>
+#include <string_view>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+
+namespace tvm {
+namespace ffi {
+namespace pyast {
+
+// Forward declarations (defined in pyast_trait_print.cc)
+NodeAST TraitPrint(AnyView obj, const ObjectRef& trait, IRPrinter printer, AccessPath path);
+NodeAST DefaultPrint(ObjectRef obj, IRPrinter printer, AccessPath path);
+
+namespace {
+
+// ============================================================================
+// Byte span helpers
+// ============================================================================
+
+using ByteSpan = std::pair<size_t, size_t>;
+
+// ============================================================================
+// DocPrinter — abstract base for rendering the text format AST
+// ============================================================================
+
+class DocPrinter {
+ public:
+ explicit DocPrinter(PrinterConfig options);
+ virtual ~DocPrinter() = default;
+
+ void Append(const NodeAST& doc);
+ void Append(const NodeAST& doc, const PrinterConfig& cfg);
+ String GetString() const;
+
+ protected:
+ void PrintDoc(const NodeAST& doc);
+ virtual void PrintTypedDoc(const LiteralAST& doc) = 0;
+ virtual void PrintTypedDoc(const IdAST& doc) = 0;
+ virtual void PrintTypedDoc(const AttrAST& doc) = 0;
+ virtual void PrintTypedDoc(const IndexAST& doc) = 0;
+ virtual void PrintTypedDoc(const OperationAST& doc) = 0;
+ virtual void PrintTypedDoc(const CallAST& doc) = 0;
+ virtual void PrintTypedDoc(const LambdaAST& doc) = 0;
+ virtual void PrintTypedDoc(const ListAST& doc) = 0;
+ virtual void PrintTypedDoc(const TupleAST& doc) = 0;
+ virtual void PrintTypedDoc(const DictAST& doc) = 0;
+ virtual void PrintTypedDoc(const SliceAST& doc) = 0;
+ virtual void PrintTypedDoc(const StmtBlockAST& doc) = 0;
+ virtual void PrintTypedDoc(const AssignAST& doc) = 0;
+ virtual void PrintTypedDoc(const IfAST& doc) = 0;
+ virtual void PrintTypedDoc(const WhileAST& doc) = 0;
+ virtual void PrintTypedDoc(const ForAST& doc) = 0;
+ virtual void PrintTypedDoc(const WithAST& doc) = 0;
+ virtual void PrintTypedDoc(const ExprStmtAST& doc) = 0;
+ virtual void PrintTypedDoc(const AssertAST& doc) = 0;
+ virtual void PrintTypedDoc(const ReturnAST& doc) = 0;
+ virtual void PrintTypedDoc(const FunctionAST& doc) = 0;
+ virtual void PrintTypedDoc(const ClassAST& doc) = 0;
+ virtual void PrintTypedDoc(const CommentAST& doc) = 0;
+ virtual void PrintTypedDoc(const DocStringAST& doc) = 0;
+ virtual void PrintTypedDoc(const SetAST& doc) = 0;
+ virtual void PrintTypedDoc(const ComprehensionIterAST& doc) = 0;
+ virtual void PrintTypedDoc(const ComprehensionAST& doc) = 0;
+ virtual void PrintTypedDoc(const YieldAST& doc) = 0;
+ virtual void PrintTypedDoc(const YieldFromAST& doc) = 0;
+ virtual void PrintTypedDoc(const StarredExprAST& doc) = 0;
+ virtual void PrintTypedDoc(const AwaitExprAST& doc) = 0;
+ virtual void PrintTypedDoc(const WalrusExprAST& doc) = 0;
+ virtual void PrintTypedDoc(const FStrAST& doc) = 0;
+ virtual void PrintTypedDoc(const FStrValueAST& doc) = 0;
+ virtual void PrintTypedDoc(const ExceptHandlerAST& doc) = 0;
+ virtual void PrintTypedDoc(const TryAST& doc) = 0;
+ virtual void PrintTypedDoc(const MatchCaseAST& doc) = 0;
+ virtual void PrintTypedDoc(const MatchAST& doc) = 0;
+
+ void PrintTypedDoc(const NodeASTObj* doc) {
+ using PrinterVTable =
+ std::unordered_map<int32_t, std::function<void(DocPrinter*, const NodeASTObj*)>>;
+ // clang-format off
+ #define TVM_FFI_PRINTER_VTABLE_ENTRY_(Type) \
+ { Type##Obj::RuntimeTypeIndex(), \
+ [](DocPrinter* printer, const NodeASTObj* d) { \
+ printer->PrintTypedDoc(Type(GetObjectPtr<Type##Obj>( \
+ const_cast<Type##Obj*>(static_cast<const Type##Obj*>(d))))); \
+ } }
+ // clang-format on
+ static PrinterVTable vtable{
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(LiteralAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(IdAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(AttrAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(IndexAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(OperationAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(CallAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(LambdaAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(ListAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(TupleAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(DictAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(SliceAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(StmtBlockAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(AssignAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(IfAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(WhileAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(ForAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(WithAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(ExprStmtAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(AssertAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(ReturnAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(FunctionAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(ClassAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(CommentAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(DocStringAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(SetAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(ComprehensionIterAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(ComprehensionAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(YieldAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(YieldFromAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(StarredExprAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(AwaitExprAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(WalrusExprAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(FStrAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(FStrValueAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(ExceptHandlerAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(TryAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(MatchCaseAST),
+ TVM_FFI_PRINTER_VTABLE_ENTRY_(MatchAST),
+ };
+ // clang-format off
+ #undef TVM_FFI_PRINTER_VTABLE_ENTRY_
+ // clang-format on
+ vtable.at(doc->type_index())(this, doc);
+ }
+
+ void IncreaseIndent() { indent_ += options_->indent_spaces; }
+ void DecreaseIndent() { indent_ -= options_->indent_spaces; }
+ std::ostream& NewLine() {
+ size_t start_pos = output_.tellp();
+ output_ << "\n";
+ line_starts_.push_back(output_.tellp());
+ for (int i = 0; i < indent_; ++i) {
+ output_ << ' ';
+ }
+ size_t end_pos = output_.tellp();
+ underlines_exempted_.emplace_back(start_pos, end_pos);
+ return output_;
+ }
+ std::ostringstream output_;
+ std::vector<ByteSpan> underlines_exempted_;
+
+ private:
+ void MarkSpan(const ByteSpan& span, const AccessPath& path);
+ PrinterConfig options_;
+ int indent_ = 0;
+ std::vector<size_t> line_starts_;
+ List<AccessPath> path_to_underline_;
+ std::vector<std::vector<ByteSpan>> current_underline_candidates_;
+ std::vector<int> current_max_path_length_;
+ std::vector<ByteSpan> underlines_;
+};
+
+// ============================================================================
+// OpKind helpers
+// ============================================================================
+
+inline const char* OpKindToString(OperationASTObj::Kind kind) {
+ switch (kind) {
+ case OperationASTObj::Kind::kUSub:
+ return "-";
+ case OperationASTObj::Kind::kInvert:
+ return "~";
+ case OperationASTObj::Kind::kNot:
+ return "not ";
+ case OperationASTObj::Kind::kUAdd:
+ case OperationASTObj::Kind::kAdd:
+ return "+";
+ case OperationASTObj::Kind::kSub:
+ return "-";
+ case OperationASTObj::Kind::kMult:
+ return "*";
+ case OperationASTObj::Kind::kDiv:
+ return "/";
+ case OperationASTObj::Kind::kFloorDiv:
+ return "//";
+ case OperationASTObj::Kind::kMod:
+ return "%";
+ case OperationASTObj::Kind::kPow:
+ return "**";
+ case OperationASTObj::Kind::kLShift:
+ return "<<";
+ case OperationASTObj::Kind::kRShift:
+ return ">>";
+ case OperationASTObj::Kind::kBitAnd:
+ return "&";
+ case OperationASTObj::Kind::kBitOr:
+ return "|";
+ case OperationASTObj::Kind::kBitXor:
+ return "^";
+ case OperationASTObj::Kind::kLt:
+ return "<";
+ case OperationASTObj::Kind::kLtE:
+ return "<=";
+ case OperationASTObj::Kind::kEq:
+ return "==";
+ case OperationASTObj::Kind::kNotEq:
+ return "!=";
+ case OperationASTObj::Kind::kGt:
+ return ">";
+ case OperationASTObj::Kind::kGtE:
+ return ">=";
+ case OperationASTObj::Kind::kAnd:
+ return "and";
+ case OperationASTObj::Kind::kOr:
+ return "or";
+ case OperationASTObj::Kind::kMatMult:
+ return "@";
+ case OperationASTObj::Kind::kIs:
+ return "is";
+ case OperationASTObj::Kind::kIsNot:
+ return "is not";
+ case OperationASTObj::Kind::kIn:
+ return "in";
+ case OperationASTObj::Kind::kNotIn:
+ return "not in";
+ default:
+ TVM_FFI_THROW(ValueError) << "Unknown operation kind: " << static_cast<int>(kind);
+ }
+ TVM_FFI_UNREACHABLE();
+}
+
+inline const char* OpKindToString(int64_t kind) {
+ return OpKindToString(static_cast<OperationASTObj::Kind>(kind));
+}
+
+// ============================================================================
+// ExprPrecedence
+// ============================================================================
+
+/*!
+ * \brief Operator precedence based on
+ * https://docs.python.org/3/reference/expressions.html#operator-precedence
+ */
+enum class ExprPrecedence : int32_t {
+ /*! \brief Unknown precedence */
+ kUnkown = 0,
+ /*! \brief Lambda Expression */
+ kLambda = 1,
+ /*! \brief Conditional Expression */
+ kIfThenElse = 2,
+ /*! \brief Boolean OR */
+ kBooleanOr = 3,
+ /*! \brief Boolean AND */
+ kBooleanAnd = 4,
+ /*! \brief Boolean NOT */
+ kBooleanNot = 5,
+ /*! \brief Comparisons */
+ kComparison = 6,
+ /*! \brief Bitwise OR */
+ kBitwiseOr = 7,
+ /*! \brief Bitwise XOR */
+ kBitwiseXor = 8,
+ /*! \brief Bitwise AND */
+ kBitwiseAnd = 9,
+ /*! \brief Shift Operators */
+ kShift = 10,
+ /*! \brief Addition and subtraction */
+ kAdd = 11,
+ /*! \brief Multiplication, division, floor division, remainder */
+ kMult = 12,
+ /*! \brief Positive negative and bitwise NOT */
+ kUnary = 13,
+ /*! \brief Exponentiation */
+ kExp = 14,
+ /*! \brief Index access, attribute access, call and atom expression */
+ kIdentity = 15,
+};
+
+inline ExprPrecedence GetExprPrecedence(const ExprAST& doc) {
+ // Key is the type index of Doc
+ static const std::unordered_map<uint32_t, ExprPrecedence> doc_type_precedence = {
+ {LiteralASTObj::RuntimeTypeIndex(), ExprPrecedence::kIdentity},
+ {IdASTObj::RuntimeTypeIndex(), ExprPrecedence::kIdentity},
+ {AttrASTObj::RuntimeTypeIndex(), ExprPrecedence::kIdentity},
+ {IndexASTObj::RuntimeTypeIndex(), ExprPrecedence::kIdentity},
+ {CallASTObj::RuntimeTypeIndex(), ExprPrecedence::kIdentity},
+ {LambdaASTObj::RuntimeTypeIndex(), ExprPrecedence::kLambda},
+ {TupleASTObj::RuntimeTypeIndex(), ExprPrecedence::kIdentity},
+ {ListASTObj::RuntimeTypeIndex(), ExprPrecedence::kIdentity},
+ {DictASTObj::RuntimeTypeIndex(), ExprPrecedence::kIdentity},
+ {SetASTObj::RuntimeTypeIndex(), ExprPrecedence::kIdentity},
+ {ComprehensionASTObj::RuntimeTypeIndex(), ExprPrecedence::kIdentity},
+ {YieldASTObj::RuntimeTypeIndex(), ExprPrecedence::kLambda},
+ {YieldFromASTObj::RuntimeTypeIndex(), ExprPrecedence::kLambda},
+ {StarredExprASTObj::RuntimeTypeIndex(), ExprPrecedence::kUnary},
+ {AwaitExprASTObj::RuntimeTypeIndex(), ExprPrecedence::kUnary},
+ {WalrusExprASTObj::RuntimeTypeIndex(), ExprPrecedence::kLambda},
+ {FStrASTObj::RuntimeTypeIndex(), ExprPrecedence::kIdentity},
+ {FStrValueASTObj::RuntimeTypeIndex(), ExprPrecedence::kIdentity},
+ };
+ // Key is the value of OperationASTObj::Kind
+ static const std::vector<ExprPrecedence> op_kind_precedence = []() {
+ using OpKind = OperationASTObj::Kind;
+ std::map<OpKind, ExprPrecedence> raw_table = {
+ {OpKind::kUSub, ExprPrecedence::kUnary},
+ {OpKind::kInvert, ExprPrecedence::kUnary},
+ {OpKind::kNot, ExprPrecedence::kBooleanNot},
+ {OpKind::kUAdd, ExprPrecedence::kUnary},
+ {OpKind::kAdd, ExprPrecedence::kAdd},
+ {OpKind::kSub, ExprPrecedence::kAdd},
+ {OpKind::kMult, ExprPrecedence::kMult},
+ {OpKind::kDiv, ExprPrecedence::kMult},
+ {OpKind::kFloorDiv, ExprPrecedence::kMult},
+ {OpKind::kMod, ExprPrecedence::kMult},
+ {OpKind::kPow, ExprPrecedence::kExp},
+ {OpKind::kLShift, ExprPrecedence::kShift},
+ {OpKind::kRShift, ExprPrecedence::kShift},
+ {OpKind::kBitAnd, ExprPrecedence::kBitwiseAnd},
+ {OpKind::kBitOr, ExprPrecedence::kBitwiseOr},
+ {OpKind::kBitXor, ExprPrecedence::kBitwiseXor},
+ {OpKind::kLt, ExprPrecedence::kComparison},
+ {OpKind::kLtE, ExprPrecedence::kComparison},
+ {OpKind::kEq, ExprPrecedence::kComparison},
+ {OpKind::kNotEq, ExprPrecedence::kComparison},
+ {OpKind::kGt, ExprPrecedence::kComparison},
+ {OpKind::kGtE, ExprPrecedence::kComparison},
+ {OpKind::kAnd, ExprPrecedence::kBooleanAnd},
+ {OpKind::kOr, ExprPrecedence::kBooleanOr},
+ {OpKind::kMatMult, ExprPrecedence::kMult},
+ {OpKind::kIs, ExprPrecedence::kComparison},
+ {OpKind::kIsNot, ExprPrecedence::kComparison},
+ {OpKind::kIn, ExprPrecedence::kComparison},
+ {OpKind::kNotIn, ExprPrecedence::kComparison},
+ {OpKind::kIfThenElse, ExprPrecedence::kIfThenElse},
+ {OpKind::kChainedCompare, ExprPrecedence::kComparison},
+ {OpKind::kParens, ExprPrecedence::kIdentity},
+ };
+ std::vector<ExprPrecedence> table(static_cast<size_t>(OpKind::kSpecialEnd) + 1,
+ ExprPrecedence::kUnkown);
+ for (const auto& kv : raw_table) {
+ table[static_cast<int>(kv.first)] = kv.second;
+ }
+ return table;
+ }();
+ if (const auto* op_doc =
+ doc->IsInstance<OperationASTObj>() ? doc.as<OperationASTObj>() : nullptr) {
+ ExprPrecedence precedence = op_kind_precedence.at(op_doc->op);
+ if (precedence == ExprPrecedence::kUnkown) {
+ TVM_FFI_THROW(ValueError) << "Unknown precedence for operator: " << op_doc->op;
+ }
+ return precedence;
+ } else if (auto it = doc_type_precedence.find(doc->type_index());
+ it != doc_type_precedence.end()) {
+ return it->second;
+ }
+ TVM_FFI_THROW(ValueError) << "Unknown precedence for doc type: " << doc->GetTypeKey();
+ TVM_FFI_UNREACHABLE();
+}
+
+// ============================================================================
+// Span / underline helpers
+// ============================================================================
+
+inline std::vector<ByteSpan> MergeAndExemptSpans(const std::vector<ByteSpan>& spans,
+ const std::vector<ByteSpan>& spans_exempted) {
+ std::vector<ByteSpan> res;
+ std::vector<std::pair<size_t, int>> prefix_stamp;
+ for (ByteSpan span : spans) {
+ prefix_stamp.emplace_back(span.first, 1);
+ prefix_stamp.emplace_back(span.second, -1);
+ }
+ int max_n = static_cast<int>(spans.size()) + 1;
+ for (ByteSpan span : spans_exempted) {
+ prefix_stamp.emplace_back(span.first, -max_n);
+ prefix_stamp.emplace_back(span.second, max_n);
+ }
+ std::sort(prefix_stamp.begin(), prefix_stamp.end());
+ int prefix_sum = 0;
+ int n = static_cast<int>(prefix_stamp.size());
+ for (int i = 0; i < n - 1; ++i) {
+ prefix_sum += prefix_stamp[i].second;
+ if (prefix_sum > 0 && prefix_stamp[i].first < prefix_stamp[i + 1].first) {
+ if (res.size() && res.back().second == prefix_stamp[i].first) {
+ res.back().second = prefix_stamp[i + 1].first;
+ } else {
+ res.emplace_back(prefix_stamp[i].first, prefix_stamp[i + 1].first);
+ }
+ }
+ }
+ return res;
+}
+
+inline size_t GetTextWidth(const String& text, const ByteSpan& span) {
+ // FIXME: this only works for ASCII characters.
+ size_t ret = 0;
+ for (size_t i = span.first; i != span.second; ++i) {
+ if (isprint(text.data()[i])) {
+ ret += 1;
+ }
+ }
+ return ret;
+}
+
+inline size_t MoveBack(size_t pos, size_t distance) { return distance > pos ? 0 : pos - distance; }
+
+inline size_t MoveForward(size_t pos, size_t distance, size_t max) {
+ return distance > max - pos ? max : pos + distance;
+}
+
+inline size_t GetLineIndex(size_t byte_pos, const std::vector<size_t>& line_starts) {
+ auto it = std::upper_bound(line_starts.begin(), line_starts.end(), byte_pos);
+ return (it - line_starts.begin()) - 1;
+}
+
+using UnderlineIter = typename std::vector<ByteSpan>::const_iterator;
+
+inline ByteSpan PopNextUnderline(UnderlineIter* next_underline, UnderlineIter end_underline) {
+ if (*next_underline == end_underline) {
+ constexpr size_t kMaxSizeT = 18446744073709551615U;
+ return {kMaxSizeT, kMaxSizeT};
+ } else {
+ return *(*next_underline)++;
+ }
+}
+
+inline void PrintChunk(const std::pair<size_t, size_t>& lines_range,
+ const std::pair<UnderlineIter, UnderlineIter>& underlines,
+ const String& text, const std::vector<size_t>& line_starts,
+ const PrinterConfig& options, size_t line_number_width,
+ std::ostringstream* out) {
+ UnderlineIter next_underline = underlines.first;
+ ByteSpan current_underline = PopNextUnderline(&next_underline, underlines.second);
+
+ for (size_t line_idx = lines_range.first; line_idx < lines_range.second; ++line_idx) {
+ if (options->print_line_numbers) {
+ (*out) << std::setw(static_cast<int>(line_number_width)) << std::right
+ << std::to_string(line_idx + 1) << ' ';
+ }
+ size_t line_start = line_starts.at(line_idx);
+ size_t line_end =
+ line_idx + 1 == line_starts.size() ? text.size() : line_starts.at(line_idx + 1);
+ (*out) << std::string_view(text.data() + line_start, line_end - line_start);
+ bool printed_underline = false;
+ size_t line_pos = line_start;
+ bool printed_extra_caret = false;
+ while (current_underline.first < line_end) {
+ if (!printed_underline) {
+ for (size_t i = 0; i < line_number_width; ++i) {
+ (*out) << ' ';
+ }
+ printed_underline = true;
+ }
+ size_t underline_end_for_line = std::min<size_t>(line_end, current_underline.second);
+ size_t num_spaces = GetTextWidth(text, {line_pos, current_underline.first});
+ if (num_spaces > 0 && printed_extra_caret) {
+ num_spaces -= 1;
+ printed_extra_caret = false;
+ }
+ for (size_t i = 0; i < num_spaces; ++i) {
+ (*out) << ' ';
+ }
+ size_t num_carets = GetTextWidth(text, {current_underline.first, underline_end_for_line});
+ if (num_carets == 0 && !printed_extra_caret) {
+ num_carets = 1;
+ printed_extra_caret = true;
+ } else if (num_carets > 0 && printed_extra_caret) {
+ num_carets -= 1;
+ printed_extra_caret = false;
+ }
+ for (size_t i = 0; i < num_carets; ++i) {
+ (*out) << '^';
+ }
+ line_pos = current_underline.first = underline_end_for_line;
+ if (current_underline.first == current_underline.second) {
+ current_underline = PopNextUnderline(&next_underline, underlines.second);
+ }
+ }
+ if (printed_underline) {
+ (*out) << '\n';
+ }
+ }
+}
+
+inline void PrintCut(size_t num_lines_skipped, std::ostringstream* out) {
+ if (num_lines_skipped != 0) {
+ (*out) << "(... " << num_lines_skipped << " lines skipped ...)\n";
+ }
+}
+
+inline std::pair<size_t, size_t> GetLinesForUnderline(const ByteSpan& underline,
+ const std::vector<size_t>& line_starts,
+ size_t num_lines,
+ const PrinterConfig& options) {
+ size_t first_line_of_underline = GetLineIndex(underline.first, line_starts);
+ size_t first_line_of_chunk = MoveBack(first_line_of_underline, options->num_context_lines);
+ size_t end_line_of_underline = GetLineIndex(underline.second - 1, line_starts) + 1;
+ size_t end_line_of_chunk =
+ MoveForward(end_line_of_underline, options->num_context_lines, num_lines);
+ return {first_line_of_chunk, end_line_of_chunk};
+}
+
+constexpr const size_t kMinLinesToCutOut = 2;
+
+inline bool TryMergeChunks(std::pair<size_t, size_t>* cur_chunk,
+ const std::pair<size_t, size_t>& new_chunk) {
+ if (new_chunk.first < cur_chunk->second + kMinLinesToCutOut) {
+ cur_chunk->second = new_chunk.second;
+ return true;
+ } else {
+ return false;
+ }
+}
+
+inline size_t GetNumLines(const String& text, const std::vector<size_t>& line_starts) {
+ if (static_cast<int64_t>(line_starts.back()) == static_cast<int64_t>(text.size())) {
+ return line_starts.size() - 1;
+ } else {
+ return line_starts.size();
+ }
+}
+
+inline size_t GetLineNumberWidth(size_t num_lines, const PrinterConfig& options) {
+ if (options->print_line_numbers) {
+ return std::to_string(num_lines).size() + 1;
+ } else {
+ return 0;
+ }
+}
+
+inline String DecorateText(const String& text, const std::vector<size_t>& line_starts,
+ const PrinterConfig& options, const std::vector<ByteSpan>& underlines) {
+ size_t num_lines = GetNumLines(text, line_starts);
+ size_t line_number_width = GetLineNumberWidth(num_lines, options);
+
+ std::ostringstream ret;
+ if (underlines.empty()) {
+ PrintChunk({0, num_lines}, {underlines.begin(), underlines.begin()}, text, line_starts, options,
+ line_number_width, &ret);
+ return String(ret.str());
+ }
+
+ size_t last_end_line = 0;
+ std::pair<size_t, size_t> cur_chunk =
+ GetLinesForUnderline(underlines[0], line_starts, num_lines, options);
+ if (cur_chunk.first < kMinLinesToCutOut) {
+ cur_chunk.first = 0;
+ }
+
+ auto first_underline_in_cur_chunk = underlines.begin();
+ for (auto underline_it = underlines.begin() + 1; underline_it != underlines.end();
+ ++underline_it) {
+ std::pair<size_t, size_t> new_chunk =
+ GetLinesForUnderline(*underline_it, line_starts, num_lines, options);
+ if (!TryMergeChunks(&cur_chunk, new_chunk)) {
+ PrintCut(cur_chunk.first - last_end_line, &ret);
+ PrintChunk(cur_chunk, {first_underline_in_cur_chunk, underline_it}, text, line_starts,
+ options, line_number_width, &ret);
+ last_end_line = cur_chunk.second;
+ cur_chunk = new_chunk;
+ first_underline_in_cur_chunk = underline_it;
+ }
+ }
+
+ PrintCut(cur_chunk.first - last_end_line, &ret);
+ if (num_lines - cur_chunk.second < kMinLinesToCutOut) {
+ cur_chunk.second = num_lines;
+ }
+ PrintChunk(cur_chunk, {first_underline_in_cur_chunk, underlines.end()}, text, line_starts,
+ options, line_number_width, &ret);
+ PrintCut(num_lines - cur_chunk.second, &ret);
+ return String(ret.str());
+}
+
+// ============================================================================
+// DocPrinter implementation
+// ============================================================================
+
+inline DocPrinter::DocPrinter(PrinterConfig options) : options_(std::move(options)) {
+ line_starts_.push_back(0);
+}
+
+inline void DocPrinter::Append(const NodeAST& doc) { Append(doc, PrinterConfig()); }
+
+inline void DocPrinter::Append(const NodeAST& doc, const PrinterConfig& cfg) {
+ for (AccessPath p : cfg->path_to_underline) {
+ path_to_underline_.push_back(p);
+ current_max_path_length_.push_back(0);
+ current_underline_candidates_.emplace_back();
+ }
+ PrintDoc(doc);
+ for (const auto& c : current_underline_candidates_) {
+ underlines_.insert(underlines_.end(), c.begin(), c.end());
+ }
+}
+
+inline String DocPrinter::GetString() const {
+ std::string text = output_.str();
+ // Remove any trailing indentation
+ while (!text.empty() && text.back() == ' ') {
+ text.pop_back();
+ }
+ if (!text.empty() && text.back() != '\n') {
+ text.push_back('\n');
+ }
+ String text_str(text);
+ return DecorateText(text_str, line_starts_, options_,
+ MergeAndExemptSpans(underlines_, underlines_exempted_));
+}
+
+inline void DocPrinter::PrintDoc(const NodeAST& doc) {
+ size_t start_pos = output_.tellp();
+ this->PrintTypedDoc(doc.get());
+ size_t end_pos = output_.tellp();
+ for (AccessPath path : doc->source_paths) {
+ MarkSpan({start_pos, end_pos}, path);
+ }
+}
+
+inline void DocPrinter::MarkSpan(const ByteSpan& span, const AccessPath& path) {
+ int n = static_cast<int>(path_to_underline_.size());
+ for (int i = 0; i < n; ++i) {
+ AccessPath p = path_to_underline_[i];
+ if (path->depth >= current_max_path_length_[i] && path->IsPrefixOf(p)) {
+ if (path->depth > current_max_path_length_[i]) {
+ current_max_path_length_[i] = static_cast<int>(path->depth);
+ current_underline_candidates_[i].clear();
+ }
+ current_underline_candidates_[i].push_back(span);
+ }
+ }
+}
+
+// ============================================================================
+// PythonDocPrinter
+// ============================================================================
+
+class PythonDocPrinter : public DocPrinter {
+ public:
+ explicit PythonDocPrinter(const PrinterConfig& options) : DocPrinter(options) {}
+
+ protected:
+ using DocPrinter::PrintDoc;
+
+ void PrintTypedDoc(const LiteralAST& doc) final;
+ void PrintTypedDoc(const IdAST& doc) final;
+ void PrintTypedDoc(const AttrAST& doc) final;
+ void PrintTypedDoc(const IndexAST& doc) final;
+ void PrintTypedDoc(const OperationAST& doc) final;
+ void PrintTypedDoc(const CallAST& doc) final;
+ void PrintTypedDoc(const LambdaAST& doc) final;
+ void PrintTypedDoc(const ListAST& doc) final;
+ void PrintTypedDoc(const DictAST& doc) final;
+ void PrintTypedDoc(const TupleAST& doc) final;
+ void PrintTypedDoc(const SliceAST& doc) final;
+ void PrintTypedDoc(const StmtBlockAST& doc) final;
+ void PrintTypedDoc(const AssignAST& doc) final;
+ void PrintTypedDoc(const IfAST& doc) final;
+ void PrintTypedDoc(const WhileAST& doc) final;
+ void PrintTypedDoc(const ForAST& doc) final;
+ void PrintTypedDoc(const ExprStmtAST& doc) final;
+ void PrintTypedDoc(const AssertAST& doc) final;
+ void PrintTypedDoc(const ReturnAST& doc) final;
+ void PrintTypedDoc(const WithAST& doc) final;
+ void PrintTypedDoc(const FunctionAST& doc) final;
+ void PrintTypedDoc(const ClassAST& doc) final;
+ void PrintTypedDoc(const CommentAST& doc) final;
+ void PrintTypedDoc(const DocStringAST& doc) final;
+ void PrintTypedDoc(const SetAST& doc) final;
+ void PrintTypedDoc(const ComprehensionIterAST& doc) final;
+ void PrintTypedDoc(const ComprehensionAST& doc) final;
+ void PrintTypedDoc(const YieldAST& doc) final;
+ void PrintTypedDoc(const YieldFromAST& doc) final;
+ void PrintTypedDoc(const StarredExprAST& doc) final;
+ void PrintTypedDoc(const AwaitExprAST& doc) final;
+ void PrintTypedDoc(const WalrusExprAST& doc) final;
+ void PrintTypedDoc(const FStrAST& doc) final;
+ void PrintTypedDoc(const FStrValueAST& doc) final;
+ void PrintTypedDoc(const ExceptHandlerAST& doc) final;
+ void PrintTypedDoc(const TryAST& doc) final;
... 6654 lines suppressed ...