[cfe-dev] base type name strings

Douglas Gregor dgregor at apple.com
Tue Feb 15 13:21:22 PST 2011


On Feb 15, 2011, at 12:51 PM, John Thompson wrote:

> Hi,
>  
> Given a QualType that has a class, struct, or enum name in there somewhere, I'd like to get a string that just contains the leaf type name, and a string that contains just the qualified type name.
>  
> For example, given a QualType whose getAsString() call returns "class namespace::classname *&", I'd like to get a string like "classname" and a string like "namespace::classname".
>  
> At present I'm doing it very naively like this:
>  
> //...
> std::string baseName = LuaBindingsConsumer::StripToBaseName(type.GetAsString());
> std::string qualifiedBaseName = LuaBindingsConsumer::StripToQualifiedName(type.GetAsString());
> //...
> 
>   // Strip a type string of everything but the base type name.
> std::string LuaBindingsConsumer::StripToBaseName(std::string typeName) {
>   typeName = StripToQualifiedName(typeName);
>   size_t index;
>   while ((index = typeName.find_first_of("::")) < typeName.length())
>     typeName = typeName.substr(index + 2);
>   return typeName;
> }
>   // Strip a type string of everything but the qualified base type name.
> std::string LuaBindingsConsumer::StripToQualifiedName(std::string typeName) {
>   size_t index;
>   if (typeName.compare(0, 6, "class ") == 0)
>     typeName = typeName.substr(6);
>   else if (typeName.compare(0, 7, "struct ") == 0)
>     typeName = typeName.substr(7);
>   else if (typeName.compare(0, 5, "enum ") == 0)
>     typeName = typeName.substr(5);
>   while ((index = typeName.find_first_of('*')) < typeName.length())
>     typeName = typeName.substr(0, index);
>   while ((index = typeName.find_first_of('&')) < typeName.length())
>     typeName = typeName.substr(0, index);
>   while ((index = typeName.find_first_of('[')) < typeName.length())
>     typeName = typeName.substr(0, index);
>   while ((index = typeName.find_first_of('{')) < typeName.length())
>     typeName = typeName.substr(0, index);
>   while ((index = typeName.find_first_of(' ')) < typeName.length())
>     typeName = typeName.substr(0, index);
>   while ((index = typeName.find_first_of('\t')) < typeName.length())
>     typeName = typeName.substr(0, index);
>   return typeName;
> }
> 
> but there must be a better way.

There's no reason to view this as a string-manipulation problem. Just look at the structure of the type and strip off all of the information you don't care about. For example, match PointerType nodes and pull out the pointee, match ArrayType nodes and pull out the element type, etc.

	- Doug

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20110215/7bd52224/attachment.html>


More information about the cfe-dev mailing list