tvm
Loading...
Searching...
No Matches
doc_translator.h
Go to the documentation of this file.
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 */
23#ifndef TVM_SCRIPT_PRINTER_DOC_TRANSLATOR_H_
24#define TVM_SCRIPT_PRINTER_DOC_TRANSLATOR_H_
25
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>
31#include <tvm/ir/expr.h>
33
34#include <optional>
35#include <utility>
36
37namespace tvm {
38
39namespace script {
40namespace printer {
41
42class DocTranslatorObj;
43
56 TVMFFIAny (*translate)(DocTranslatorObj* translator, ffi::AnyView value,
57 const ffi::Object* destination) noexcept;
64 TVMFFIAny (*alloc_id)(DocTranslatorObj* translator, ffi::AnyView hint) noexcept;
72 TVMFFIAny (*var_get_or_alloc_id)(DocTranslatorObj* translator, ffi::AnyView var,
73 bool explicit_def) noexcept;
79 TVMFFIAny (*get_implicit_defs)(DocTranslatorObj* translator) noexcept;
85 TVMFFIAny (*begin_var_scope)(DocTranslatorObj* translator) noexcept;
91 TVMFFIAny (*end_var_scope)(DocTranslatorObj* translator) noexcept;
92};
93
104using FDocTranslate = ffi::reflection::NativeFunctionView<ffi::Optional<ExprDoc>(
105 DocTranslatorObj* translator, ffi::AnyView value, const ffi::Object* destination)>;
106
124class DocTranslatorObj : public ffi::Object {
125 public:
134 ffi::Optional<ExprDoc> Translate(ffi::AnyView value,
135 const ffi::Optional<Var> bind_var = std::nullopt) {
136 auto result = ffi::detail::ExpectedUnsafe::MoveFromTVMFFIAny<ffi::Optional<ExprDoc>>(
137 vtable_->translate(this, value,
138 bind_var.has_value() ? bind_var.value().get() : nullptr))
139 .value();
140 if (result.has_value()) {
141 if (const auto* origin = value.as<ffi::Object>()) {
142 RecordOrigin(result.value(), ffi::GetRef<ffi::ObjectRef>(origin));
143 }
144 }
145 return result;
146 }
152 void Emit(const Doc& doc, ffi::Optional<ffi::ObjectRef> origin = std::nullopt) {
153 CurrentScopeDocs().push_back(doc);
154 if (origin.has_value()) RecordOrigin(doc, origin.value());
155 }
156
163 IdDoc VarGetOrAllocId(const Var& var, bool explicit_def) {
164 return ffi::detail::ExpectedUnsafe::MoveFromTVMFFIAny<IdDoc>(
165 vtable_->var_get_or_alloc_id(this, var, explicit_def))
166 .value();
167 }
173 IdDoc AllocId(const ffi::String& hint) {
174 return ffi::detail::ExpectedUnsafe::MoveFromTVMFFIAny<IdDoc>(vtable_->alloc_id(this, hint))
175 .value();
176 }
181 ffi::Dict<Var, IdDoc> GetImplicitDefs() {
182 return ffi::detail::ExpectedUnsafe::MoveFromTVMFFIAny<ffi::Dict<Var, IdDoc>>(
183 vtable_->get_implicit_defs(this))
184 .value();
185 }
186
194 template <typename T>
195 T GetExtraConfig(const ffi::String& name, T fallback) const {
196 auto it = extra_config_.find(name);
197 return it == extra_config_.end() ? fallback : (*it).second.as_or_throw<T>();
198 }
205 template <typename T>
206 T GetOrCreateExtraState(const ffi::String& name) {
207 auto it = extra_state_.find(name);
208 if (it != extra_state_.end()) return (*it).second.as_or_throw<T>();
209 T value{};
210 extra_state_.Set(name, value);
211 return value;
212 }
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()));
221 } else {
222 extra_state_.erase(name);
223 }
224 }
225
230 ffi::detail::ExpectedUnsafe::MoveFromTVMFFIAny<void>(vtable_->begin_var_scope(this)).value();
231 }
238 void EndVarScope() {
239 ffi::detail::ExpectedUnsafe::MoveFromTVMFFIAny<void>(vtable_->end_var_scope(this)).value();
240 }
249 template <typename Callback>
250 decltype(auto) WithVarScope(Callback&& callback) {
251 struct Scope {
252 DocTranslatorObj* translator;
253 ~Scope() {
254 ffi::detail::ExpectedUnsafe::MoveFromTVMFFIAny<void>(
255 translator->vtable_->end_var_scope(translator));
256 }
257 };
259 Scope scope{this};
260 return std::forward<Callback>(callback)();
261 }
262
273 template <typename T, typename Callback>
274 decltype(auto) WithExtraStateScope(const ffi::String& name, T value, Callback&& callback) {
275 struct Scope {
276 DocTranslatorObj* translator;
277 ffi::String key;
278 T saved;
279 ~Scope() { translator->SetExtraState(key, std::move(saved)); }
280 };
281 Scope scope{this, name, GetOrCreateExtraState<T>(name)};
282 SetExtraState(scope.key, std::move(value));
283 return std::forward<Callback>(callback)();
284 }
285
289 void BeginDocScope() { doc_scopes_.push_back(ffi::List<Doc>()); }
294 ffi::List<Doc> EndDocScope() {
295 auto docs = CurrentScopeDocs();
296 doc_scopes_.pop_back();
297 return docs;
298 }
303 ffi::List<Doc> CurrentScopeDocs() const {
304 TVM_FFI_CHECK(!doc_scopes_.empty(), ValueError)
305 << "printer emission requires a collection scope";
306 return doc_scopes_.back();
307 }
314 template <typename Callback>
315 ffi::List<Doc> WithDocScope(Callback&& callback) {
316 size_t depth = doc_scopes_.size();
318 try {
319 std::forward<Callback>(callback)();
320 TVM_FFI_CHECK(doc_scopes_.size() == depth + 1, ValueError)
321 << "printer unbalanced Doc collection scopes";
322 return EndDocScope();
323 } catch (...) {
324 while (doc_scopes_.size() > depth) doc_scopes_.pop_back();
325 throw;
326 }
327 }
328
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); }
346 ffi::Optional<ExprDoc> DefaultTranslate(ffi::AnyView value,
347 const ffi::Object* destination = nullptr);
348
351
352 static constexpr bool _type_mutable = true;
353 TVM_FFI_DECLARE_OBJECT_INFO("script.printer.DocTranslator", DocTranslatorObj, ffi::Object);
354
355 protected:
361 explicit DocTranslatorObj(const DocTranslatorVTable* vtable,
362 ffi::Map<ffi::String, ffi::Any> extra_config = {})
363 : extra_config_(std::move(extra_config)), vtable_(vtable) {}
364
368 ffi::List<ffi::List<Doc>> doc_scopes_;
369
370 private:
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_;
388 const DocTranslatorVTable* vtable_;
389};
390
398inline ffi::Array<StmtDoc> ToStmtDocArray(const ffi::List<Doc>& docs) {
399 ffi::Array<StmtDoc> statements;
400 for (const auto& doc : docs) {
401 if (auto block = doc.as<StmtBlockDoc>()) {
402 for (const auto& stmt : block.value()->stmts) statements.push_back(stmt);
403 } else {
404 statements.push_back(doc.as_or_throw<StmtDoc>());
405 }
406 }
407 return statements;
408}
409
413class DocTranslator : public ffi::ObjectRef {
414 public:
420};
421
430 ffi::Dict<Doc, ffi::ObjectRef>* doc_origins = nullptr,
431 ffi::Map<ffi::String, ffi::Any> extra_config = {});
432
433namespace type_attr {
437inline constexpr ffi::reflection::AttrKey<FDocTranslate> kDocTranslate{"__tvm_doc_translate__"};
438} // namespace type_attr
439
440namespace op_attr {
444inline constexpr ffi::reflection::AttrKey<FDocTranslate> kDocTranslateOpCall{
445 "__tvm_doc_translate_op_call__"};
446} // namespace op_attr
447
448inline ffi::Optional<ExprDoc> DocTranslatorObj::DefaultTranslate(ffi::AnyView value,
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) {
454 return type_attr::kDocTranslate.ValueFrom(attr)
455 .value()
456 .CallExpected(this, value, destination)
457 .value();
458 }
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)
464 .value();
465 }
466 if (attr.type_index() == ffi::TypeIndex::kTVMFFINone) {
467 if (value == nullptr) return LiteralDoc::None(std::nullopt);
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>())
472 return LiteralDoc::Float(floating.value(), std::nullopt);
473 if (auto dtype = value.as<DLDataType>())
474 return LiteralDoc::DataType(dtype.value(), std::nullopt);
475 if (auto type = value.as<Type>()) return DefaultTypeTranslate(type.value());
476 }
477 TVM_FFI_THROW(TypeError) << (attr.type_index() == ffi::TypeIndex::kTVMFFINone
478 ? std::string("printer has no Doc hook for ") +
479 value.GetTypeKey()
480 : "printer Doc hook must be a native pointer or ffi.Function");
481 TVM_FFI_UNREACHABLE();
482}
483
484} // namespace printer
485} // namespace script
486} // namespace tvm
487
488#endif // TVM_SCRIPT_PRINTER_DOC_TRANSLATOR_H_
Base expr nodes in TVM.
#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