Monday, May 9, 2016

Demangling Swift With Swift

Matt Gallagher (tweet):

I rewrote the C++ implementation of Swift’s Demangle.cpp in Swift. My reimplementation is completely standalone and can be dropped directly into any Swift project.

[…]

From the first line, we can see a difference between the Swift and C++ versions. Swift has a standard set of protocols and constraints for defining data providers, so it makes sense to use them. C++ could use a template parameter to define the data provider but since C++ lacks an equivalent to Swift’s protocol constraints and lacks a corresponding set of standard behaviors, the mulitple constraints for the data provider would be a confusing black box thrust upon any user of NameSource – likely manifesting in weird errors in internal headers if any requirements were not met.

[…]

But the most visible difference in adopting Swift error handling is a significant reduction in code size. Switching to Swift error handling immediately eliminated 149 return nullptr early exit lines from the C++ version. Furthermore, Swift can happily exit from a function in the middle of an expression when a parse attempt fails instead of needing to break expressions into multiple pieces either side of early exits.

[…]

Many large C++ projects – Swift included – are compiled with C++ exceptions entirely disabled. Why deliberately remove a potentially useful feature from the language? The Swift developers answer this question when considering error handling options for Swift[…]

[…]

This shows the advantage of a two value switch being idiomatic in Swift: compared to the strange series of #define, if and switch constructions in C++, this is clear, simple and readable.

He downplays the usefulness of the project, focusing on the code comparison with C++. However, I think the code is actually very useful because I want to record readable stack traces when throwing or propagating an error.

Update (2016-05-09): Cédric Luthi mentions the built-in _stdlib_demangleName(), but I think it’s private API.

Comments RSS · Twitter

Leave a Comment