[clangd] Implement hover for string literals
authorv1nh1shungry <v1nh1shungry@outlook.com>
Thu, 10 Nov 2022 11:15:41 +0000 (12:15 +0100)
committerKadir Cetinkaya <kadircet@google.com>
Thu, 10 Nov 2022 11:16:05 +0000 (12:16 +0100)
Show string-literals' type and size in a hover card

Issue related: https://github.com/clangd/clangd/issues/1016

Reviewed By: kadircet

Differential Revision: https://reviews.llvm.org/D137650

clang-tools-extra/clangd/Hover.cpp
clang-tools-extra/clangd/unittests/HoverTests.cpp

index 555cefd..d3dc396 100644 (file)
@@ -777,6 +777,17 @@ HoverInfo getDeducedTypeHoverContents(QualType QT, const syntax::Token &Tok,
   return HI;
 }
 
+HoverInfo getStringLiteralContents(const StringLiteral *SL,
+                                   const PrintingPolicy &PP) {
+  HoverInfo HI;
+
+  HI.Name = "string-literal";
+  HI.Size = (SL->getLength() + 1) * SL->getCharByteWidth();
+  HI.Type = SL->getType().getAsString(PP).c_str();
+
+  return HI;
+}
+
 bool isLiteral(const Expr *E) {
   // Unfortunately there's no common base Literal classes inherits from
   // (apart from Expr), therefore these exclusions.
@@ -785,7 +796,7 @@ bool isLiteral(const Expr *E) {
          llvm::isa<CXXNullPtrLiteralExpr>(E) ||
          llvm::isa<FixedPointLiteral>(E) || llvm::isa<FloatingLiteral>(E) ||
          llvm::isa<ImaginaryLiteral>(E) || llvm::isa<IntegerLiteral>(E) ||
-         llvm::isa<StringLiteral>(E) || llvm::isa<UserDefinedLiteral>(E);
+         llvm::isa<UserDefinedLiteral>(E);
 }
 
 llvm::StringLiteral getNameForExpr(const Expr *E) {
@@ -810,6 +821,9 @@ llvm::Optional<HoverInfo> getHoverContents(const Expr *E, ParsedAST &AST,
     return llvm::None;
 
   HoverInfo HI;
+  // Print the type and the size for string literals
+  if (const StringLiteral *SL = dyn_cast<StringLiteral>(E))
+    return getStringLiteralContents(SL, PP);
   // For `this` expr we currently generate hover with pointee type.
   if (const CXXThisExpr *CTE = dyn_cast<CXXThisExpr>(E))
     return getThisExprHoverContents(CTE, AST.getASTContext(), PP);
index 9f64def..4b1dbdf 100644 (file)
@@ -1300,7 +1300,6 @@ TEST(Hover, NoHover) {
       "auto x = ^42.0i;",
       "auto x = ^42;",
       "auto x = ^nullptr;",
-      "auto x = ^\"asdf\";",
   };
 
   for (const auto &Test : Tests) {
@@ -1326,6 +1325,12 @@ TEST(Hover, All) {
          HI.Type = "char";
          HI.Value = "65 (0x41)";
        }},
+      {"auto s = ^[[\"Hello, world!\"]]; // string literal",
+       [](HoverInfo &HI) {
+         HI.Name = "string-literal";
+         HI.Size = 14;
+         HI.Type = "const char[14]";
+       }},
       {
           R"cpp(// Local variable
             int main() {