[llvm] [FileCheck] Improve printing variables with escapes (PR #145865)

Mészáros Gergely via llvm-commits llvm-commits at lists.llvm.org
Thu Jun 26 03:57:06 PDT 2025


================
@@ -274,14 +274,55 @@ Expected<std::string> NumericSubstitution::getResult() const {
   return Format.getMatchingString(*EvaluatedValue);
 }
 
-Expected<std::string> StringSubstitution::getResult() const {
+Expected<std::string> NumericSubstitution::getResultForDiagnostics() const {
+  // The "regex" returned by getResultRegex() is just a numeric value
+  // like '42', '0x2A', '-17', 'DEADBEEF' etc. This is already suitable for use in diagnostics.
+  Expected<std::string> Literal = getResultRegex();
+  if (!Literal)
+    return Literal;
+
+  return "\"" + std::move(*Literal) + "\"";
+}
+
+Expected<std::string> StringSubstitution::getResultRegex() const {
   // Look up the value and escape it so that we can put it into the regex.
   Expected<StringRef> VarVal = Context->getPatternVarValue(FromStr);
   if (!VarVal)
     return VarVal.takeError();
   return Regex::escape(*VarVal);
 }
 
+Expected<std::string> StringSubstitution::getResultForDiagnostics() const {
+    Expected<StringRef> VarVal = Context->getPatternVarValue(FromStr);
+    if (!VarVal)
+      return VarVal.takeError();
+
+    std::string Result;
+    Result.reserve(VarVal->size() + 2);
+    raw_string_ostream OS(Result);
+
+    OS << '"';
+    // Escape the string if it contains any characters that
+    // make it hard to read, such as tabs, newlines, quotes, and non-printable characters.
+    // Note that we do not include backslashes in this set, because they are
+    // common in Windows paths and escaping them would make the output
+    // harder to read.
+    // However, when we do escape, backslashes are escaped as well,
+    // otherwise the output would be ambiguous.
+    const bool NeedsEscaping = llvm::any_of(*VarVal, [](char C) {
+      return C == '\t' || C == '\n' || C == '"' || !isPrint(C);
----------------
Maetveis wrote:

I can make it `!isPrint || C == '"'`
Turns out `isPrint` only includes space from the whitespace characters.
(`\f` is 0xc and `\v` is 0xb.)

https://github.com/llvm/llvm-project/pull/145865


More information about the llvm-commits mailing list