2016-11-14 54 views
0

我想漂亮打印Clang声明到string,以便打印声明的C/C++代码。我这样做以下列方式:漂亮打印声明在叮铛声字符串

//Generate string and string ostream. 
string stmt; 
raw_string_ostream stream(stmt); 

//Get statement from ASTMatcher and print to ostream. 
auto* statement = result.Nodes.getNodeAs<clang::Expr>(types[VAR_STMT]); 
statement->printPretty(stream, NULL, PrintingPolicy(LangOptions())); 

//Flush ostream buffer. 
stream.flush(); 
cout << statement << endl; 


此代码编译并运行正常。但是,当我运行以下代码时,我得到statement对象的地址打印到string。例如,当我运行此代码,我得到以下的输出:

0x3ccd598 
0x3ccd5b0 
0x3ccd728 
0x3ccdc88 
0x3ccdd08 


是不是真的在Clang的文档很多文档中关于printPretty(...)的那么什么是正确的方式到打印一个statement的代码为字符串?

回答

0

一个解决方案,我发现试图得到这个工作是从Clang developers post从2013年开始

相反的:

//Generate string and string ostream. 
string stmt; 
raw_string_ostream stream(stmt); 

//Get statement from ASTMatcher and print to ostream. 
auto* statement = result.Nodes.getNodeAs<clang::Expr>(types[VAR_STMT]); 
statement->printPretty(stream, NULL, PrintingPolicy(LangOptions())); 

//Flush ostream buffer. 
stream.flush(); 
cout << statement << endl; 

我的代码是现在:

//Get the statement from the ASTMatcher 
auto *statement = result.Nodes.getNodeAs<clang::Expr>(types[VAR_STMT]); 

//Get the source range and manager. 
SourceRange range = statement->getSourceRange(); 
const SourceManager *SM = result.SourceManager; 

//Use LLVM's lexer to get source text. 
llvm::StringRef ref = Lexer::getSourceText(CharSourceRange::getCharRange(range), *SM, LangOptions()); 
cout << ref.str() << endl; 

这种方法似乎工作,虽然我不太确定任何潜在的缺点。

0

由于您的类似变量名称,您似乎会迷惑自己。您有一个变量stmt,它的类型为string,并且您有一个变量statement,(推测)是clang::Stmt *printPretty调用正在修改stream变量,该变量写入stmt,而不是statement。然后你打印statement,指向clang类型的指针。所以很自然地,一个指针类型的cout调用写入指针的地址。

改变你的cout行写出stmt,你会得到你所期望的。