traces: DRY printPosMaybe

This commit is contained in:
Robert Hensing 2023-09-03 14:00:55 +02:00
parent 4c50f5d130
commit f1aeeea32b

View file

@ -155,6 +155,25 @@ static std::string indent(std::string_view indentFirst, std::string_view indentR
return res; return res;
} }
/**
* Print a position, if it is known.
*
* @return true if a position was printed.
*/
static bool printPosMaybe(std::ostream & oss, std::string_view indent, const std::shared_ptr<AbstractPos> & pos) {
bool hasPos = pos && *pos;
if (hasPos) {
oss << "\n" << indent << ANSI_BLUE << "at " ANSI_WARNING << *pos << ANSI_NORMAL << ":";
if (auto loc = pos->getCodeLines()) {
oss << "\n";
printCodeLines(oss, "", *pos, *loc);
oss << "\n";
}
}
return hasPos;
}
std::ostream & showErrorInfo(std::ostream & out, const ErrorInfo & einfo, bool showTrace) std::ostream & showErrorInfo(std::ostream & out, const ErrorInfo & einfo, bool showTrace)
{ {
std::string prefix; std::string prefix;
@ -318,32 +337,15 @@ std::ostream & showErrorInfo(std::ostream & out, const ErrorInfo & einfo, bool s
oss << "\n" << "" << trace.hint.str() << "\n"; oss << "\n" << "" << trace.hint.str() << "\n";
if (trace.pos && *trace.pos) { if (printPosMaybe(oss, ellipsisIndent, trace.pos))
count++; count++;
oss << "\n" << ellipsisIndent << ANSI_BLUE << "at " ANSI_WARNING << *trace.pos << ANSI_NORMAL << ":";
if (auto loc = trace.pos->getCodeLines()) {
oss << "\n";
printCodeLines(oss, "", *trace.pos, *loc);
oss << "\n";
}
}
} }
oss << "\n" << prefix; oss << "\n" << prefix;
} }
oss << einfo.msg << "\n"; oss << einfo.msg << "\n";
if (einfo.errPos && *einfo.errPos) { printPosMaybe(oss, "", einfo.errPos);
oss << "\n" << ANSI_BLUE << "at " ANSI_WARNING << *einfo.errPos << ANSI_NORMAL << ":";
if (auto loc = einfo.errPos->getCodeLines()) {
oss << "\n";
printCodeLines(oss, "", *einfo.errPos, *loc);
oss << "\n";
}
}
auto suggestions = einfo.suggestions.trim(); auto suggestions = einfo.suggestions.trim();
if (!suggestions.suggestions.empty()) { if (!suggestions.suggestions.empty()) {