VioletOil
VioletOil

Reputation: 63

How to print fully qualified Expr in clang?

I'm working on my reflection tool with clang 8.0.1. And right now I need to print Expr with all names fully qualified.

I already tried builtin prettyPrint function with FullyQualifiedName bit set to true. But it still gives incorrect result.

For this piece of code:

namespace math {
   struct Transform {
     float val;
     [[custom_attr(&Transform::public_val)]]
     void foo();
   };
}

It gives me

&Transform::public_val

instead of

&math::Transform::public_val

And for

static_cast<float (*)(const Transform&)>(Transform::static_overload)

as value of custom_attr it gives me

static_cast<float (*)(const math::Transform &)>(Transform::static_overload)

(only Transform::static_over)

Here is my code for printing:

std::string get_string(const Expr *expr, const ASTContext &Context) {
  PrintingPolicy print_policy(Context.getLangOpts());
  print_policy.FullyQualifiedName = 1;
  print_policy.SuppressScope = 0;
  print_policy.SuppressUnwrittenScope = 0;
  std::string expr_string;
  llvm::raw_string_ostream stream(expr_string);
  expr->printPretty(stream, nullptr, print_policy);
  stream.flush();
  return expr_string;
}

Upvotes: 1

Views: 1220

Answers (1)

VioletOil
VioletOil

Reputation: 63

All I needed is to specify PrintCanonicalTypes flag. Here is function for getting string from Expr:

std::string getFullyQualified(const Expr *expr,
                                          const ASTContext &Context) {
  static PrintingPolicy print_policy(Context.getLangOpts());
  print_policy.FullyQualifiedName = 1;
  print_policy.SuppressScope = 0;
  print_policy.PrintCanonicalTypes = 1;


  std::string expr_string;
  llvm::raw_string_ostream stream(expr_string);
  expr->printPretty(stream, nullptr, print_policy);
  stream.flush();
  return expr_string;
}

Upvotes: 1

Related Questions