gemini-code-assist[bot] commented on code in PR #19940:
URL: https://github.com/apache/tvm/pull/19940#discussion_r3523499925
##########
src/script/printer/doc_printer/python_doc_printer.cc:
##########
@@ -394,6 +396,19 @@ void PythonDocPrinter::PrintTypedDoc(const LiteralDoc&
doc) {
}
}
+void PythonDocPrinter::PrintTypedDoc(const ExprStringDoc& doc) {
+ this->output_ << '"';
+ size_t start_pos = this->output_.tellp();
+ this->PrintDoc(doc->value);
+ std::string output = this->output_.str();
+ std::string value = output.substr(start_pos);
+ TVM_FFI_ICHECK(value.find('\n') == std::string::npos)
+ << "An expression rendered inside a Python string literal must be one
line";
+ this->output_.str(output.substr(0, start_pos));
+ this->output_.seekp(start_pos);
+ this->output_ << support::StrEscape(value) << '"';
+}
Review Comment:

### Performance Bottleneck and Potential Underline Bug in `ExprStringDoc`
Printing\n\nCalling `this->output_.str()` copies the **entire** accumulated
output string so far. In large TVMScript files (e.g., large Relax or TIR models
with many shape variables), calling this repeatedly for every `ExprStringDoc`
results in quadratic $O(N^2)$ time and memory complexity, where $N$ is the size
of the generated script.\n\nAdditionally, calling `PrintDoc(doc->value)` on the
main printer can register incorrect source path underline spans (relative to
the un-escaped positions) in `current_underline_candidates_`, which are never
cleared or adjusted, potentially leading to misaligned or misplaced diagnostic
underlines.\n\n### Solution\nWe can instantiate a temporary, isolated
`PythonDocPrinter` with a default `PrinterConfig` to print the sub-expression.
This completely avoids copying the main output buffer and ensures any recorded
source path spans are safely discarded when the temporary printer
goes out of scope.
```c
void PythonDocPrinter::PrintTypedDoc(const ExprStringDoc& doc) {
PythonDocPrinter sub_printer(PrinterConfig());
sub_printer.PrintDoc(doc->value);
std::string value = sub_printer.output_.str();
TVM_FFI_ICHECK(value.find('\\n') == std::string::npos)
<< "An expression rendered inside a Python string literal must be one
line";
this->output_ << '"' << support::StrEscape(value) << '"';
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]