23#ifndef TVM_SCRIPT_PRINTER_DOC_TRANSLATOR_H_
24#define TVM_SCRIPT_PRINTER_DOC_TRANSLATOR_H_
26#include <tvm/ffi/container/dict.h>
27#include <tvm/ffi/container/list.h>
28#include <tvm/ffi/container/map.h>
29#include <tvm/ffi/expected.h>
30#include <tvm/ffi/reflection/accessor.h>
42class DocTranslatorObj;
57 const ffi::Object* destination)
noexcept;
73 bool explicit_def)
noexcept;
104using FDocTranslate = ffi::reflection::NativeFunctionView<ffi::Optional<ExprDoc>(
105 DocTranslatorObj* translator, ffi::AnyView value,
const ffi::Object* destination)>;
135 const ffi::Optional<Var> bind_var = std::nullopt) {
136 auto result = ffi::detail::ExpectedUnsafe::MoveFromTVMFFIAny<ffi::Optional<ExprDoc>>(
138 bind_var.has_value() ? bind_var.value().get() :
nullptr))
140 if (result.has_value()) {
141 if (
const auto* origin = value.as<ffi::Object>()) {
142 RecordOrigin(result.value(), ffi::GetRef<ffi::ObjectRef>(origin));
152 void Emit(
const Doc& doc, ffi::Optional<ffi::ObjectRef> origin = std::nullopt) {
154 if (origin.has_value())
RecordOrigin(doc, origin.value());
164 return ffi::detail::ExpectedUnsafe::MoveFromTVMFFIAny<IdDoc>(
174 return ffi::detail::ExpectedUnsafe::MoveFromTVMFFIAny<IdDoc>(vtable_->
alloc_id(
this, hint))
182 return ffi::detail::ExpectedUnsafe::MoveFromTVMFFIAny<ffi::Dict<Var, IdDoc>>(
194 template <
typename T>
196 auto it = extra_config_.find(name);
197 return it == extra_config_.end() ? fallback : (*it).second.as_or_throw<T>();
205 template <
typename T>
207 auto it = extra_state_.find(name);
208 if (it != extra_state_.end())
return (*it).second.as_or_throw<T>();
210 extra_state_.Set(name, value);
218 void SetExtraState(
const ffi::String& name, std::optional<ffi::Any> value) {
219 if (value.has_value()) {
220 extra_state_.Set(name, std::move(value.value()));
222 extra_state_.erase(name);
230 ffi::detail::ExpectedUnsafe::MoveFromTVMFFIAny<void>(vtable_->
begin_var_scope(
this)).value();
239 ffi::detail::ExpectedUnsafe::MoveFromTVMFFIAny<void>(vtable_->
end_var_scope(
this)).value();
249 template <
typename Callback>
254 ffi::detail::ExpectedUnsafe::MoveFromTVMFFIAny<void>(
260 return std::forward<Callback>(callback)();
273 template <
typename T,
typename Callback>
279 ~Scope() { translator->
SetExtraState(key, std::move(saved)); }
281 Scope scope{
this, name, GetOrCreateExtraState<T>(name)};
283 return std::forward<Callback>(callback)();
305 <<
"printer emission requires a collection scope";
314 template <
typename Callback>
319 std::forward<Callback>(callback)();
320 TVM_FFI_CHECK(
doc_scopes_.size() == depth + 1, ValueError)
321 <<
"printer unbalanced Doc collection scopes";
333 ffi::Dict<Doc, ffi::ObjectRef>
GetDocOrigins()
const {
return doc_origins_; }
339 void RecordOrigin(
const Doc& doc,
const ffi::ObjectRef& origin) { doc_origins_.Set(doc, origin); }
347 const ffi::Object* destination =
nullptr);
362 ffi::Map<ffi::String, ffi::Any> extra_config = {})
363 : extra_config_(std::move(extra_config)), vtable_(vtable) {}
375 ffi::Map<ffi::String, ffi::Any> extra_config_;
380 ffi::Dict<ffi::String, ffi::Any> extra_state_;
384 ffi::Dict<Doc, ffi::ObjectRef> doc_origins_;
399 ffi::Array<StmtDoc> statements;
400 for (
const auto& doc : docs) {
402 for (
const auto& stmt : block.value()->stmts) statements.push_back(stmt);
404 statements.push_back(doc.as_or_throw<
StmtDoc>());
430 ffi::Dict<Doc, ffi::ObjectRef>* doc_origins =
nullptr,
431 ffi::Map<ffi::String, ffi::Any> extra_config = {});
437inline constexpr ffi::reflection::AttrKey<FDocTranslate>
kDocTranslate{
"__tvm_doc_translate__"};
445 "__tvm_doc_translate_op_call__"};
449 const ffi::Object* destination) {
450 static ffi::reflection::TypeAttrColumn column(
452 ffi::AnyView attr = column[value.type_index()];
453 if (attr.type_index() == ffi::TypeIndex::kTVMFFIOpaquePtr) {
456 .CallExpected(
this, value, destination)
459 if (attr.type_index() == ffi::TypeIndex::kTVMFFIFunction) {
460 ffi::Any destination_arg =
nullptr;
461 if (destination) destination_arg = ffi::GetRef<ffi::ObjectRef>(destination);
462 return attr.cast<ffi::Function>()
463 .CallExpected<ffi::Optional<ExprDoc>>(
this, value, destination_arg)
466 if (attr.type_index() == ffi::TypeIndex::kTVMFFINone) {
468 if (
auto string = value.as<ffi::String>())
return LiteralDoc::Str(
string.value(), std::nullopt);
469 if (
auto boolean = value.as<
bool>())
return LiteralDoc::Boolean(
boolean.value(), std::nullopt);
470 if (
auto integer = value.as<int64_t>())
return LiteralDoc::Int(integer.value(), std::nullopt);
471 if (
auto floating = value.as<
double>())
473 if (
auto dtype = value.as<DLDataType>())
477 TVM_FFI_THROW(TypeError) << (attr.type_index() == ffi::TypeIndex::kTVMFFINone
478 ? std::string(
"printer has no Doc hook for ") +
480 :
"printer Doc hook must be a native pointer or ffi.Function");
481 TVM_FFI_UNREACHABLE();
#define TVM_TIRX_DLL
Definition base.h:55
Managed reference to TypeObj.
Definition type.h:75
Managed reference to VarObj.
Definition expr.h:571
Eager translation context shared by registered hooks. Hooks construct Docs, use explicit lexical scop...
Definition doc_translator.h:124
ffi::Dict< Doc, ffi::ObjectRef > GetDocOrigins() const
Get the owned Doc-to-original-object associations.
Definition doc_translator.h:333
TVM_FFI_DECLARE_OBJECT_INFO("script.printer.DocTranslator", DocTranslatorObj, ffi::Object)
T GetExtraConfig(const ffi::String &name, T fallback) const
Read a typed extension option.
Definition doc_translator.h:195
ffi::Dict< Var, IdDoc > GetImplicitDefs()
Get the current variable scope's pending definitions.
Definition doc_translator.h:181
void SetExtraState(const ffi::String &name, std::optional< ffi::Any > value)
Replace or remove extension state.
Definition doc_translator.h:218
static constexpr bool _type_mutable
Definition doc_translator.h:352
DocTranslatorObj(const DocTranslatorVTable *vtable, ffi::Map< ffi::String, ffi::Any > extra_config={})
Initialize an engine's translation context.
Definition doc_translator.h:361
void RecordOrigin(const Doc &doc, const ffi::ObjectRef &origin)
Set a Doc's original IR object, replacing any previous association.
Definition doc_translator.h:339
T GetOrCreateExtraState(const ffi::String &name)
Get or initialize typed extension state.
Definition doc_translator.h:206
ffi::List< ffi::List< Doc > > doc_scopes_
Active Doc collections, independent of lexical variable scopes.
Definition doc_translator.h:368
void BeginVarScope()
Begin a lexical variable scope independent of Doc collection.
Definition doc_translator.h:229
ffi::List< Doc > EndDocScope()
Pop the latest Doc collection.
Definition doc_translator.h:294
ffi::Optional< ExprDoc > DefaultTranslate(ffi::AnyView value, const ffi::Object *destination=nullptr)
Dispatch to a registered hook, or reflect an unhandled Type constructor.
Definition doc_translator.h:448
IdDoc AllocId(const ffi::String &hint)
Reserve a fresh identifier without mapping a variable.
Definition doc_translator.h:173
decltype(auto) WithVarScope(Callback &&callback)
Run a callback in a balanced lexical variable scope without collecting Docs.
Definition doc_translator.h:250
void Emit(const Doc &doc, ffi::Optional< ffi::ObjectRef > origin=std::nullopt)
Append a completed Doc and record its optional origin.
Definition doc_translator.h:152
ffi::List< Doc > WithDocScope(Callback &&callback)
Run a callback in a balanced Doc collection scope.
Definition doc_translator.h:315
void EndVarScope()
End the latest naming region, retaining the root region. Explicit local bindings expire....
Definition doc_translator.h:238
decltype(auto) WithExtraStateScope(const ffi::String &name, T value, Callback &&callback)
Run a callback with temporarily replaced typed extension state.
Definition doc_translator.h:274
ffi::Optional< ExprDoc > Translate(ffi::AnyView value, const ffi::Optional< Var > bind_var=std::nullopt)
Translate a value with an optional pre-mapped binding variable.
Definition doc_translator.h:134
TVM_TIRX_DLL ExprDoc DefaultTypeTranslate(const Type &type)
Translate a Type constructor from its reflected fields and fixed defaults.
void BeginDocScope()
Push an empty Doc collection.
Definition doc_translator.h:289
ffi::List< Doc > CurrentScopeDocs() const
Get the current Doc collection without popping it.
Definition doc_translator.h:303
IdDoc VarGetOrAllocId(const Var &var, bool explicit_def)
Reuse or allocate a variable's stable identifier.
Definition doc_translator.h:163
Owning reference to a hook translation context.
Definition doc_translator.h:413
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(DocTranslator, ffi::ObjectRef, DocTranslatorObj)
Initialize a reference to a translation context.
Reference type of DocObj.
Definition doc.h:78
Reference type of ExprDocObj.
Definition doc.h:135
Reference type of IdDocObj.
Definition doc.h:387
static LiteralDoc DataType(DLDataType v, const ffi::Optional< AccessPath > &p)
Create a LiteralDoc to represent string.
Definition doc.h:312
static LiteralDoc Boolean(bool v, const ffi::Optional< AccessPath > &p)
Create a LiteralDoc to represent boolean.
Definition doc.h:288
static LiteralDoc Int(int64_t v, const ffi::Optional< AccessPath > &p)
Create a LiteralDoc to represent integer.
Definition doc.h:270
static LiteralDoc Float(double v, const ffi::Optional< AccessPath > &p)
Create a LiteralDoc to represent float.
Definition doc.h:296
static LiteralDoc None(const ffi::Optional< AccessPath > &p)
Create a LiteralDoc to represent None/null/empty value.
Definition doc.h:262
static LiteralDoc Str(const ffi::String &v, const ffi::Optional< AccessPath > &p)
Create a LiteralDoc to represent string.
Definition doc.h:304
Reference type of StmtBlockDocObj.
Definition doc.h:213
Reference type of StmtDocObj.
Definition doc.h:183
Doc nodes used by the TVMScript printer.
constexpr ffi::reflection::AttrKey< FDocTranslate > kDocTranslateOpCall
Op-specific Call translation hook with the FDocTranslate contract.
Definition doc_translator.h:444
constexpr ffi::reflection::AttrKey< FDocTranslate > kDocTranslate
Type attribute containing a native or packed translation hook.
Definition doc_translator.h:437
TVM_TIRX_DLL Doc DocTranslate(ffi::AnyView ir, ffi::Dict< Doc, ffi::ObjectRef > *doc_origins=nullptr, ffi::Map< ffi::String, ffi::Any > extra_config={})
Translate IR into a complete Doc including declarations and metadata setup.
ffi::reflection::NativeFunctionView< ffi::Optional< ExprDoc >(DocTranslatorObj *translator, ffi::AnyView value, const ffi::Object *destination)> FDocTranslate
Native translation hook with borrowed inputs and an owning result.
Definition doc_translator.h:105
ffi::Array< StmtDoc > ToStmtDocArray(const ffi::List< Doc > &docs)
Convert collected Docs to statements in their original order.
Definition doc_translator.h:398
An object that builds and maintains block scope and StmtSref mapping for Dependence analysis.
Definition analysis.h:41
Engine callbacks borrowed for the translator's lifetime.
Definition doc_translator.h:47
TVMFFIAny(* begin_var_scope)(DocTranslatorObj *translator) noexcept
Begin a lexical variable scope.
Definition doc_translator.h:85
TVMFFIAny(* end_var_scope)(DocTranslatorObj *translator) noexcept
End the current lexical variable scope.
Definition doc_translator.h:91
TVMFFIAny(* translate)(DocTranslatorObj *translator, ffi::AnyView value, const ffi::Object *destination) noexcept
Translate a value with an optional pre-mapped destination.
Definition doc_translator.h:56
TVMFFIAny(* alloc_id)(DocTranslatorObj *translator, ffi::AnyView hint) noexcept
Reserve an identifier without mapping a variable.
Definition doc_translator.h:64
TVMFFIAny(* var_get_or_alloc_id)(DocTranslatorObj *translator, ffi::AnyView var, bool explicit_def) noexcept
Find or allocate a variable's identifier.
Definition doc_translator.h:72
TVMFFIAny(* get_implicit_defs)(DocTranslatorObj *translator) noexcept
Get the current variable scope's pending definitions.
Definition doc_translator.h:79