Skip to main content

tvm_tirx/
script.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20//! TVMScript printing. [`script`] prints an IR object as TVMScript, the Python-syntax text form
21//! of the IR.
22
23// tvm-ffi-stubgen(file): mod(missing_docs = allow)
24// Names the hand-written wrappers use: the import section keeps them even when no generated block
25// does.
26// tvm-ffi-stubgen(import): tvm_ffi::AnyCompatible
27// tvm-ffi-stubgen(import): tvm_ffi::AnyView
28// tvm-ffi-stubgen(import): tvm_ffi::ObjectRefCore
29// tvm-ffi-stubgen(import): tvm_ffi::Result
30// tvm-ffi-stubgen(import): tvm_ffi::String
31
32// tvm-ffi-stubgen(begin): import-section
33use tvm_ffi::AnyCompatible;
34use tvm_ffi::AnyView;
35use tvm_ffi::ObjectRefCore;
36use tvm_ffi::Result;
37use tvm_ffi::String;
38// tvm-ffi-stubgen(end)
39
40/// Print the IR object `obj` as TVMScript, with the default printer config
41/// (`script.printer.Script`).
42///
43/// # Examples
44///
45/// ```
46/// use tvm_tirx::ir::{
47///     DictAttrs, Expr, PrimExpr, PrimType, PrimVar, Return, SeqStmt, Var, UNKNOWN_LOC,
48/// };
49/// use tvm_tirx::script::script;
50/// use tvm_tirx::tirx::Function;
51/// use tvm_tirx::tvm_ffi::Map;
52///
53/// let x = PrimVar::new("x", PrimType::int(32), UNKNOWN_LOC);
54/// assert_eq!(script(&PrimExpr::try_from(&x * 2 + 1)?)?, "x * 2 + 1");
55///
56/// let body = SeqStmt::new([Return::new(Expr::try_from(&x + 1)?, UNKNOWN_LOC)], UNKNOWN_LOC);
57/// let attrs = DictAttrs::new(Map::new());
58/// let func = Function::new([&x], &body, PrimType::int(32), attrs, UNKNOWN_LOC);
59/// let text = script(&func)?;
60/// assert!(text.contains("def main(x: T.int32) -> T.int32:\n    return x + 1"));
61/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
62/// ```
63pub fn script<T: ObjectRefCore + AnyCompatible>(obj: &T) -> Result<String> {
64    tvm_ffi::cached_global_func!("script.printer.Script")
65        .call_packed(&[AnyView::from(obj), AnyView::new()])?
66        .try_into()
67}